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
|
---|---|---|---|---|---|
15,009,022 |
I was reading this <http://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.80).aspx> but I am wondering, what is the difference between or benefit of using interfaces as opposed to simply creating a class with properties and adding it to your class via "`using MyClass.cs`?" It seems like either way you have to instantiate the method or property class...
Thanks for your advice.
|
2013/02/21
|
[
"https://Stackoverflow.com/questions/15009022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477388/"
] |
An interface is *not* so you can use the interface's objects. It's, rather, so that you *must* **create** those objects.
|
I don't see how the two are even similar. An interface defines how your code is used by clients. The using keyword (which should be followed by a namespace name rather than a file name) simply lets you use objects in that namespace without prefixing them with the entire namespace each time.
A more common question is what is the difference between implementing an interface and deriving from a class. Maybe that is what you were trying to ask. That question has been covered pretty extensively elsewhere.
|
15,009,022 |
I was reading this <http://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.80).aspx> but I am wondering, what is the difference between or benefit of using interfaces as opposed to simply creating a class with properties and adding it to your class via "`using MyClass.cs`?" It seems like either way you have to instantiate the method or property class...
Thanks for your advice.
|
2013/02/21
|
[
"https://Stackoverflow.com/questions/15009022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477388/"
] |
An interface is *not* so you can use the interface's objects. It's, rather, so that you *must* **create** those objects.
|
Interface only contains the signature of your logic. It must be implemented fully in your child class. We use "using" clause when we want to include namespace which is different then the namespace of your project, but if your class or interface is in the same namespace you don't need to use "using" clause.
You can inherit your child class with interfaces and make your code more flexible.
An example of it would be:
```
public interface IClown
{
string FunnyThingIHave { get; }
void Honk();
}
public class TallGuy : IClown
{
public string FunnyThingIHave {
get { return "big shoes"; }
}
public void Honk() {
MessageBox.Show("Honk honk!");
}
}
public class Joker:IClown
{
public string FunnyThingIHave
{
get {return "I have a clown car"}
}
public void Honk()
{
MessageBox.Show("Honk Bonk");
}
}
public class FunnyClowns
{
Joker joker = new Joker();
TallGuy tguy = new TallGuy();
string WhichFunnyThingIWant(IClown clownType)
{
clownType.Honk();
}
}
```
Now what this is doing is defining a clown interface and then defining two child classes for it then a third class can dynamically call the clowntype object of IClown. This is a simple example but this kind of logic can be applied in many other situations. That is where interfaces can be really helpful. I hope this helps..
|
6,924,048 |
I use Richfaces in my Project and I really like the Kickass Code Completion in IntelliJ. But somehow I am not able to autocomplete the Richfaces Stuff. Here is my relevant part of my XHTML file:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
template="layout/template.xhtml">
```
IntelliJ tells me, that it can not fetch the external ressource, because there is no XML at the Richfaces URL. All other Code Completions work. Has someone an idea how to solve this?
|
2011/08/03
|
[
"https://Stackoverflow.com/questions/6924048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441467/"
] |
Here is the tutorial links:
<http://blog.maxaller.name/2010/05/attaching-a-sticky-headerfooter-to-an-android-listview/>
<http://www.vogella.de/articles/AndroidListView/article.html>
<http://www.vogella.de/articles/AndroidListView/article.html#headerfooter>
|
You may need to add in your xml two `TextViews`. One before your `ListView`, the other one, right under the `ListView`.
|
6,924,048 |
I use Richfaces in my Project and I really like the Kickass Code Completion in IntelliJ. But somehow I am not able to autocomplete the Richfaces Stuff. Here is my relevant part of my XHTML file:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
template="layout/template.xhtml">
```
IntelliJ tells me, that it can not fetch the external ressource, because there is no XML at the Richfaces URL. All other Code Completions work. Has someone an idea how to solve this?
|
2011/08/03
|
[
"https://Stackoverflow.com/questions/6924048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441467/"
] |
Here is the tutorial links:
<http://blog.maxaller.name/2010/05/attaching-a-sticky-headerfooter-to-an-android-listview/>
<http://www.vogella.de/articles/AndroidListView/article.html>
<http://www.vogella.de/articles/AndroidListView/article.html#headerfooter>
|
here comes a snippet for the ListView with header+footer;
```
<LinearLayout android:id="@+id/lay_listitems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/white"
>
<TextView android:id="@+id/listview_items_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"
android:textStyle="normal"
android:gravity="center_horizontal"
android:textColor="@drawable/titlecolor"
android:singleLine="true"
android:visibility="visible"
android:text=" --- HEADER ---"
/>
<ListView android:id="@+id/listview_items"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"
android:smoothScrollbar="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:dividerHeight="1dip"
android:divider="@drawable/ltgray"
android:layout_gravity="center"
android:gravity="center"
/>
<TextView android:id="@+id/listview_items_footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"
android:textStyle="italic"
android:gravity="center_horizontal"
android:textColor="@drawable/normaltextcolor"
android:singleLine="true"
android:visibility="visible"
android:text=" --- FOOTER --- "
/>
</LinearLayout>
```
p.s. as an extra, custom colors can be added into colors.xml as below
```
<drawable name="titlecolor">#83a4cd</drawable>
<drawable name="normaltextcolor">#83a4cd</drawable>
<drawable name="gray">#585858</drawable>
<drawable name="ltgray">#BDBDBD</drawable>
<drawable name="extraltgray">#F2F2F2</drawable>
```
|
6,924,048 |
I use Richfaces in my Project and I really like the Kickass Code Completion in IntelliJ. But somehow I am not able to autocomplete the Richfaces Stuff. Here is my relevant part of my XHTML file:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
template="layout/template.xhtml">
```
IntelliJ tells me, that it can not fetch the external ressource, because there is no XML at the Richfaces URL. All other Code Completions work. Has someone an idea how to solve this?
|
2011/08/03
|
[
"https://Stackoverflow.com/questions/6924048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441467/"
] |
Here is the tutorial links:
<http://blog.maxaller.name/2010/05/attaching-a-sticky-headerfooter-to-an-android-listview/>
<http://www.vogella.de/articles/AndroidListView/article.html>
<http://www.vogella.de/articles/AndroidListView/article.html#headerfooter>
|
This may be late but hope this may help someone. :-)
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:text="Header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@android:id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="Footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</LinearLayout>
```
|
6,924,048 |
I use Richfaces in my Project and I really like the Kickass Code Completion in IntelliJ. But somehow I am not able to autocomplete the Richfaces Stuff. Here is my relevant part of my XHTML file:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
template="layout/template.xhtml">
```
IntelliJ tells me, that it can not fetch the external ressource, because there is no XML at the Richfaces URL. All other Code Completions work. Has someone an idea how to solve this?
|
2011/08/03
|
[
"https://Stackoverflow.com/questions/6924048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441467/"
] |
You may need to add in your xml two `TextViews`. One before your `ListView`, the other one, right under the `ListView`.
|
This may be late but hope this may help someone. :-)
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:text="Header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@android:id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="Footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</LinearLayout>
```
|
6,924,048 |
I use Richfaces in my Project and I really like the Kickass Code Completion in IntelliJ. But somehow I am not able to autocomplete the Richfaces Stuff. Here is my relevant part of my XHTML file:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
template="layout/template.xhtml">
```
IntelliJ tells me, that it can not fetch the external ressource, because there is no XML at the Richfaces URL. All other Code Completions work. Has someone an idea how to solve this?
|
2011/08/03
|
[
"https://Stackoverflow.com/questions/6924048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441467/"
] |
here comes a snippet for the ListView with header+footer;
```
<LinearLayout android:id="@+id/lay_listitems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/white"
>
<TextView android:id="@+id/listview_items_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"
android:textStyle="normal"
android:gravity="center_horizontal"
android:textColor="@drawable/titlecolor"
android:singleLine="true"
android:visibility="visible"
android:text=" --- HEADER ---"
/>
<ListView android:id="@+id/listview_items"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"
android:smoothScrollbar="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:dividerHeight="1dip"
android:divider="@drawable/ltgray"
android:layout_gravity="center"
android:gravity="center"
/>
<TextView android:id="@+id/listview_items_footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"
android:textStyle="italic"
android:gravity="center_horizontal"
android:textColor="@drawable/normaltextcolor"
android:singleLine="true"
android:visibility="visible"
android:text=" --- FOOTER --- "
/>
</LinearLayout>
```
p.s. as an extra, custom colors can be added into colors.xml as below
```
<drawable name="titlecolor">#83a4cd</drawable>
<drawable name="normaltextcolor">#83a4cd</drawable>
<drawable name="gray">#585858</drawable>
<drawable name="ltgray">#BDBDBD</drawable>
<drawable name="extraltgray">#F2F2F2</drawable>
```
|
This may be late but hope this may help someone. :-)
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:text="Header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@android:id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="Footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</LinearLayout>
```
|
40,742,033 |
I have this table:
```
Profile_id Phase_id order
30087853 30021628 525
30087853 30021635 523
30087853 30021673 122
30087853 30021703 521
```
from the above I would like to get profile\_id along with this phase\_id, which has lowest order\_num, so the outcome will be like:
```
Profile_id Phase_id order
30087853 30021673 122
```
|
2016/11/22
|
[
"https://Stackoverflow.com/questions/40742033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7194407/"
] |
You didn't specify your DBMS so this is standard SQL:
```
select profile_id, phase_id, "order"
from (
select profile_id, phase_id, "order",
row_number() over (partition by profile_id order by "order") as rn
from the_table
) t
where rn = 1;
```
Online example: <http://rextester.com/MAUV44954>
|
CREATE TABLE #table(Profile\_id INT, Phase\_id INT, \_order INT)
INSERT INTO #table(Profile\_id , Phase\_id , \_order )
SELECT 30087853,30021628,525 UNION ALL
SELECT 30087853,30021635,523 UNION ALL
SELECT 30087853,30021673,122 UNION ALL
SELECT 30087853,30021703,521
SELECT \*
FROM #table T1
JOIN
(
SELECT Profile\_id ProfileId, MIN(\_order) [order]
FROM #table
GROUP BY Profile\_id
) A ON T1.Profile\_id = ProfileId AND T1.\_order = [order]
|
40,742,033 |
I have this table:
```
Profile_id Phase_id order
30087853 30021628 525
30087853 30021635 523
30087853 30021673 122
30087853 30021703 521
```
from the above I would like to get profile\_id along with this phase\_id, which has lowest order\_num, so the outcome will be like:
```
Profile_id Phase_id order
30087853 30021673 122
```
|
2016/11/22
|
[
"https://Stackoverflow.com/questions/40742033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7194407/"
] |
Without a sub-query or self-join you can use also this one:
```
SELECT Profile_id, MIN("order") as "order",
MIN(Phase_id) KEEP (DENSE_RANK FIRST ORDER BY "order") AS Phase_id
FROM your_table
GROUP BY Profile_id;
```
|
CREATE TABLE #table(Profile\_id INT, Phase\_id INT, \_order INT)
INSERT INTO #table(Profile\_id , Phase\_id , \_order )
SELECT 30087853,30021628,525 UNION ALL
SELECT 30087853,30021635,523 UNION ALL
SELECT 30087853,30021673,122 UNION ALL
SELECT 30087853,30021703,521
SELECT \*
FROM #table T1
JOIN
(
SELECT Profile\_id ProfileId, MIN(\_order) [order]
FROM #table
GROUP BY Profile\_id
) A ON T1.Profile\_id = ProfileId AND T1.\_order = [order]
|
40,742,033 |
I have this table:
```
Profile_id Phase_id order
30087853 30021628 525
30087853 30021635 523
30087853 30021673 122
30087853 30021703 521
```
from the above I would like to get profile\_id along with this phase\_id, which has lowest order\_num, so the outcome will be like:
```
Profile_id Phase_id order
30087853 30021673 122
```
|
2016/11/22
|
[
"https://Stackoverflow.com/questions/40742033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7194407/"
] |
You didn't specify your DBMS so this is standard SQL:
```
select profile_id, phase_id, "order"
from (
select profile_id, phase_id, "order",
row_number() over (partition by profile_id order by "order") as rn
from the_table
) t
where rn = 1;
```
Online example: <http://rextester.com/MAUV44954>
|
Without a sub-query or self-join you can use also this one:
```
SELECT Profile_id, MIN("order") as "order",
MIN(Phase_id) KEEP (DENSE_RANK FIRST ORDER BY "order") AS Phase_id
FROM your_table
GROUP BY Profile_id;
```
|
63,581,399 |
I have a string column (`cmpstn_val`) which has values with decimal points embedded - like this:
```
cust_nm | cmpstn_val
--------+------------------------
John | 123.384501928340000
Mark | 443.827345985
Peter | 145.320004
Mike | 678.293845012000000010
```
Firstly, I have to consider only the part that appears **after** the dot (.) and secondly, I have to find out which of these values has the **highest number of digits** present after the dot (.), and print the corresponding record which contains that value.
Hence, for the example presented above the SQL query should return the last value (i.e. '`678.293845012000000010`') since it has the highest number of digits/characters after the decimal point.
```
cust_nm | cmpstn_val
--------+------------------------
Mike | 678.293845012000000010
```
|
2020/08/25
|
[
"https://Stackoverflow.com/questions/63581399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14029222/"
] |
One method is:
```
select len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) as num_digits_after_dot
```
If you want the longest one:
```
select top (1) t.*
from t
order by len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) desc;
```
[Here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=52c6fa990dc7ccbd8f0b2c6145358160) is a db<>fiddle.
|
Using `parsename` with `len`. This one works if the string after the decimal is at most 128 characters.
```
select top (1) *
from t
order by len(parsename(cmpstn_val,1)) desc;
```
This one is probably more reliable since the string before decimal looks more likely to be shorter
```
select top (1) *
from t
order by len(cmpstn_val)-len(parsename(cmpstn_val,2)) desc;
```
|
63,581,399 |
I have a string column (`cmpstn_val`) which has values with decimal points embedded - like this:
```
cust_nm | cmpstn_val
--------+------------------------
John | 123.384501928340000
Mark | 443.827345985
Peter | 145.320004
Mike | 678.293845012000000010
```
Firstly, I have to consider only the part that appears **after** the dot (.) and secondly, I have to find out which of these values has the **highest number of digits** present after the dot (.), and print the corresponding record which contains that value.
Hence, for the example presented above the SQL query should return the last value (i.e. '`678.293845012000000010`') since it has the highest number of digits/characters after the decimal point.
```
cust_nm | cmpstn_val
--------+------------------------
Mike | 678.293845012000000010
```
|
2020/08/25
|
[
"https://Stackoverflow.com/questions/63581399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14029222/"
] |
One method is:
```
select len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) as num_digits_after_dot
```
If you want the longest one:
```
select top (1) t.*
from t
order by len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) desc;
```
[Here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=52c6fa990dc7ccbd8f0b2c6145358160) is a db<>fiddle.
|
Slightly different way to use `parsename`, return that portion also, filter out any values that don't contain a decimal, and optionally deal with ties.
```
;WITH x AS
(
SELECT *, digits = PARSENAME(cmpstn_val,1)
FROM dbo.tablename
WHERE cmpstn_val LIKE '%.%'
)
SELECT TOP (1) WITH TIES
* FROM x
ORDER BY LEN(digits) DESC;
```
Results given the sample data in the question:
```
cust_nm cmpstn_val digits
======= ====================== ==================
Mike 678.293845012000000010 293845012000000010
```
But I agree with [@Larnu's comment](https://stackoverflow.com/questions/63581399/finding-largest-value-from-string-in-sql-server/63582707#comment112432238_63581399), you shouldn't be storing decimals as strings.
|
63,581,399 |
I have a string column (`cmpstn_val`) which has values with decimal points embedded - like this:
```
cust_nm | cmpstn_val
--------+------------------------
John | 123.384501928340000
Mark | 443.827345985
Peter | 145.320004
Mike | 678.293845012000000010
```
Firstly, I have to consider only the part that appears **after** the dot (.) and secondly, I have to find out which of these values has the **highest number of digits** present after the dot (.), and print the corresponding record which contains that value.
Hence, for the example presented above the SQL query should return the last value (i.e. '`678.293845012000000010`') since it has the highest number of digits/characters after the decimal point.
```
cust_nm | cmpstn_val
--------+------------------------
Mike | 678.293845012000000010
```
|
2020/08/25
|
[
"https://Stackoverflow.com/questions/63581399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14029222/"
] |
One method is:
```
select len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) as num_digits_after_dot
```
If you want the longest one:
```
select top (1) t.*
from t
order by len(stuff(cmpstn_val, 1, charindex('.', cmpstn_val), '')) desc;
```
[Here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=52c6fa990dc7ccbd8f0b2c6145358160) is a db<>fiddle.
|
You can use `String functions`.`CHARINDEX function` - to get '.' position in the field (`CHARINDEX('.',cmpstn_val`) and
then
using `SUBSTRING function` - we cut the string from the dot till the end (`SUBSTRING(cmpstn_val,CHARINDEX('.',cmpstn_val)+1,LEN(cmpstn_val))`).At last just get the `LEN`(number of digits):
```
SELECT TOP(1) WITH TIES *,
LEN(SUBSTRING(cmpstn_val,CHARINDEX('.',cmpstn_val)+1,LEN(cmpstn_val))) len_val from Table
ORDER BY len_val DESC
```
|
47,824,417 |
I have a ScrollView and a ConstraintLayout with some views inside, but it is not scrolling. I saw in other related questions some advice to add:
```
android:fillViewport="true"
```
to the layout and I ever tried with NestedScrollView and change the position of ScrollView, but nothing helps.
My fragment layout is:
```
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:paddingEnd="?attr/listPreferredItemPaddingRight"
android:paddingStart="?attr/listPreferredItemPaddingLeft"
android:paddingTop="?attr/listPreferredItemPaddingLeft"
>
<TextView
android:id="@+id/lbl_style"
style="@style/HeadSection"
android:text="@string/label_style"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_beer_description"/>
<TextView
android:id="@+id/lbl_short_style"
style="@style/Label"
android:text="@string/label_short_style"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style_name"/>
<TextView
android:id="@+id/txt_short_style"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_style_name"
tools:text="American Dark Lager"/>
<TextView
android:id="@+id/lbl_style_name"
style="@style/Label"
android:text="@string/label_style_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style"/>
<TextView
android:id="@+id/txt_style_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style"
tools:text="American-Style Dark Lager"/>
<TextView
android:id="@+id/lbl_style_category_name"
style="@style/Label"
android:layout_height="19dp"
android:text="@string/label_style_category_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_short_style"/>
<TextView
android:id="@+id/txt_style_category_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_short_style"
tools:text="North American Lager"/>
<TextView
android:id="@+id/lbl_beer"
style="@style/HeadSection"
android:layout_marginLeft="16dp"
android:layout_marginTop="4dp"
android:text="@string/label_detail_head_beer_info"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/lbl_beer_name"
style="@style/Label"
android:text="@string/label_detail_beer_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer"/>
<TextView
android:id="@+id/txt_beer_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer"
tools:text="Heineken"/>
<TextView
android:id="@+id/lbl_beer_Description"
style="@style/Label"
android:text="@string/label_detail_beer_description"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer_name"/>
<TextView
android:id="@+id/txt_beer_description"
style="@style/Content"
android:layout_width="0dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer_Description"/>
<android.support.constraint.Guideline
android:id="@+id/guideline_label_margins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="16dp"/>
<android.support.constraint.Guideline
android:id="@+id/guideline_content_margins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="120dp"/>
</android.support.constraint.ConstraintLayout>
</ScrollView>
```
This layout is inflated in a fragment that is:
content\_detail.xml:
```
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
```
And the root layout:
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/card_height_huge"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include
layout="@layout/content_detail"/>
</android.support.design.widget.CoordinatorLayout>
```
-- EDIT
there is a [bug report](https://issuetracker.google.com/issues/37115702) about this behavior.
I found a bug that was supposed to be fixed, but some others users related still report the issue:
<https://issuetracker.google.com/issues/37115702>
-- EDIT
I rotate the phone, the `txt_beer_description` TextView goes off the screen. So if I scroll the scroll works until the end of txt\_beer\_description, no more.
-- EDIT
style file is:
```
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@android:color/black</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="SearchBeerItemBaseText">
<item name="android:gravity">start|center_vertical</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginStart">8dp</item>
</style>
<style name="SearchBeerItemTextPrimary" parent="SearchBeerItemBaseText">
<item name="android:textColor">@color/primary_text</item>
<item name="android:textSize">16sp</item>
</style>
<style name="SearchBeerItemTextSecundary" parent="SearchBeerItemBaseText">
<item name="android:textColor">@color/secondary_text</item>
<item name="android:textSize">14sp</item>
</style>
<style name="CollectionItemBaseText">
<item name="android:gravity">start|center_vertical</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="CollectionItemTextPrimary" parent="CollectionItemBaseText">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">15sp</item>
<item name="android:focusable">false</item>
<item name="android:focusableInTouchMode">false</item>
<item name="android:clickable">false</item>
</style>
<style name="CollectionItemTextSecundary" parent="CollectionItemBaseText">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">13sp</item>
</style>
<style name="SearchActivityPrimaryImage">
<item name="android:layout_width">56dp</item>
<item name="android:layout_height">56dp</item>
</style>
<style name="HeadSection">
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_marginBottom">8dp</item>
<item name="android:textStyle">bold</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/primary</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Subhead</item>
</style>
<style name="Label">
<item name="android:textStyle">bold</item>
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/primary_text</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
</style>
<style name="Content" >
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/secondary_text</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
```
|
2017/12/15
|
[
"https://Stackoverflow.com/questions/47824417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785114/"
] |
The problems that I noticed:
* Your cross-entropy loss is wrong (see [this question](https://stackoverflow.com/q/46291253/712995) for details, in short you're computing *binary* cross-entropy).
* I dropped manual gradient computation in favor of `tf.train.AdamOptimizer`.
* I dropped the split of the input of `x` (it's not the right way to do distributed computation in tensorflow).
The result model easily gets to 99% accuracy even on one GPU.
```py
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import datetime
x = tf.placeholder(tf.float32, [None, 784], name='x')
x_img = tf.reshape(x, [-1, 28, 28, 1])
y = tf.placeholder(tf.float32, [None, 10], name='y')
keep_prob = tf.placeholder(tf.float32)
stddev = 0.1
w0 = tf.get_variable('w0', initializer=tf.truncated_normal([5, 5, 1, 32], stddev=stddev))
b0 = tf.get_variable('b0', initializer=tf.zeros([32]))
w1 = tf.get_variable('w1', initializer=tf.truncated_normal([5, 5, 32, 64], stddev=stddev))
b1 = tf.get_variable('b1', initializer=tf.zeros([64]))
w2 = tf.get_variable('w2', initializer=tf.truncated_normal([7 * 7 * 64, 1024], stddev=stddev))
b2 = tf.get_variable('b2', initializer=tf.zeros([1024]))
w3 = tf.get_variable('w3', initializer=tf.truncated_normal([1024, 10], stddev=stddev))
b3 = tf.get_variable('b3', initializer=tf.zeros([10]))
def conv2d(xx, W):
return tf.nn.conv2d(xx, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(xx):
return tf.nn.max_pool(xx, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def model_forward(xx):
h_conv1 = tf.nn.relu(conv2d(xx, w0) + b0)
h_pool1 = max_pool_2x2(h_conv1)
h_conv2 = tf.nn.relu(conv2d(h_pool1, w1) + b1)
h_pool2 = max_pool_2x2(h_conv2)
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w2) + b2)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
y = tf.matmul(h_fc1_drop, w3) + b3
return y
yy = model_forward(x_img)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=yy, labels=y))
train_step = tf.train.AdamOptimizer().minimize(loss)
correct_prediction = tf.equal(tf.argmax(yy, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
def main():
mnist = input_data.read_data_sets("/home/maxim/p/data/mnist-tf", one_hot=True)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
sess.run(tf.global_variables_initializer())
t1_1 = datetime.datetime.now()
for step in range(0, 10000):
batch_x, batch_y = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5})
if (step % 200) == 0:
print(step, sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1}))
t2_1 = datetime.datetime.now()
print("Computation time: " + str(t2_1 - t1_1))
if __name__ == "__main__":
main()
```
Now, if you really want it, you can do data or model parallelism to utilize your GPU power (there is [a great post](https://clindatsci.com/blog/2017/5/31/distributed-tensorflow) about it, but sometimes it doesn't render correctly due to hosting problems).
|
This is because the model is not using the same weights & biases for inference on CPU as well as on the other GPU devices.
For example:
```
for i in range(0,2):
with tf.device(('/gpu:{0}').format(i)):
with tf.variable_scope(('scope_gpu_{0}').format(i)) as infer_scope:
yy=model_forward(x_dict[('x{0}').format(i)])
infer_scope.reuse_variables()
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_dict[('y{0}').format(i)] * tf.log(yy), reduction_indices=[1]))
grads.append(opt.compute_gradients(cross_entropy,tf.trainable_variables()))
```
The reason you are getting low accuracy is that without specifying `reuse_variables`() and you try to call the model inference inside each epoch, the graph would create a new model with random weights & biases initialization, which is not what you favored.
|
47,824,417 |
I have a ScrollView and a ConstraintLayout with some views inside, but it is not scrolling. I saw in other related questions some advice to add:
```
android:fillViewport="true"
```
to the layout and I ever tried with NestedScrollView and change the position of ScrollView, but nothing helps.
My fragment layout is:
```
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:paddingEnd="?attr/listPreferredItemPaddingRight"
android:paddingStart="?attr/listPreferredItemPaddingLeft"
android:paddingTop="?attr/listPreferredItemPaddingLeft"
>
<TextView
android:id="@+id/lbl_style"
style="@style/HeadSection"
android:text="@string/label_style"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_beer_description"/>
<TextView
android:id="@+id/lbl_short_style"
style="@style/Label"
android:text="@string/label_short_style"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style_name"/>
<TextView
android:id="@+id/txt_short_style"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_style_name"
tools:text="American Dark Lager"/>
<TextView
android:id="@+id/lbl_style_name"
style="@style/Label"
android:text="@string/label_style_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style"/>
<TextView
android:id="@+id/txt_style_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_style"
tools:text="American-Style Dark Lager"/>
<TextView
android:id="@+id/lbl_style_category_name"
style="@style/Label"
android:layout_height="19dp"
android:text="@string/label_style_category_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_short_style"/>
<TextView
android:id="@+id/txt_style_category_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/txt_short_style"
tools:text="North American Lager"/>
<TextView
android:id="@+id/lbl_beer"
style="@style/HeadSection"
android:layout_marginLeft="16dp"
android:layout_marginTop="4dp"
android:text="@string/label_detail_head_beer_info"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/lbl_beer_name"
style="@style/Label"
android:text="@string/label_detail_beer_name"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer"/>
<TextView
android:id="@+id/txt_beer_name"
style="@style/Content"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer"
tools:text="Heineken"/>
<TextView
android:id="@+id/lbl_beer_Description"
style="@style/Label"
android:text="@string/label_detail_beer_description"
app:layout_constraintStart_toStartOf="@+id/guideline_label_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer_name"/>
<TextView
android:id="@+id/txt_beer_description"
style="@style/Content"
android:layout_width="0dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline_content_margins"
app:layout_constraintTop_toBottomOf="@+id/lbl_beer_Description"/>
<android.support.constraint.Guideline
android:id="@+id/guideline_label_margins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="16dp"/>
<android.support.constraint.Guideline
android:id="@+id/guideline_content_margins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="120dp"/>
</android.support.constraint.ConstraintLayout>
</ScrollView>
```
This layout is inflated in a fragment that is:
content\_detail.xml:
```
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
```
And the root layout:
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/card_height_huge"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include
layout="@layout/content_detail"/>
</android.support.design.widget.CoordinatorLayout>
```
-- EDIT
there is a [bug report](https://issuetracker.google.com/issues/37115702) about this behavior.
I found a bug that was supposed to be fixed, but some others users related still report the issue:
<https://issuetracker.google.com/issues/37115702>
-- EDIT
I rotate the phone, the `txt_beer_description` TextView goes off the screen. So if I scroll the scroll works until the end of txt\_beer\_description, no more.
-- EDIT
style file is:
```
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@android:color/black</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="SearchBeerItemBaseText">
<item name="android:gravity">start|center_vertical</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginStart">8dp</item>
</style>
<style name="SearchBeerItemTextPrimary" parent="SearchBeerItemBaseText">
<item name="android:textColor">@color/primary_text</item>
<item name="android:textSize">16sp</item>
</style>
<style name="SearchBeerItemTextSecundary" parent="SearchBeerItemBaseText">
<item name="android:textColor">@color/secondary_text</item>
<item name="android:textSize">14sp</item>
</style>
<style name="CollectionItemBaseText">
<item name="android:gravity">start|center_vertical</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="CollectionItemTextPrimary" parent="CollectionItemBaseText">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">15sp</item>
<item name="android:focusable">false</item>
<item name="android:focusableInTouchMode">false</item>
<item name="android:clickable">false</item>
</style>
<style name="CollectionItemTextSecundary" parent="CollectionItemBaseText">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">13sp</item>
</style>
<style name="SearchActivityPrimaryImage">
<item name="android:layout_width">56dp</item>
<item name="android:layout_height">56dp</item>
</style>
<style name="HeadSection">
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_marginBottom">8dp</item>
<item name="android:textStyle">bold</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/primary</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Subhead</item>
</style>
<style name="Label">
<item name="android:textStyle">bold</item>
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/primary_text</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
</style>
<style name="Content" >
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/secondary_text</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
```
|
2017/12/15
|
[
"https://Stackoverflow.com/questions/47824417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785114/"
] |
Along with the points mentioned in the first two answers, take a look at `return average_grads` in average\_gradients function, it's returning from the 1st iteration of the first for loop, meaning the gradients will only apply to the first variable (probably w0). Hence only w0 is getting updated and so you are getting a very low accuracy since the rest of the variables stay to their original values (either random/zeros).
|
This is because the model is not using the same weights & biases for inference on CPU as well as on the other GPU devices.
For example:
```
for i in range(0,2):
with tf.device(('/gpu:{0}').format(i)):
with tf.variable_scope(('scope_gpu_{0}').format(i)) as infer_scope:
yy=model_forward(x_dict[('x{0}').format(i)])
infer_scope.reuse_variables()
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_dict[('y{0}').format(i)] * tf.log(yy), reduction_indices=[1]))
grads.append(opt.compute_gradients(cross_entropy,tf.trainable_variables()))
```
The reason you are getting low accuracy is that without specifying `reuse_variables`() and you try to call the model inference inside each epoch, the graph would create a new model with random weights & biases initialization, which is not what you favored.
|
5,932,227 |
I've tried
```
text = nltk.word_tokenize("hello, my name is John")
words = nltk.pos_tag(text)
for w in words:
print "%s = %s" % (w[0], w[1])
```
And I got:
```
hello = NN
, = ,
my = PRP$
name = NN
is = VBZ
John = NNP
```
|
2011/05/09
|
[
"https://Stackoverflow.com/questions/5932227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260610/"
] |
According to the Penn Treebank tagset, *hello* is definitely an interjection and is consistently tagged UH. The problem you're running into is that the taggers that NLTK ships with were most likely trained on the part of the Wall Street Journal section of the Penn Treebank that is available for free, which unfortunately for you contains zero occurrences of the word *hello* and only three words tagged UH (interjection). If you want to tag spoken text, you'll need to train your tagger on the whole Penn Treebank, which includes something like 3 million words of spoken English.
By the way, the NLTK taggers won't always call *hello* a noun -- try tagging "don't hello me!" or "he said hello".
|
NLTK use it own tagger to tag part of speech.
But the accuracy will vary from text to text. It is because the tagger was trained using a corpus provided by NLTK itself. The corpus could be about anything.
The corpus is not similar to your text, then the tagger will fail to tag your text because the context, style is all very different.
You can train your own tagger if you got the time to do it.
Computer are not human, computer just do what we told them to do. So in order to make it do it properly, you should teach them properly to achieve best result.
|
5,932,227 |
I've tried
```
text = nltk.word_tokenize("hello, my name is John")
words = nltk.pos_tag(text)
for w in words:
print "%s = %s" % (w[0], w[1])
```
And I got:
```
hello = NN
, = ,
my = PRP$
name = NN
is = VBZ
John = NNP
```
|
2011/05/09
|
[
"https://Stackoverflow.com/questions/5932227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260610/"
] |
According to the Penn Treebank tagset, *hello* is definitely an interjection and is consistently tagged UH. The problem you're running into is that the taggers that NLTK ships with were most likely trained on the part of the Wall Street Journal section of the Penn Treebank that is available for free, which unfortunately for you contains zero occurrences of the word *hello* and only three words tagged UH (interjection). If you want to tag spoken text, you'll need to train your tagger on the whole Penn Treebank, which includes something like 3 million words of spoken English.
By the way, the NLTK taggers won't always call *hello* a noun -- try tagging "don't hello me!" or "he said hello".
|
Look in any dictionary and you will find hello defined as a "noun" (e.g. Longman). It's often described as an "exclamation" or "interjection" but the tag "noun" is not incorrect.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
Perhaps it was a tail-recursive call. GCC has some pass doing tail-recursive optimization.
But why should you bother? If the called function is an `extern` function, then it is public, and GCC should call it following the ABI conventions (which means that it follows the calling convention).
You should not care if the function was called by a jmp.
And it might also be a call to a dynamic library function (i.e. with the PLT for [dynamic linking](http://en.wikipedia.org/wiki/Dynamic_linking))
|
jmp has less overhead than call. jmp just jumps, call pushes some stuff on stack and jumps
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
As you don't show an example, I can only guess: the called function has the same return type as the calling one, and this works like
```
return func2(...)
```
or has no return type at all (`void`).
In this case, "we" leave "our" return address on the stack, leaving it to "them" to use it to return to "our" caller.
|
Perhaps it was a tail-recursive call. GCC has some pass doing tail-recursive optimization.
But why should you bother? If the called function is an `extern` function, then it is public, and GCC should call it following the ABI conventions (which means that it follows the calling convention).
You should not care if the function was called by a jmp.
And it might also be a call to a dynamic library function (i.e. with the PLT for [dynamic linking](http://en.wikipedia.org/wiki/Dynamic_linking))
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
Perhaps it was a tail-recursive call. GCC has some pass doing tail-recursive optimization.
But why should you bother? If the called function is an `extern` function, then it is public, and GCC should call it following the ABI conventions (which means that it follows the calling convention).
You should not care if the function was called by a jmp.
And it might also be a call to a dynamic library function (i.e. with the PLT for [dynamic linking](http://en.wikipedia.org/wiki/Dynamic_linking))
|
I'm assuming that this is a tail call, meaning either the current function returns the result of the called function unmodified, or (for a function that returns void) returns immediately after the function call. In either case, it is not necessary to use `call`.
The `call` instruction performs two functions. First, it pushes the address of the instruction after the call onto the stack as a return address. Then it jumps to the destination of the call. `ret` pops the return address off of the stack and jumps to that location.
Since the calling function returns the result of the called function, there is no reason for operation to return to it after the called function returns. Therefore, whenever possible and if the optimization level permits it, GCC will destroy its stack frame before the function call, so that the top of the stack contains the return address for the function that called it, and then simply jump to the called function. The result is that, when the called function returns, it returns directly to the first function instead of the calling function.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
Perhaps it was a tail-recursive call. GCC has some pass doing tail-recursive optimization.
But why should you bother? If the called function is an `extern` function, then it is public, and GCC should call it following the ABI conventions (which means that it follows the calling convention).
You should not care if the function was called by a jmp.
And it might also be a call to a dynamic library function (i.e. with the PLT for [dynamic linking](http://en.wikipedia.org/wiki/Dynamic_linking))
|
You will never know, but one of the likely reasons is "cache" (among other reasons such as the already mentioned tail call optimization).
Inlining can make code faster and it can make code slower, because more code means less of it will be in the L1 cache at one time.
A JMP allows the compiler to reuse the same piece of code at little or no cost at all. Modern processors are deeply pipelined, and pipelines go over a JMP without problems (there is no possibility of a misprediction here!).
In the average case, it will cost as little as 1-2 cycles, in the best cases zero cycles, because the CPU would have to wait on a previous instruction to retire anyway. This obviously depends totally on the respective, individual code.
The compiler could in principle even do that with several functions that have common parts.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
As you don't show an example, I can only guess: the called function has the same return type as the calling one, and this works like
```
return func2(...)
```
or has no return type at all (`void`).
In this case, "we" leave "our" return address on the stack, leaving it to "them" to use it to return to "our" caller.
|
jmp has less overhead than call. jmp just jumps, call pushes some stuff on stack and jumps
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
jmp has less overhead than call. jmp just jumps, call pushes some stuff on stack and jumps
|
You will never know, but one of the likely reasons is "cache" (among other reasons such as the already mentioned tail call optimization).
Inlining can make code faster and it can make code slower, because more code means less of it will be in the L1 cache at one time.
A JMP allows the compiler to reuse the same piece of code at little or no cost at all. Modern processors are deeply pipelined, and pipelines go over a JMP without problems (there is no possibility of a misprediction here!).
In the average case, it will cost as little as 1-2 cycles, in the best cases zero cycles, because the CPU would have to wait on a previous instruction to retire anyway. This obviously depends totally on the respective, individual code.
The compiler could in principle even do that with several functions that have common parts.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
As you don't show an example, I can only guess: the called function has the same return type as the calling one, and this works like
```
return func2(...)
```
or has no return type at all (`void`).
In this case, "we" leave "our" return address on the stack, leaving it to "them" to use it to return to "our" caller.
|
I'm assuming that this is a tail call, meaning either the current function returns the result of the called function unmodified, or (for a function that returns void) returns immediately after the function call. In either case, it is not necessary to use `call`.
The `call` instruction performs two functions. First, it pushes the address of the instruction after the call onto the stack as a return address. Then it jumps to the destination of the call. `ret` pops the return address off of the stack and jumps to that location.
Since the calling function returns the result of the called function, there is no reason for operation to return to it after the called function returns. Therefore, whenever possible and if the optimization level permits it, GCC will destroy its stack frame before the function call, so that the top of the stack contains the return address for the function that called it, and then simply jump to the called function. The result is that, when the called function returns, it returns directly to the first function instead of the calling function.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
As you don't show an example, I can only guess: the called function has the same return type as the calling one, and this works like
```
return func2(...)
```
or has no return type at all (`void`).
In this case, "we" leave "our" return address on the stack, leaving it to "them" to use it to return to "our" caller.
|
You will never know, but one of the likely reasons is "cache" (among other reasons such as the already mentioned tail call optimization).
Inlining can make code faster and it can make code slower, because more code means less of it will be in the L1 cache at one time.
A JMP allows the compiler to reuse the same piece of code at little or no cost at all. Modern processors are deeply pipelined, and pipelines go over a JMP without problems (there is no possibility of a misprediction here!).
In the average case, it will cost as little as 1-2 cycles, in the best cases zero cycles, because the CPU would have to wait on a previous instruction to retire anyway. This obviously depends totally on the respective, individual code.
The compiler could in principle even do that with several functions that have common parts.
|
7,984,703 |
Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found [Drawing a line/path on Google Maps](https://stackoverflow.com/questions/2176397/drawing-a-line-path-on-google-maps) but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to <http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html> This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
|
2011/11/02
|
[
"https://Stackoverflow.com/questions/7984703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751223/"
] |
I'm assuming that this is a tail call, meaning either the current function returns the result of the called function unmodified, or (for a function that returns void) returns immediately after the function call. In either case, it is not necessary to use `call`.
The `call` instruction performs two functions. First, it pushes the address of the instruction after the call onto the stack as a return address. Then it jumps to the destination of the call. `ret` pops the return address off of the stack and jumps to that location.
Since the calling function returns the result of the called function, there is no reason for operation to return to it after the called function returns. Therefore, whenever possible and if the optimization level permits it, GCC will destroy its stack frame before the function call, so that the top of the stack contains the return address for the function that called it, and then simply jump to the called function. The result is that, when the called function returns, it returns directly to the first function instead of the calling function.
|
You will never know, but one of the likely reasons is "cache" (among other reasons such as the already mentioned tail call optimization).
Inlining can make code faster and it can make code slower, because more code means less of it will be in the L1 cache at one time.
A JMP allows the compiler to reuse the same piece of code at little or no cost at all. Modern processors are deeply pipelined, and pipelines go over a JMP without problems (there is no possibility of a misprediction here!).
In the average case, it will cost as little as 1-2 cycles, in the best cases zero cycles, because the CPU would have to wait on a previous instruction to retire anyway. This obviously depends totally on the respective, individual code.
The compiler could in principle even do that with several functions that have common parts.
|
53,964,623 |
I was ask to write a function in erlang that given a list of integer and an integer, will return all integer smaller than or equal to the integer. Example sive ([1,2,3,4,5 ],3)=[1,2,3]
|
2018/12/28
|
[
"https://Stackoverflow.com/questions/53964623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10785849/"
] |
List comprehensions are explained here:
* <http://erlang.org/doc/programming_examples/list_comprehensions.html>
* <https://learnyousomeerlang.com/starting-out-for-real#list-comprehensions>
|
If you'd like to use function instead you can check [filter/2](http://erlang.org/doc/man/lists.html#filter-2).
|
72,201,260 |
I have a form, when I enter une value for example `test`, I would like to retrieve the value in a modal, please.
1))
[](https://i.stack.imgur.com/4haFu.png)
2))
[](https://i.stack.imgur.com/X9u91.png)
Here is my error message
```
error TS2339: Property 'dest' does not exist on type 'TotoResultModalComponent'.
```
Can you help me to be able to display the value in the modal please?
**PARENT**
toto.component.ts
```
export class TotoComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
private svm: string | null = null;
dest: string = '';
constructor(
private service: TotoService,
private router: Router,
private activatedRoute: ActivatedRoute,
private modalService: BsModalService,
private location: Location,
) { }
ngOnInit(): void {
this.svm = this.activatedRoute.snapshot.paramMap.get('svm');
if (!this.svm) {
return;
}
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
openConfirmModal(): void {
const modalRef = this.modalService.show(TotoResultModalComponent, {
...NOT_CLOSABLE_MODAL_OPTIONS,
class: 'modal-dialog-centered modal-lg',
ariaLabelledBy: 'modal-error-title',
initialState: {
},
providers: [
{ provide: TotoService}
]
});
}
}
```
toto.component.html
```
<form #formulaire="ngForm" (ngSubmit)="formulaire.form.valid">
<div class="row row-cols-3 pt-3">
<div class="col text-end">
<label for="dest" class="form-label">Name</label>
</div>
<div class="col-4">
<input
id="dest"
name="dest"
type="text"
class="form-control"
style="min-width: 380px"
maxlength="25"
[(ngModel)]="dest"
/>
</div>
</div>
<div class="row row-cols-3 pt-3">
<div class="col"></div>
<div class="col text-start">
<button
type="submit"
class="btn btn-primary"
(click)="openConfirmModal()"
style="background-color: #239CD3;"
[disabled]="formulaire.form.invalid"
>
Confirm
</button>
</div>
</div>
</form>
```
**CHILD**
toto-result-modal.component.html
```
<table class="table table-hover table-striped spaceLeft" style="width: 700px">
<tbody>
<tr>
<th style="width: 60%">Name</th>
<td style="min-width: 100%">{{ dest}}</td>
</tr>
</tbody>
</table>
```
toto-result-modal.component.ts
```
export class TotoResultModalComponent implements OnInit {
private unsubscribe$ = new Subject<void>();
modalService: any;
@Output() closeModal = new EventEmitter<void>();
constructor(
public modal: BsModalRef,
private router: Router,
private location: Location,
private service: TotoService
) { }
ngOnInit(): void {
this.goBack();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
goBack(): void {
this.modal.hide();
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/transfers/toto']);
});
}
}
```
|
2022/05/11
|
[
"https://Stackoverflow.com/questions/72201260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18237732/"
] |
Short answer is: No.
It's best practice with containers to have one process per container. The container has an entrypoint, basically a command that is executed when starting the container. This entrypoint will be the command that starts your process. If you want more than one process, you need to have a script in the container that starts them and puts them in the background, complicating the whole setup. See also [docker docs](https://docs.docker.com/config/containers/multi-service_container/).
There are some more downsides.
1. A container should only consist of everything it needs to run the process. If you have more than one process, you'll have one big container. Also your not independent on the base image, but you need to find one, that fits all processes you want to run. Also you might have troubles with dependencies, because the different processes might need different version of a dependency (like a library).
2. You're unable to scale independently. E.g. you could have 5 CMS container that all use the same database, for redundance and performance. That's not possible when you have everything in the same container.
3. Detecting/debugging fault. If more than one process runs in a container, the container might fail because one of the processes failed. But you can't be sure which one. If you have one process and the container fails, you know exactly why. Also it's easier to monitor health, because there is one health-check endpoint for that container. Last but not least, logs of the container represent logs of the process, not of multiple ones.
4. Updating becomes easier. When updating your CMS to the next version or updating the database, you need to update the container image of the process. E.g. the database doesn't need to be stopped/started when you update the CMS.
5. The container can be reused easier. You can e.g. use the same container everywhere and mount the customer specifics from a volume, configmap or environment variable.
If you want both your CMS and database together you can use the sidecar pattern in kubernetes. Simply have a pod with multiple containers in the manifest. Note that this too will not make it horizontal scalable.
|
It's not clear what you mean with CMS (content/customer/... management system). Nonetheless, milestones on the way to create/sepearte an application (monolith/mcsvs) would propably be:
* if the application is a smaller one, start with a monolithic structure (whole application as an executable on a application/webserver
* otherwise determine which parts should be seperated (-> [Domain-Driven Design](https://en.wikipedia.org/wiki/Domain-driven_design))
* if the smaller monolithic structure is getting bigger and you put more domain related services, you pull it apart with well defined seperations according to your domain landscape:
>
> Once you have a firm grasp on why you think microservices are a good
> idea, you can use this understanding to help prioritize which
> microservices to create first. Want to scale the application?
> Functionality that currently constrains the systemโs ability to handle
> load is going to be high on the list. Want to improve time to market?
> Look at the systemโs volatility to identify those pieces of
> functionality that change most frequently, and see if they would work
> as microservices. You can use static analysis tools like CodeScene to
> quickly find volatile parts of your codebase.
>
>
> "Building Microservices"-S.Newman
>
>
>
**Database**
According to the principle of "hiding internal state", every microservice should have its own database.
>
> If a microservice wants to access data held by another microservice,
> it should go and ask that second microservice for the data. ... which allows us to clearly separate functionality
>
>
>
In the long run this could be perfected into completely seperated end-to-end slices backed by their own database (UI-LOGIC-DATA). In the context of microservices:
>
> sharing databases is one of the worst things you can do if youโre trying to achieve independent deployability
>
>
>
So the general way of choice would be more or less:
[](https://i.stack.imgur.com/c8hIa.png)
|
72,201,260 |
I have a form, when I enter une value for example `test`, I would like to retrieve the value in a modal, please.
1))
[](https://i.stack.imgur.com/4haFu.png)
2))
[](https://i.stack.imgur.com/X9u91.png)
Here is my error message
```
error TS2339: Property 'dest' does not exist on type 'TotoResultModalComponent'.
```
Can you help me to be able to display the value in the modal please?
**PARENT**
toto.component.ts
```
export class TotoComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
private svm: string | null = null;
dest: string = '';
constructor(
private service: TotoService,
private router: Router,
private activatedRoute: ActivatedRoute,
private modalService: BsModalService,
private location: Location,
) { }
ngOnInit(): void {
this.svm = this.activatedRoute.snapshot.paramMap.get('svm');
if (!this.svm) {
return;
}
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
openConfirmModal(): void {
const modalRef = this.modalService.show(TotoResultModalComponent, {
...NOT_CLOSABLE_MODAL_OPTIONS,
class: 'modal-dialog-centered modal-lg',
ariaLabelledBy: 'modal-error-title',
initialState: {
},
providers: [
{ provide: TotoService}
]
});
}
}
```
toto.component.html
```
<form #formulaire="ngForm" (ngSubmit)="formulaire.form.valid">
<div class="row row-cols-3 pt-3">
<div class="col text-end">
<label for="dest" class="form-label">Name</label>
</div>
<div class="col-4">
<input
id="dest"
name="dest"
type="text"
class="form-control"
style="min-width: 380px"
maxlength="25"
[(ngModel)]="dest"
/>
</div>
</div>
<div class="row row-cols-3 pt-3">
<div class="col"></div>
<div class="col text-start">
<button
type="submit"
class="btn btn-primary"
(click)="openConfirmModal()"
style="background-color: #239CD3;"
[disabled]="formulaire.form.invalid"
>
Confirm
</button>
</div>
</div>
</form>
```
**CHILD**
toto-result-modal.component.html
```
<table class="table table-hover table-striped spaceLeft" style="width: 700px">
<tbody>
<tr>
<th style="width: 60%">Name</th>
<td style="min-width: 100%">{{ dest}}</td>
</tr>
</tbody>
</table>
```
toto-result-modal.component.ts
```
export class TotoResultModalComponent implements OnInit {
private unsubscribe$ = new Subject<void>();
modalService: any;
@Output() closeModal = new EventEmitter<void>();
constructor(
public modal: BsModalRef,
private router: Router,
private location: Location,
private service: TotoService
) { }
ngOnInit(): void {
this.goBack();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
goBack(): void {
this.modal.hide();
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/transfers/toto']);
});
}
}
```
|
2022/05/11
|
[
"https://Stackoverflow.com/questions/72201260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18237732/"
] |
Short answer is: No.
It's best practice with containers to have one process per container. The container has an entrypoint, basically a command that is executed when starting the container. This entrypoint will be the command that starts your process. If you want more than one process, you need to have a script in the container that starts them and puts them in the background, complicating the whole setup. See also [docker docs](https://docs.docker.com/config/containers/multi-service_container/).
There are some more downsides.
1. A container should only consist of everything it needs to run the process. If you have more than one process, you'll have one big container. Also your not independent on the base image, but you need to find one, that fits all processes you want to run. Also you might have troubles with dependencies, because the different processes might need different version of a dependency (like a library).
2. You're unable to scale independently. E.g. you could have 5 CMS container that all use the same database, for redundance and performance. That's not possible when you have everything in the same container.
3. Detecting/debugging fault. If more than one process runs in a container, the container might fail because one of the processes failed. But you can't be sure which one. If you have one process and the container fails, you know exactly why. Also it's easier to monitor health, because there is one health-check endpoint for that container. Last but not least, logs of the container represent logs of the process, not of multiple ones.
4. Updating becomes easier. When updating your CMS to the next version or updating the database, you need to update the container image of the process. E.g. the database doesn't need to be stopped/started when you update the CMS.
5. The container can be reused easier. You can e.g. use the same container everywhere and mount the customer specifics from a volume, configmap or environment variable.
If you want both your CMS and database together you can use the sidecar pattern in kubernetes. Simply have a pod with multiple containers in the manifest. Note that this too will not make it horizontal scalable.
|
That's a fair question that most of us go through at some point. One tends to have everything in the same container for convenience but then later regret that choice.
So, best to do it right from the start and to have one container for the app and one for the database.
According to [Docker's documentation](https://docs.docker.com/get-started/07_multi_container/),
>
> Up to this point, we have been working with single container apps. But, we now want to add MySQL to the application stack. The following question often arises - โWhere will MySQL run? Install it in the same container or run it separately?โ In general, each container should do one thing and do it well.
>
>
> (...)
>
>
> So, we will update our application to work like this:
>
>
> [](https://i.stack.imgur.com/yrZUi.png)
>
>
>
|
72,201,260 |
I have a form, when I enter une value for example `test`, I would like to retrieve the value in a modal, please.
1))
[](https://i.stack.imgur.com/4haFu.png)
2))
[](https://i.stack.imgur.com/X9u91.png)
Here is my error message
```
error TS2339: Property 'dest' does not exist on type 'TotoResultModalComponent'.
```
Can you help me to be able to display the value in the modal please?
**PARENT**
toto.component.ts
```
export class TotoComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
private svm: string | null = null;
dest: string = '';
constructor(
private service: TotoService,
private router: Router,
private activatedRoute: ActivatedRoute,
private modalService: BsModalService,
private location: Location,
) { }
ngOnInit(): void {
this.svm = this.activatedRoute.snapshot.paramMap.get('svm');
if (!this.svm) {
return;
}
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
openConfirmModal(): void {
const modalRef = this.modalService.show(TotoResultModalComponent, {
...NOT_CLOSABLE_MODAL_OPTIONS,
class: 'modal-dialog-centered modal-lg',
ariaLabelledBy: 'modal-error-title',
initialState: {
},
providers: [
{ provide: TotoService}
]
});
}
}
```
toto.component.html
```
<form #formulaire="ngForm" (ngSubmit)="formulaire.form.valid">
<div class="row row-cols-3 pt-3">
<div class="col text-end">
<label for="dest" class="form-label">Name</label>
</div>
<div class="col-4">
<input
id="dest"
name="dest"
type="text"
class="form-control"
style="min-width: 380px"
maxlength="25"
[(ngModel)]="dest"
/>
</div>
</div>
<div class="row row-cols-3 pt-3">
<div class="col"></div>
<div class="col text-start">
<button
type="submit"
class="btn btn-primary"
(click)="openConfirmModal()"
style="background-color: #239CD3;"
[disabled]="formulaire.form.invalid"
>
Confirm
</button>
</div>
</div>
</form>
```
**CHILD**
toto-result-modal.component.html
```
<table class="table table-hover table-striped spaceLeft" style="width: 700px">
<tbody>
<tr>
<th style="width: 60%">Name</th>
<td style="min-width: 100%">{{ dest}}</td>
</tr>
</tbody>
</table>
```
toto-result-modal.component.ts
```
export class TotoResultModalComponent implements OnInit {
private unsubscribe$ = new Subject<void>();
modalService: any;
@Output() closeModal = new EventEmitter<void>();
constructor(
public modal: BsModalRef,
private router: Router,
private location: Location,
private service: TotoService
) { }
ngOnInit(): void {
this.goBack();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
goBack(): void {
this.modal.hide();
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/transfers/toto']);
});
}
}
```
|
2022/05/11
|
[
"https://Stackoverflow.com/questions/72201260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18237732/"
] |
That's a fair question that most of us go through at some point. One tends to have everything in the same container for convenience but then later regret that choice.
So, best to do it right from the start and to have one container for the app and one for the database.
According to [Docker's documentation](https://docs.docker.com/get-started/07_multi_container/),
>
> Up to this point, we have been working with single container apps. But, we now want to add MySQL to the application stack. The following question often arises - โWhere will MySQL run? Install it in the same container or run it separately?โ In general, each container should do one thing and do it well.
>
>
> (...)
>
>
> So, we will update our application to work like this:
>
>
> [](https://i.stack.imgur.com/yrZUi.png)
>
>
>
|
It's not clear what you mean with CMS (content/customer/... management system). Nonetheless, milestones on the way to create/sepearte an application (monolith/mcsvs) would propably be:
* if the application is a smaller one, start with a monolithic structure (whole application as an executable on a application/webserver
* otherwise determine which parts should be seperated (-> [Domain-Driven Design](https://en.wikipedia.org/wiki/Domain-driven_design))
* if the smaller monolithic structure is getting bigger and you put more domain related services, you pull it apart with well defined seperations according to your domain landscape:
>
> Once you have a firm grasp on why you think microservices are a good
> idea, you can use this understanding to help prioritize which
> microservices to create first. Want to scale the application?
> Functionality that currently constrains the systemโs ability to handle
> load is going to be high on the list. Want to improve time to market?
> Look at the systemโs volatility to identify those pieces of
> functionality that change most frequently, and see if they would work
> as microservices. You can use static analysis tools like CodeScene to
> quickly find volatile parts of your codebase.
>
>
> "Building Microservices"-S.Newman
>
>
>
**Database**
According to the principle of "hiding internal state", every microservice should have its own database.
>
> If a microservice wants to access data held by another microservice,
> it should go and ask that second microservice for the data. ... which allows us to clearly separate functionality
>
>
>
In the long run this could be perfected into completely seperated end-to-end slices backed by their own database (UI-LOGIC-DATA). In the context of microservices:
>
> sharing databases is one of the worst things you can do if youโre trying to achieve independent deployability
>
>
>
So the general way of choice would be more or less:
[](https://i.stack.imgur.com/c8hIa.png)
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
You can simply perform an `UPDATE` that uses a `JOIN` between the two tables like so:
```
UPDATE c
SET Active = u.Active
FROM Company c
INNER JOIN Users u ON u.CompanyId = c.ID
```
**Full working sample code:**
```
CREATE TABLE #Users
(
CompanyId INT ,
Active BIT
)
INSERT INTO #Users
( CompanyId, Active )
VALUES ( 458, 1 ),
( 685, 1 ),
( 58, 0 )
CREATE TABLE #Company
(
ID INT ,
Active BIT
)
INSERT INTO #Company
( ID, Active )
VALUES ( 5, NULL ),
( 3, NULL ),
( 58, NULL ),
( 685, NULL )
UPDATE c
SET Active = u.Active
FROM #Company c
INNER JOIN #Users u ON u.CompanyId = c.ID
SELECT * FROM #Company
DROP TABLE #Users
DROP TABLE #Company
```
You'll notice that the `UPDATE` statement in the sample code uses aliases `c` and `u` to reference the two tables.
**Caveat:**
As stated in the comments, this assumes that you only ever have a 1 to 1 relationship between `Company` and `Users`. If there is more than one user assigned to the same company, you will need to filter the `Users` to pick the one you want to use, otherwise you may get unexpected results.
|
That should do the trick for you.
```
DECLARE @Users TABLE (CompanyID INT, Active BIT);
DECLARE @Companies TABLE (CompanyID INT, Active BIT);
INSERT INTO @Users (CompanyID, Active)
VALUES (458, 1), (685, 1), (58, 0)
INSERT INTO @Companies (CompanyID)
VALUES (5),(3),(58),(685)
SELECT C.CompanyID, U.Active
FROM @Companies AS C
OUTER APPLY (
SELECT TOP (1) U.Active
FROM @Users AS U
WHERE U.CompanyID = C.CompanyID
ORDER BY U.Active DESC
) AS U(Active)
```
**Result:**
```
CompanyID Active
------------------
5 NULL
3 NULL
58 0
685 1
```
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
That should do the trick for you.
```
DECLARE @Users TABLE (CompanyID INT, Active BIT);
DECLARE @Companies TABLE (CompanyID INT, Active BIT);
INSERT INTO @Users (CompanyID, Active)
VALUES (458, 1), (685, 1), (58, 0)
INSERT INTO @Companies (CompanyID)
VALUES (5),(3),(58),(685)
SELECT C.CompanyID, U.Active
FROM @Companies AS C
OUTER APPLY (
SELECT TOP (1) U.Active
FROM @Users AS U
WHERE U.CompanyID = C.CompanyID
ORDER BY U.Active DESC
) AS U(Active)
```
**Result:**
```
CompanyID Active
------------------
5 NULL
3 NULL
58 0
685 1
```
|
Assuming you have more users for each company, I would assume that 1 active user would result in an active company.
```
UPDATE
Company
SET Active = (SELECT top 1 Active
FROM Users
WHERE CompanyId = Company.id
ORDER BY Active DESC)
```
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
That should do the trick for you.
```
DECLARE @Users TABLE (CompanyID INT, Active BIT);
DECLARE @Companies TABLE (CompanyID INT, Active BIT);
INSERT INTO @Users (CompanyID, Active)
VALUES (458, 1), (685, 1), (58, 0)
INSERT INTO @Companies (CompanyID)
VALUES (5),(3),(58),(685)
SELECT C.CompanyID, U.Active
FROM @Companies AS C
OUTER APPLY (
SELECT TOP (1) U.Active
FROM @Users AS U
WHERE U.CompanyID = C.CompanyID
ORDER BY U.Active DESC
) AS U(Active)
```
**Result:**
```
CompanyID Active
------------------
5 NULL
3 NULL
58 0
685 1
```
|
```
UPDATE Company
SET Company.Active = u.Active from Users u
where Company.ID = u.CompanyID
```
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
You can simply perform an `UPDATE` that uses a `JOIN` between the two tables like so:
```
UPDATE c
SET Active = u.Active
FROM Company c
INNER JOIN Users u ON u.CompanyId = c.ID
```
**Full working sample code:**
```
CREATE TABLE #Users
(
CompanyId INT ,
Active BIT
)
INSERT INTO #Users
( CompanyId, Active )
VALUES ( 458, 1 ),
( 685, 1 ),
( 58, 0 )
CREATE TABLE #Company
(
ID INT ,
Active BIT
)
INSERT INTO #Company
( ID, Active )
VALUES ( 5, NULL ),
( 3, NULL ),
( 58, NULL ),
( 685, NULL )
UPDATE c
SET Active = u.Active
FROM #Company c
INNER JOIN #Users u ON u.CompanyId = c.ID
SELECT * FROM #Company
DROP TABLE #Users
DROP TABLE #Company
```
You'll notice that the `UPDATE` statement in the sample code uses aliases `c` and `u` to reference the two tables.
**Caveat:**
As stated in the comments, this assumes that you only ever have a 1 to 1 relationship between `Company` and `Users`. If there is more than one user assigned to the same company, you will need to filter the `Users` to pick the one you want to use, otherwise you may get unexpected results.
|
Assuming you have more users for each company, I would assume that 1 active user would result in an active company.
```
UPDATE
Company
SET Active = (SELECT top 1 Active
FROM Users
WHERE CompanyId = Company.id
ORDER BY Active DESC)
```
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
You can simply perform an `UPDATE` that uses a `JOIN` between the two tables like so:
```
UPDATE c
SET Active = u.Active
FROM Company c
INNER JOIN Users u ON u.CompanyId = c.ID
```
**Full working sample code:**
```
CREATE TABLE #Users
(
CompanyId INT ,
Active BIT
)
INSERT INTO #Users
( CompanyId, Active )
VALUES ( 458, 1 ),
( 685, 1 ),
( 58, 0 )
CREATE TABLE #Company
(
ID INT ,
Active BIT
)
INSERT INTO #Company
( ID, Active )
VALUES ( 5, NULL ),
( 3, NULL ),
( 58, NULL ),
( 685, NULL )
UPDATE c
SET Active = u.Active
FROM #Company c
INNER JOIN #Users u ON u.CompanyId = c.ID
SELECT * FROM #Company
DROP TABLE #Users
DROP TABLE #Company
```
You'll notice that the `UPDATE` statement in the sample code uses aliases `c` and `u` to reference the two tables.
**Caveat:**
As stated in the comments, this assumes that you only ever have a 1 to 1 relationship between `Company` and `Users`. If there is more than one user assigned to the same company, you will need to filter the `Users` to pick the one you want to use, otherwise you may get unexpected results.
|
```
UPDATE Company
SET Company.Active = u.Active from Users u
where Company.ID = u.CompanyID
```
|
29,257,756 |
I have two tables, `Users` and `Company`.
I want to transfer values from a `Active` column in the `Users` table to the `Active` column in the `Company` table, where the `CompanyID` in matches `ID`.
This is an example table. It has many thousands of rows, and there is 1 on 1 relationship between `Company` and `Users`:
```
Users:
CompanyID Active
458 1
685 1
58 0
Company:
ID Active
5 Null
3 Null
58 Null
685 Null
```
The final `Company` table should look something like this where the `Null` has been replaced with the value from the `Users` table.
```
Company:
ID Active
5 Null
3 Null
58 0
685 1
```
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29257756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515143/"
] |
Assuming you have more users for each company, I would assume that 1 active user would result in an active company.
```
UPDATE
Company
SET Active = (SELECT top 1 Active
FROM Users
WHERE CompanyId = Company.id
ORDER BY Active DESC)
```
|
```
UPDATE Company
SET Company.Active = u.Active from Users u
where Company.ID = u.CompanyID
```
|
4,340,609 |
You can get the current class name, assuming RTTI is enabled, using typeid(this).name() at runtime.
I would like to be able to get the name of the base class for "this". Is that possible? I'm not using multiple inheritance, in case that makes a difference.
|
2010/12/02
|
[
"https://Stackoverflow.com/questions/4340609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
No sir. Sorry. And your method of getting the class name this way is implementation-dependent. On my implementation, I get the mangled name.
|
No, it is not, and the reason you need this feature is dubious :)
|
4,340,609 |
You can get the current class name, assuming RTTI is enabled, using typeid(this).name() at runtime.
I would like to be able to get the name of the base class for "this". Is that possible? I'm not using multiple inheritance, in case that makes a difference.
|
2010/12/02
|
[
"https://Stackoverflow.com/questions/4340609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
Plus, I don't think that you can count on `typeid(this).name()` to give you a class name (AFAIK the exact value to be returned is implementation-defined).
|
No sir. Sorry. And your method of getting the class name this way is implementation-dependent. On my implementation, I get the mangled name.
|
4,340,609 |
You can get the current class name, assuming RTTI is enabled, using typeid(this).name() at runtime.
I would like to be able to get the name of the base class for "this". Is that possible? I'm not using multiple inheritance, in case that makes a difference.
|
2010/12/02
|
[
"https://Stackoverflow.com/questions/4340609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
Plus, I don't think that you can count on `typeid(this).name()` to give you a class name (AFAIK the exact value to be returned is implementation-defined).
|
No, it is not, and the reason you need this feature is dubious :)
|
4,340,609 |
You can get the current class name, assuming RTTI is enabled, using typeid(this).name() at runtime.
I would like to be able to get the name of the base class for "this". Is that possible? I'm not using multiple inheritance, in case that makes a difference.
|
2010/12/02
|
[
"https://Stackoverflow.com/questions/4340609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
The information can't reliably be retrieved because it isn't reliably stored anywhere, in turn because the C++ philosophy is not to give you things unless you explicitly ask for them.
|
No, it is not, and the reason you need this feature is dubious :)
|
4,340,609 |
You can get the current class name, assuming RTTI is enabled, using typeid(this).name() at runtime.
I would like to be able to get the name of the base class for "this". Is that possible? I'm not using multiple inheritance, in case that makes a difference.
|
2010/12/02
|
[
"https://Stackoverflow.com/questions/4340609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
Plus, I don't think that you can count on `typeid(this).name()` to give you a class name (AFAIK the exact value to be returned is implementation-defined).
|
The information can't reliably be retrieved because it isn't reliably stored anywhere, in turn because the C++ philosophy is not to give you things unless you explicitly ask for them.
|
20,280,757 |
I have a question regarding fetch data in the form of table. i have a table with a single row now i just want amount increased on the basis on given logic..
like
```
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
```
logic is 10% add with previous amount
My table is
```
Sno - Name- Amount
1 - A - 1200
```
Now I want result like this..
```
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
```
Can anybody help me i'm not find any logic for that
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20280757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016777/"
] |
```
WITH COUNTER(RN)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.objects
),
A(RN, value)
AS
(
SELECT CAST(1 as bigint),
CAST(1200 as decimal(20, 0))
UNION ALL
SELECT COUNTER.RN,
CAST(A.value*1.1 as decimal(20, 0))
FROM COUNTER JOIN A ON A.RN=COUNTER.RN-1
)
SELECT TOP 1000 *
FROM A
OPTION(MAXRECURSION 1000)
```
This example selects first 1000 rows from sys.objects. You should replace **sys.objects** with your table name and **object\_id** with primary/unique key column(s). Also you should change **TOP 1000** and **MAXRECURSION 1000**. Notice MAXRECURSION ะผะฐั be between 0 and 32767, 0 - no limit.
Be aware of large tables, because it can cause arithmetic overflow of value.
|
This does what you ask for:
```
select sno, name, amount from table1
union select sno+1, name, amount*1.1 from table1
union select sno+2, name, amount*1.1*1.1 from table1
```
But it's not very flexible. E.g. if there are multiple rows you might get duplicate 'sno' numbers.
|
20,280,757 |
I have a question regarding fetch data in the form of table. i have a table with a single row now i just want amount increased on the basis on given logic..
like
```
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
```
logic is 10% add with previous amount
My table is
```
Sno - Name- Amount
1 - A - 1200
```
Now I want result like this..
```
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
```
Can anybody help me i'm not find any logic for that
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20280757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016777/"
] |
This has exactly the same limitation as WadimX's answer, but it'll do 100 rows. To produce your example output given your input table (which I'll refer to as `example`):
```
;WITH nums AS
(SELECT 1 AS RowNum, Name, Amount
FROM (SELECT Name, Amount FROM example) s
UNION ALL
SELECT RowNum + 1 As RowNum, Name, CAST(1.1*Amount AS INT) AS Amount
FROM nums
WHERE RowNum < 5)
SELECT RowNum AS SNo, Name, Amount
FROM nums
ORDER BY Name
```
[SQLFiddle](http://sqlfiddle.com/#!3/524ae/1/0)
That returns 5 rows for every record in `example`, you can increase that count by changing the `RowNum < 5` to `100` or however many you want.
**Output**
```
SNo Name Amount
-----------------------
1 A 1200
2 A 1320
3 A 1452
... ... ...
```
|
This does what you ask for:
```
select sno, name, amount from table1
union select sno+1, name, amount*1.1 from table1
union select sno+2, name, amount*1.1*1.1 from table1
```
But it's not very flexible. E.g. if there are multiple rows you might get duplicate 'sno' numbers.
|
20,280,757 |
I have a question regarding fetch data in the form of table. i have a table with a single row now i just want amount increased on the basis on given logic..
like
```
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
```
logic is 10% add with previous amount
My table is
```
Sno - Name- Amount
1 - A - 1200
```
Now I want result like this..
```
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
```
Can anybody help me i'm not find any logic for that
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20280757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016777/"
] |
```
WITH COUNTER(RN)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.objects
),
A(RN, value)
AS
(
SELECT CAST(1 as bigint),
CAST(1200 as decimal(20, 0))
UNION ALL
SELECT COUNTER.RN,
CAST(A.value*1.1 as decimal(20, 0))
FROM COUNTER JOIN A ON A.RN=COUNTER.RN-1
)
SELECT TOP 1000 *
FROM A
OPTION(MAXRECURSION 1000)
```
This example selects first 1000 rows from sys.objects. You should replace **sys.objects** with your table name and **object\_id** with primary/unique key column(s). Also you should change **TOP 1000** and **MAXRECURSION 1000**. Notice MAXRECURSION ะผะฐั be between 0 and 32767, 0 - no limit.
Be aware of large tables, because it can cause arithmetic overflow of value.
|
Remodified answer to use cte instead:
```
DECLARE @T TABLE (sno INT, name CHAR(1), amount INT)
INSERT INTO @T
SELECT 1, 'a', 1200
;WITH cte AS (
SELECT sno, name, amount
FROM @T
WHERE sno = 1
UNION ALL
SELECT sno+1, name, amount + amount / 10
FROM cte
WHERE sno+1 <= 100
)
SELECT *
FROM cte
```
Results:
```
sno name amount
1 a 1200
2 a 1320
3 a 1452
4 a 1597
5 a 1756
6 a 1931
```
|
20,280,757 |
I have a question regarding fetch data in the form of table. i have a table with a single row now i just want amount increased on the basis on given logic..
like
```
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
```
logic is 10% add with previous amount
My table is
```
Sno - Name- Amount
1 - A - 1200
```
Now I want result like this..
```
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
```
Can anybody help me i'm not find any logic for that
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20280757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016777/"
] |
This has exactly the same limitation as WadimX's answer, but it'll do 100 rows. To produce your example output given your input table (which I'll refer to as `example`):
```
;WITH nums AS
(SELECT 1 AS RowNum, Name, Amount
FROM (SELECT Name, Amount FROM example) s
UNION ALL
SELECT RowNum + 1 As RowNum, Name, CAST(1.1*Amount AS INT) AS Amount
FROM nums
WHERE RowNum < 5)
SELECT RowNum AS SNo, Name, Amount
FROM nums
ORDER BY Name
```
[SQLFiddle](http://sqlfiddle.com/#!3/524ae/1/0)
That returns 5 rows for every record in `example`, you can increase that count by changing the `RowNum < 5` to `100` or however many you want.
**Output**
```
SNo Name Amount
-----------------------
1 A 1200
2 A 1320
3 A 1452
... ... ...
```
|
```
WITH COUNTER(RN)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.objects
),
A(RN, value)
AS
(
SELECT CAST(1 as bigint),
CAST(1200 as decimal(20, 0))
UNION ALL
SELECT COUNTER.RN,
CAST(A.value*1.1 as decimal(20, 0))
FROM COUNTER JOIN A ON A.RN=COUNTER.RN-1
)
SELECT TOP 1000 *
FROM A
OPTION(MAXRECURSION 1000)
```
This example selects first 1000 rows from sys.objects. You should replace **sys.objects** with your table name and **object\_id** with primary/unique key column(s). Also you should change **TOP 1000** and **MAXRECURSION 1000**. Notice MAXRECURSION ะผะฐั be between 0 and 32767, 0 - no limit.
Be aware of large tables, because it can cause arithmetic overflow of value.
|
20,280,757 |
I have a question regarding fetch data in the form of table. i have a table with a single row now i just want amount increased on the basis on given logic..
like
```
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
```
logic is 10% add with previous amount
My table is
```
Sno - Name- Amount
1 - A - 1200
```
Now I want result like this..
```
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
```
Can anybody help me i'm not find any logic for that
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20280757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016777/"
] |
This has exactly the same limitation as WadimX's answer, but it'll do 100 rows. To produce your example output given your input table (which I'll refer to as `example`):
```
;WITH nums AS
(SELECT 1 AS RowNum, Name, Amount
FROM (SELECT Name, Amount FROM example) s
UNION ALL
SELECT RowNum + 1 As RowNum, Name, CAST(1.1*Amount AS INT) AS Amount
FROM nums
WHERE RowNum < 5)
SELECT RowNum AS SNo, Name, Amount
FROM nums
ORDER BY Name
```
[SQLFiddle](http://sqlfiddle.com/#!3/524ae/1/0)
That returns 5 rows for every record in `example`, you can increase that count by changing the `RowNum < 5` to `100` or however many you want.
**Output**
```
SNo Name Amount
-----------------------
1 A 1200
2 A 1320
3 A 1452
... ... ...
```
|
Remodified answer to use cte instead:
```
DECLARE @T TABLE (sno INT, name CHAR(1), amount INT)
INSERT INTO @T
SELECT 1, 'a', 1200
;WITH cte AS (
SELECT sno, name, amount
FROM @T
WHERE sno = 1
UNION ALL
SELECT sno+1, name, amount + amount / 10
FROM cte
WHERE sno+1 <= 100
)
SELECT *
FROM cte
```
Results:
```
sno name amount
1 a 1200
2 a 1320
3 a 1452
4 a 1597
5 a 1756
6 a 1931
```
|
30,103,425 |
I am trying to find the dominant color of an image. I am using [ColorMine](https://github.com/THEjoezack/ColorMine) to do the color comparison. Basically I have a template of colors that I compare each pixel against.
The color with the least distance gets elected from the template as the representative of that pixel.
```
public class ColorItem
{
public enum Colors
{
White ,
Black ,
Gray ,
Red ,
Orange ,
Yellow ,
Green ,
Cyan ,
Blue ,
Magenta,
Pink ,
Brown ,
None,
}
public ColorItem(Color color, Colors colorType)
{
this.color = color;
this.colorType = colorType;
}
public Colors colorType;
public Color color;
}
//The color template that I am comparing against, which I cannot help but to
//Think that this is the issue
public class ColorTemplate
{
public static Color white = Color.FromArgb(255,255,255);
public static Color black = Color.FromArgb(0, 0, 0);
public static Color gray = Color.FromArgb(150, 150, 150);
public static Color red = Color.FromArgb(255, 0, 0);
public static Color orange = Color.FromArgb(255, 150, 0);
public static Color yellow = Color.FromArgb(255, 255, 0);
public static Color green = Color.FromArgb(0, 255, 0);
public static Color cyan = Color.FromArgb(0, 255, 255);
public static Color blue = Color.FromArgb(0, 0, 255);
public static Color magenta = Color.FromArgb(255, 0, 255);
public static Color pink = Color.FromArgb(255, 150, 255);
public static Color brown = Color.FromArgb(150, 90, 25);
}
private static List<ColorItem> _template = new List<ColorItem>
{
new ColorItem(ColorTemplate.black, ColorItem.Colors.Black),
new ColorItem(ColorTemplate.blue, ColorItem.Colors.Blue),
new ColorItem(ColorTemplate.brown, ColorItem.Colors.Brown),
new ColorItem(ColorTemplate.cyan, ColorItem.Colors.Cyan),
new ColorItem(ColorTemplate.gray, ColorItem.Colors.Gray),
new ColorItem(ColorTemplate.green, ColorItem.Colors.Green),
new ColorItem(ColorTemplate.magenta, ColorItem.Colors.Magenta),
new ColorItem(ColorTemplate.orange, ColorItem.Colors.Orange),
new ColorItem(ColorTemplate.pink, ColorItem.Colors.Pink),
new ColorItem(ColorTemplate.red, ColorItem.Colors.Red),
new ColorItem(ColorTemplate.white, ColorItem.Colors.White),
new ColorItem(ColorTemplate.yellow, ColorItem.Colors.Yellow)
};
public bool GetDominantColor(string filePath, out List<ColorPercentages> domColor)
{
domColor = new List<ColorPercentages>();
Bitmap bmp = null;
try
{
bmp = new Bitmap(filePath);
}
catch (Exception)
{
}
if (bmp == null)
return false;
//Used for tally
var total = 0;
var countWhite = 0;
var countBlack = 0;
var countGray = 0;
var countRed = 0;
var countOrange = 0;
var countYellow = 0;
var countGreen = 0;
var countCyan = 0;
var countBlue = 0;
var countMagenta = 0;
var countPink = 0;
var countBrown = 0;
for (var x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
total++;
var clr = bmp.GetPixel(x, y);
var near = FindNearestColor(clr);
switch (near)
{
case ColorItem.Colors.Black:
countBlack++;
break;
case ColorItem.Colors.Blue:
countBlue++;
break;
case ColorItem.Colors.Brown:
countBrown++;
break;
case ColorItem.Colors.Cyan:
countCyan++;
break;
case ColorItem.Colors.Gray:
countGray++;
break;
case ColorItem.Colors.Green:
countGreen++;
break;
case ColorItem.Colors.Magenta:
countMagenta++;
break;
case ColorItem.Colors.Orange:
countOrange++;
break;
case ColorItem.Colors.Pink:
countPink++;
break;
case ColorItem.Colors.Red:
countRed++;
break;
case ColorItem.Colors.White:
countWhite++;
break;
case ColorItem.Colors.Yellow:
countYellow++;
break;
}
}
}
domColor.Add(new ColorPercentages((int)(((double)countWhite / (double)total) * 100), ColorItem.Colors.White));
domColor.Add(new ColorPercentages((int)(((double)countBlack / (double)total) * 100), ColorItem.Colors.Black));
domColor.Add(new ColorPercentages((int)(((double)countGray / (double)total) * 100), ColorItem.Colors.Gray));
domColor.Add(new ColorPercentages((int)(((double)countRed / (double)total) * 100), ColorItem.Colors.Red));
domColor.Add(new ColorPercentages((int)(((double)countOrange / (double)total) * 100), ColorItem.Colors.Orange));
domColor.Add(new ColorPercentages((int)(((double)countYellow / (double)total) * 100), ColorItem.Colors.Yellow));
domColor.Add(new ColorPercentages((int)(((double)countGreen / (double)total) * 100), ColorItem.Colors.Green));
domColor.Add(new ColorPercentages((int)(((double)countCyan / (double)total) * 100), ColorItem.Colors.Cyan));
domColor.Add(new ColorPercentages((int)(((double)countBlue / (double)total) * 100), ColorItem.Colors.Blue));
domColor.Add(new ColorPercentages((int)(((double)countMagenta / (double)total) * 100), ColorItem.Colors.Magenta));
domColor.Add(new ColorPercentages((int)(((double)countPink / (double)total) * 100), ColorItem.Colors.Pink));
domColor.Add(new ColorPercentages((int)(((double)countBrown / (double)total) * 100), ColorItem.Colors.Brown));
domColor.Sort(new SortColorPercentagesDescending());
return true;
}
private ColorItem.Colors FindNearestColor(Color input)
{
ColorItem.Colors nearest_color = ColorItem.Colors.None;
var distance = 255.0;
Rgb inColoRgb = new Rgb {R = input.R, G = input.G, B = input.B};
Lab inColorLab = inColoRgb.To<Lab>();
foreach (var colorItem in _template)
{
Rgb templateColorRgb = new Rgb {R = colorItem.color.R, G = colorItem.color.G, B = colorItem.color.B};
Lab templateColorLab = templateColorRgb.To<Lab>();
var target = new CieDe2000Comparison();
var tempRes = inColoRgb.Compare(templateColorRgb, target);
if (tempRes == 0.0)
{
nearest_color = colorItem.colorType;
break;
}
else if (tempRes < distance)
{
distance = tempRes;
nearest_color = colorItem.colorType;
}
}
return nearest_color;
}
public class SortColorPercentagesDescending : Comparer<ColorPercentages>
{
public override int Compare(ColorPercentages x, ColorPercentages y)
{
if (x == null || y == null)
return -1;
if (x.Percentage > y.Percentage)
return -1;
if (x.Percentage < y.Percentage)
return 1;
return 0;
}
}
public class ColorPercentages
{
public int Percentage;
public ColorItem.Colors Color;
public ColorPercentages(int percentage, ColorItem.Colors color)
{
Percentage = percentage;
Color = color;
}
}
```
The two main functions here are `GetDominantColor` and `FindNearestColor`. The first loads an image file in a bitmap and iterates over each pixel, finds the nearest color and increments that color's count. Once it goes over all the pixels it calculate the occurrence percentage of each color and returns them in a list to the caller sorted by the colors' percentages.
The `FindNearestColor` function compares each pixel to a hardcoded template using ColorMine's CieDe2000Comparison implementation and returns the closest template color as the pixel's color.
Now, I cannot help but think that the issue is with the template of colors I am using. I am not sure how to adjust those to give accurate results. I tried halving the RGB values and the results got somewhat better yet not to the point where it is accurate. For example, Yellow images returns the dominant color as White. Dark Green Images returns the dominant color as Black and so on.
How can I make this work
EDIT: I am not looking to find the average color of the image. What I am looking for is a way to categorize/map the color of each pixel to a specific pre-defined color and then find the most repeated color.
|
2015/05/07
|
[
"https://Stackoverflow.com/questions/30103425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127602/"
] |
I had to do something similar. As input colors I used all values in System.Drawing.KnownColor, but you can change that part pretty easily.
The code below gets the color most often used in an image and then tries to match it a known color.
```
class Program
{
static void Main(string[] args)
{
var image = (Bitmap)Image.FromFile(@"C:\temp\colorimage3.bmp");
var mostUsedColor = GetMostUsedColor(image);
var color = GetNearestColor(mostUsedColor);
Console.WriteLine(color.Name);
Console.ReadKey();
}
private static Color GetNearestColor(Color inputColor)
{
var inputRed = Convert.ToDouble(inputColor.R);
var inputGreen = Convert.ToDouble(inputColor.G);
var inputBlue = Convert.ToDouble(inputColor.B);
var colors = new List<Color>();
foreach (var knownColor in Enum.GetValues(typeof(KnownColor)))
{
var color = Color.FromKnownColor((KnownColor) knownColor);
if (!color.IsSystemColor)
colors.Add(color);
}
var nearestColor = Color.Empty;
var distance = 500.0;
foreach (var color in colors)
{
// Compute Euclidean distance between the two colors
var testRed = Math.Pow(Convert.ToDouble(color.R) - inputRed, 2.0);
var testGreen = Math.Pow(Convert.ToDouble(color.G) - inputGreen, 2.0);
var testBlue = Math.Pow(Convert.ToDouble(color.B) - inputBlue, 2.0);
var tempDistance = Math.Sqrt(testBlue + testGreen + testRed);
if (tempDistance == 0.0)
return color;
if (tempDistance < distance)
{
distance = tempDistance;
nearestColor = color;
}
}
return nearestColor;
}
public static Color GetMostUsedColor(Bitmap bitMap)
{
var colorIncidence = new Dictionary<int, int>();
for (var x = 0; x < bitMap.Size.Width; x++)
for (var y = 0; y < bitMap.Size.Height; y++)
{
var pixelColor = bitMap.GetPixel(x, y).ToArgb();
if (colorIncidence.Keys.Contains(pixelColor))
colorIncidence[pixelColor]++;
else
colorIncidence.Add(pixelColor, 1);
}
return Color.FromArgb(colorIncidence.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value).First().Key);
}
}
```
|
It looks to me like your starting values for `ColourTemplate` is a little off what you expect them to be.
One solution would be to categorise all a whole range of colours (try googling "CIE colour"), and seeing where you agree and disagree with your programs categorisation.
Pseudo code:
```
Image CategoriseImage (Image input) {
Image result = new Image(input.height, image.width);
foreach (pixel in input) {
colour c = FindNearestColour(pixel);
result.SetColour(c, pixel.x, pixel.y);
}
return result;
}
```
Then you can save the image or display it. It might involve a little trial-and-error, but you should be able to move the seed values in `ColourTemplate` around until you are happy with what they categorise each colour as.
|
30,103,425 |
I am trying to find the dominant color of an image. I am using [ColorMine](https://github.com/THEjoezack/ColorMine) to do the color comparison. Basically I have a template of colors that I compare each pixel against.
The color with the least distance gets elected from the template as the representative of that pixel.
```
public class ColorItem
{
public enum Colors
{
White ,
Black ,
Gray ,
Red ,
Orange ,
Yellow ,
Green ,
Cyan ,
Blue ,
Magenta,
Pink ,
Brown ,
None,
}
public ColorItem(Color color, Colors colorType)
{
this.color = color;
this.colorType = colorType;
}
public Colors colorType;
public Color color;
}
//The color template that I am comparing against, which I cannot help but to
//Think that this is the issue
public class ColorTemplate
{
public static Color white = Color.FromArgb(255,255,255);
public static Color black = Color.FromArgb(0, 0, 0);
public static Color gray = Color.FromArgb(150, 150, 150);
public static Color red = Color.FromArgb(255, 0, 0);
public static Color orange = Color.FromArgb(255, 150, 0);
public static Color yellow = Color.FromArgb(255, 255, 0);
public static Color green = Color.FromArgb(0, 255, 0);
public static Color cyan = Color.FromArgb(0, 255, 255);
public static Color blue = Color.FromArgb(0, 0, 255);
public static Color magenta = Color.FromArgb(255, 0, 255);
public static Color pink = Color.FromArgb(255, 150, 255);
public static Color brown = Color.FromArgb(150, 90, 25);
}
private static List<ColorItem> _template = new List<ColorItem>
{
new ColorItem(ColorTemplate.black, ColorItem.Colors.Black),
new ColorItem(ColorTemplate.blue, ColorItem.Colors.Blue),
new ColorItem(ColorTemplate.brown, ColorItem.Colors.Brown),
new ColorItem(ColorTemplate.cyan, ColorItem.Colors.Cyan),
new ColorItem(ColorTemplate.gray, ColorItem.Colors.Gray),
new ColorItem(ColorTemplate.green, ColorItem.Colors.Green),
new ColorItem(ColorTemplate.magenta, ColorItem.Colors.Magenta),
new ColorItem(ColorTemplate.orange, ColorItem.Colors.Orange),
new ColorItem(ColorTemplate.pink, ColorItem.Colors.Pink),
new ColorItem(ColorTemplate.red, ColorItem.Colors.Red),
new ColorItem(ColorTemplate.white, ColorItem.Colors.White),
new ColorItem(ColorTemplate.yellow, ColorItem.Colors.Yellow)
};
public bool GetDominantColor(string filePath, out List<ColorPercentages> domColor)
{
domColor = new List<ColorPercentages>();
Bitmap bmp = null;
try
{
bmp = new Bitmap(filePath);
}
catch (Exception)
{
}
if (bmp == null)
return false;
//Used for tally
var total = 0;
var countWhite = 0;
var countBlack = 0;
var countGray = 0;
var countRed = 0;
var countOrange = 0;
var countYellow = 0;
var countGreen = 0;
var countCyan = 0;
var countBlue = 0;
var countMagenta = 0;
var countPink = 0;
var countBrown = 0;
for (var x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
total++;
var clr = bmp.GetPixel(x, y);
var near = FindNearestColor(clr);
switch (near)
{
case ColorItem.Colors.Black:
countBlack++;
break;
case ColorItem.Colors.Blue:
countBlue++;
break;
case ColorItem.Colors.Brown:
countBrown++;
break;
case ColorItem.Colors.Cyan:
countCyan++;
break;
case ColorItem.Colors.Gray:
countGray++;
break;
case ColorItem.Colors.Green:
countGreen++;
break;
case ColorItem.Colors.Magenta:
countMagenta++;
break;
case ColorItem.Colors.Orange:
countOrange++;
break;
case ColorItem.Colors.Pink:
countPink++;
break;
case ColorItem.Colors.Red:
countRed++;
break;
case ColorItem.Colors.White:
countWhite++;
break;
case ColorItem.Colors.Yellow:
countYellow++;
break;
}
}
}
domColor.Add(new ColorPercentages((int)(((double)countWhite / (double)total) * 100), ColorItem.Colors.White));
domColor.Add(new ColorPercentages((int)(((double)countBlack / (double)total) * 100), ColorItem.Colors.Black));
domColor.Add(new ColorPercentages((int)(((double)countGray / (double)total) * 100), ColorItem.Colors.Gray));
domColor.Add(new ColorPercentages((int)(((double)countRed / (double)total) * 100), ColorItem.Colors.Red));
domColor.Add(new ColorPercentages((int)(((double)countOrange / (double)total) * 100), ColorItem.Colors.Orange));
domColor.Add(new ColorPercentages((int)(((double)countYellow / (double)total) * 100), ColorItem.Colors.Yellow));
domColor.Add(new ColorPercentages((int)(((double)countGreen / (double)total) * 100), ColorItem.Colors.Green));
domColor.Add(new ColorPercentages((int)(((double)countCyan / (double)total) * 100), ColorItem.Colors.Cyan));
domColor.Add(new ColorPercentages((int)(((double)countBlue / (double)total) * 100), ColorItem.Colors.Blue));
domColor.Add(new ColorPercentages((int)(((double)countMagenta / (double)total) * 100), ColorItem.Colors.Magenta));
domColor.Add(new ColorPercentages((int)(((double)countPink / (double)total) * 100), ColorItem.Colors.Pink));
domColor.Add(new ColorPercentages((int)(((double)countBrown / (double)total) * 100), ColorItem.Colors.Brown));
domColor.Sort(new SortColorPercentagesDescending());
return true;
}
private ColorItem.Colors FindNearestColor(Color input)
{
ColorItem.Colors nearest_color = ColorItem.Colors.None;
var distance = 255.0;
Rgb inColoRgb = new Rgb {R = input.R, G = input.G, B = input.B};
Lab inColorLab = inColoRgb.To<Lab>();
foreach (var colorItem in _template)
{
Rgb templateColorRgb = new Rgb {R = colorItem.color.R, G = colorItem.color.G, B = colorItem.color.B};
Lab templateColorLab = templateColorRgb.To<Lab>();
var target = new CieDe2000Comparison();
var tempRes = inColoRgb.Compare(templateColorRgb, target);
if (tempRes == 0.0)
{
nearest_color = colorItem.colorType;
break;
}
else if (tempRes < distance)
{
distance = tempRes;
nearest_color = colorItem.colorType;
}
}
return nearest_color;
}
public class SortColorPercentagesDescending : Comparer<ColorPercentages>
{
public override int Compare(ColorPercentages x, ColorPercentages y)
{
if (x == null || y == null)
return -1;
if (x.Percentage > y.Percentage)
return -1;
if (x.Percentage < y.Percentage)
return 1;
return 0;
}
}
public class ColorPercentages
{
public int Percentage;
public ColorItem.Colors Color;
public ColorPercentages(int percentage, ColorItem.Colors color)
{
Percentage = percentage;
Color = color;
}
}
```
The two main functions here are `GetDominantColor` and `FindNearestColor`. The first loads an image file in a bitmap and iterates over each pixel, finds the nearest color and increments that color's count. Once it goes over all the pixels it calculate the occurrence percentage of each color and returns them in a list to the caller sorted by the colors' percentages.
The `FindNearestColor` function compares each pixel to a hardcoded template using ColorMine's CieDe2000Comparison implementation and returns the closest template color as the pixel's color.
Now, I cannot help but think that the issue is with the template of colors I am using. I am not sure how to adjust those to give accurate results. I tried halving the RGB values and the results got somewhat better yet not to the point where it is accurate. For example, Yellow images returns the dominant color as White. Dark Green Images returns the dominant color as Black and so on.
How can I make this work
EDIT: I am not looking to find the average color of the image. What I am looking for is a way to categorize/map the color of each pixel to a specific pre-defined color and then find the most repeated color.
|
2015/05/07
|
[
"https://Stackoverflow.com/questions/30103425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127602/"
] |
I had to do something similar. As input colors I used all values in System.Drawing.KnownColor, but you can change that part pretty easily.
The code below gets the color most often used in an image and then tries to match it a known color.
```
class Program
{
static void Main(string[] args)
{
var image = (Bitmap)Image.FromFile(@"C:\temp\colorimage3.bmp");
var mostUsedColor = GetMostUsedColor(image);
var color = GetNearestColor(mostUsedColor);
Console.WriteLine(color.Name);
Console.ReadKey();
}
private static Color GetNearestColor(Color inputColor)
{
var inputRed = Convert.ToDouble(inputColor.R);
var inputGreen = Convert.ToDouble(inputColor.G);
var inputBlue = Convert.ToDouble(inputColor.B);
var colors = new List<Color>();
foreach (var knownColor in Enum.GetValues(typeof(KnownColor)))
{
var color = Color.FromKnownColor((KnownColor) knownColor);
if (!color.IsSystemColor)
colors.Add(color);
}
var nearestColor = Color.Empty;
var distance = 500.0;
foreach (var color in colors)
{
// Compute Euclidean distance between the two colors
var testRed = Math.Pow(Convert.ToDouble(color.R) - inputRed, 2.0);
var testGreen = Math.Pow(Convert.ToDouble(color.G) - inputGreen, 2.0);
var testBlue = Math.Pow(Convert.ToDouble(color.B) - inputBlue, 2.0);
var tempDistance = Math.Sqrt(testBlue + testGreen + testRed);
if (tempDistance == 0.0)
return color;
if (tempDistance < distance)
{
distance = tempDistance;
nearestColor = color;
}
}
return nearestColor;
}
public static Color GetMostUsedColor(Bitmap bitMap)
{
var colorIncidence = new Dictionary<int, int>();
for (var x = 0; x < bitMap.Size.Width; x++)
for (var y = 0; y < bitMap.Size.Height; y++)
{
var pixelColor = bitMap.GetPixel(x, y).ToArgb();
if (colorIncidence.Keys.Contains(pixelColor))
colorIncidence[pixelColor]++;
else
colorIncidence.Add(pixelColor, 1);
}
return Color.FromArgb(colorIncidence.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value).First().Key);
}
}
```
|
Its difficult to interpret what 'dominant color' really means in your question without a more precise definition or knowing what the application is.
The [Image Color Summarizer](http://mkweb.bcgsc.ca/color_summarizer/?examples) web service examples show that a straight pixel average is pretty good.
You can try some of the images you're working with on that site to get some idea of whether average/median stats are enough for your purpose.
[This answer](https://stackoverflow.com/a/28799108/909199) suggests using k-means quantization which looks pretty good too.
|
18,534,591 |
I am developing a command line node module and would like to be able to launch it via links on a website.
I want to register a custom protocol `my-module://` such that links would have the following format: `my-module://action:some-action` and clicking on them would start the node package.
If there isn't a node API for this (I'm sure there won't be) then is there a way I can do it from node by invoking system commands?
It must work on Windows, Linux, and MacOS.
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18534591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568805/"
] |
Its an interesting idea. I don't think there is currently a cross platform node.js solution out there. I did come across this thread of people asking for the same thing:
```
https://github.com/rogerwang/node-webkit/issues/951
```
Electron now supports it with the [`app.setAsDefaultProtocolClient`](http://electron.atom.io/docs/api/app/#appsetasdefaultprotocolclientprotocol-path-args-macos-windows) API ([since v0.37.4](https://github.com/electron/electron/releases/tag/v0.37.4)) for macOS and Windows.
It wouldn't be terribly difficult to write the library to do this.
**Windows**:
On the windows side you'd have to register the app as the application that handles that URI scheme.
You'll need to set up a registry entry for your application:
```
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe" "%1"
```
Then, when your application is run by windows, you should be able to see the arguments in `process.argv[]`. Make sure that you launch a shell to run node, not just your application directly.
[Original MSDN article](http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx)
Note this requires administrator privileges and sets the handler system-wide. To do it per user, you can use `HKEY_CURRENT_USER\Software\Classes` instead, as the Electron's implementation [does it](https://github.com/electron/electron/blob/4ec7cc913d840ee211a92afa13f260681d8bf8f9/atom/browser/browser_win.cc#L203).
**Apple:**
The cited "OS X" article in the github comment is actually for iOS. I'd look at the following programming guide for info on registering an application to handle a URL scheme:
[Apple Dev Documentation](https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCConcepts/LSCConcepts.html#//apple_ref/doc/uid/TP30000999-CH202-CIHFEEAD)
In summary, you'll need to create a launch service and populate the .plist file with `CFBundleURLTypes`, this field is an array and should be populated with just the protocol name i.e. `http`
The following [Super User Question](https://superuser.com/questions/548119/how-do-i-configure-custom-url-handlers-on-os-x) has a better solution, but is a per user setting.
"The file you seek is ~/Library/Preferences/com.apple.LaunchServices.plist.
It holds an array called LSHandlers, and the Dictionary children that define an LSHandlerURLScheme can be modified accordingly with the LSHandlerRole."
**Linux:**
From what I can tell, there are several ways to accomplish this in Linux (surprise?)
Gnome has a tool that will let you register a url handler [w3 archives](http://people.w3.org/~dom/archives/2005/09/integrating-a-new-uris-scheme-handler-to-gnome-and-firefox/)
```
gconftool-2 -t string -s /desktop/gnome/url-handlers/tel/command "bin/vonage-call %s"
gconftool-2 -s /desktop/gnome/url-handlers/tel/needs_terminal false -t bool
gconftool-2 -t bool -s /desktop/gnome/url-handlers/tel/enabled true
```
Some of the lighter weight managers look like they allow you to create fake mime types and register them as URI Protocol handlers.
"Fake mime-types are created for URIs with various scheme like this:
application/x-xdg-protocol-
Applications supporting specific URI protocol can add the fake mime-type to their MimeType key in their desktop entry files. So it's easy to find out all applications installed on the system supporting a URI scheme by looking in mimeinfo.cache file. Again defaults.list file can be used to specify a default program for speficied URI type." [wiki.lxde.org](http://wiki.lxde.org/en/Desktop_Preferred_Applications_Specification)
KDE also supports their own method of handling URL Protocol Handlers:
Create a file: `$KDEDIR/share/services/your.protocol` and populate it with relevant data:
```
[Protocol]
exec=/path/to/player "%u"
protocol=lastfm
input=none
output=none
helper=true
listing=
reading=false
writing=false
makedir=false
deleting=false
```
from [last.fm forums](http://www.last.fm/forum/21714/_/42837/1#f430232) of all places
Hope that helps.
|
Here's how I did on Mac OS with an application NW.js :
1. Open the app `/Applications/Utilities/Script Editor`
type the following code in the editor
```
on open location this_URL
do shell script "/Applications/X.app/Contents/MacOS/x '" & this_URL & "'"
end open location
```
Replace *X* by the name of your App.
Save the script as an *Application Bundle* anywhere
2. Go to the script, right click then '*Show Package Contents*' then edit `Contents/info.plist`
Add these lines at the end of the file, just before `</dict></plist>` :
```
<key>CFBundleIdentifier</key>
<string>com.mycompany.AppleScript.AppName</string> <!-- edit here -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>AppName</string> <!-- edit here -->
<key>CFBundleURLSchemes</key>
<array>
<string>myurlscheme</string> <!-- your url scheme here -->
</array>
</dict>
</array>
```
3. You can now open a link starting with *myurlscheme:* and see your app is opening!
|
18,534,591 |
I am developing a command line node module and would like to be able to launch it via links on a website.
I want to register a custom protocol `my-module://` such that links would have the following format: `my-module://action:some-action` and clicking on them would start the node package.
If there isn't a node API for this (I'm sure there won't be) then is there a way I can do it from node by invoking system commands?
It must work on Windows, Linux, and MacOS.
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18534591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568805/"
] |
Its an interesting idea. I don't think there is currently a cross platform node.js solution out there. I did come across this thread of people asking for the same thing:
```
https://github.com/rogerwang/node-webkit/issues/951
```
Electron now supports it with the [`app.setAsDefaultProtocolClient`](http://electron.atom.io/docs/api/app/#appsetasdefaultprotocolclientprotocol-path-args-macos-windows) API ([since v0.37.4](https://github.com/electron/electron/releases/tag/v0.37.4)) for macOS and Windows.
It wouldn't be terribly difficult to write the library to do this.
**Windows**:
On the windows side you'd have to register the app as the application that handles that URI scheme.
You'll need to set up a registry entry for your application:
```
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe" "%1"
```
Then, when your application is run by windows, you should be able to see the arguments in `process.argv[]`. Make sure that you launch a shell to run node, not just your application directly.
[Original MSDN article](http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx)
Note this requires administrator privileges and sets the handler system-wide. To do it per user, you can use `HKEY_CURRENT_USER\Software\Classes` instead, as the Electron's implementation [does it](https://github.com/electron/electron/blob/4ec7cc913d840ee211a92afa13f260681d8bf8f9/atom/browser/browser_win.cc#L203).
**Apple:**
The cited "OS X" article in the github comment is actually for iOS. I'd look at the following programming guide for info on registering an application to handle a URL scheme:
[Apple Dev Documentation](https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCConcepts/LSCConcepts.html#//apple_ref/doc/uid/TP30000999-CH202-CIHFEEAD)
In summary, you'll need to create a launch service and populate the .plist file with `CFBundleURLTypes`, this field is an array and should be populated with just the protocol name i.e. `http`
The following [Super User Question](https://superuser.com/questions/548119/how-do-i-configure-custom-url-handlers-on-os-x) has a better solution, but is a per user setting.
"The file you seek is ~/Library/Preferences/com.apple.LaunchServices.plist.
It holds an array called LSHandlers, and the Dictionary children that define an LSHandlerURLScheme can be modified accordingly with the LSHandlerRole."
**Linux:**
From what I can tell, there are several ways to accomplish this in Linux (surprise?)
Gnome has a tool that will let you register a url handler [w3 archives](http://people.w3.org/~dom/archives/2005/09/integrating-a-new-uris-scheme-handler-to-gnome-and-firefox/)
```
gconftool-2 -t string -s /desktop/gnome/url-handlers/tel/command "bin/vonage-call %s"
gconftool-2 -s /desktop/gnome/url-handlers/tel/needs_terminal false -t bool
gconftool-2 -t bool -s /desktop/gnome/url-handlers/tel/enabled true
```
Some of the lighter weight managers look like they allow you to create fake mime types and register them as URI Protocol handlers.
"Fake mime-types are created for URIs with various scheme like this:
application/x-xdg-protocol-
Applications supporting specific URI protocol can add the fake mime-type to their MimeType key in their desktop entry files. So it's easy to find out all applications installed on the system supporting a URI scheme by looking in mimeinfo.cache file. Again defaults.list file can be used to specify a default program for speficied URI type." [wiki.lxde.org](http://wiki.lxde.org/en/Desktop_Preferred_Applications_Specification)
KDE also supports their own method of handling URL Protocol Handlers:
Create a file: `$KDEDIR/share/services/your.protocol` and populate it with relevant data:
```
[Protocol]
exec=/path/to/player "%u"
protocol=lastfm
input=none
output=none
helper=true
listing=
reading=false
writing=false
makedir=false
deleting=false
```
from [last.fm forums](http://www.last.fm/forum/21714/_/42837/1#f430232) of all places
Hope that helps.
|
### Edit :
Looks like the module has changed the registration process for good:
```js
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // sets protocol for your command , testproto://**
command: `node ${path.join(__dirname, './tester.js')} $_URL_`, // this will be executed with a extra argument %url from which it was initiated
override: true, // Use this with caution as it will destroy all previous Registrations on this protocol
terminal: true, // Use this to run your command inside a terminal
script: false
}).then(async () => {
console.log('Successfully registered');
});
```
### Original Answer :
There is an npm module for this purpose.
link :<https://www.npmjs.com/package/protocol-registry>
So to do this in nodejs you just need to run the code below:
First Install it
```
npm i protocol-registry
```
Then use the code below to register you entry file.
```js
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // set your app for testproto://**
command: `node ${path.join(__dirname, './index.js')}`, // this will be executed with a extra argument %url from which it was initiated
}).then(async () => {
console.log('Successfully registered');
});
```
Then suppose someone opens testproto://test
then a new terminal will be launched executing :
```
node yourapp/index.js testproto://test
```
|
91,790 |
I am working on a Magento e-commerce site.
I need to disable the Catalog Advanced Search.
I checked with source code available in the stackexchange but its not working.
|
2015/11/27
|
[
"https://magento.stackexchange.com/questions/91790",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/33576/"
] |
To remove the link to advanced search edit `app/design/frontend/{package}/{theme}/layout/catalogsearch.xml`.
If the file does not exist in your theme, copy it from `base/default`. Then remove this from the file:
```
<action method="addLink" translate="label title" module="catalogsearch">
<label>Advanced Search</label>
<url helper="catalogsearch/getAdvancedSearchUrl" />
<title>Advanced Search</title>
</action>
```
But this will still leave your controller active, and anyone with a link can access it.
To restrict this, create an observer for the events `controller_action_predispatch_catalogsearch_advanced_index` and `controller_action_predispatch_catalogsearch_advanced_result` with this code:
```
public function restrictAccess($observer)
{
$url = Mage::getUrl('no-route');
Mage::app()->getResponse()->setRedirect($url);
Mage::app()->getResponse()->sendResponse();
}
```
This will redirect the users to a 404 page when trying to access the advanced search form or result page.
|
1. Copy below file in your theme directory
**app/design/frontend/base/default/layout/catalogsearch.xml**
2. search the layout **catalogsearch\_advanced\_index** & Just comment out the code inside that tag to hide the advance search content.
|
6,350,215 |
I have a split view controller in my Ipad app, in which the detail view has subviews which are UITableView's.
The functionality I am trying to implement is to get an info view at the same position of a subview when a button(info button) on the subview is pressed. I need to get this info view by animation and that animation is that when the info button is pressed, that subview alone would flip (UIAnimationOptionFlipFromRight) and the info view would show...
This is how try to implement it -
```
-(void) showInfoView: (id)sender
{
infoView = [[InfoViewController alloc] initWithNibName:@"ViewViewController" bundle:nil];
infoView.view.frame = CGRectMake(250, 300, 200, 200);
[UIView transitionWithView:self.view duration:1
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
[self.view addSubview:infoView.view];
}
completion:nil];
}
```
When I run the simulator and press the info button on any subview, what happens is that the animation happens perfectly, i.e. the subview flips from the right but the infoView is not getting displayed.
It would be great if someone could tell me where I am going wrong here.
|
2011/06/14
|
[
"https://Stackoverflow.com/questions/6350215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/621808/"
] |
The basic steps of performing an animation to onscreen is as follows:
1. Create the view.
2. Move it to the initial (offscreen) position
3. Add to the view hierarchy
4. Perform the animation.
It seems like you're skipping step 3 and possibly step 2.
|
Did you try setting the subview frame to the frame of your superview, i.e
```
info.View.frame = self.view.frame;
```
|
53,564,926 |
I am working on a WordPress site. I have two "Learn More" links on my page. When either one is clicked I would like them to revile the corresponding paragraph above. Currently clicking either or reveals both. It would also be super helpful to have the link text change from "Learn More" to "Close" on click as well.
```js
jQuery(document).ready(function($) {
$(".learnMore").on("click", function(e) {
var $a = $(this).toggleClass("is-active")
$a.text(function(i, t) {
return t === 'Learn More' ? 'Close' : 'Learn More';
});
$( "p" ).siblings( ".reveal" ).slideToggle(500);
});
});
```
```css
.hide-mobile {
display: none;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-one">
<h2>Header One</h2>
<p class="hide-mobile reveal">Etiam ut vehicula velit. Cras ut ipsum id tortor ultrices iaculis. Donec sodales ultricies urna vitae porta.</p>
<a class="button" href="/link-url/">Button One</a>
<a class="learnMore mobile">Learn More</a>
</div>
<div class="box-two">
<h2>Header Two</h2>
<p class="hide-mobile reveal">Morbi et varius elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
<a class="button" href="/link-url-two/">Button Two</a>
<a class="learnMore mobile">Learn More</a>
</div>
```
Any help would be appreciated.
Thanks
|
2018/11/30
|
[
"https://Stackoverflow.com/questions/53564926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2026241/"
] |
Just using the mathmetical way + `numpy` `broadcast`
```
v1=df1.start.values
v2=df1.end.values
s1=df2.start.values
s2=df2.end.values
s=pd.DataFrame(((s2-v1[:,None])>0)&((s1-v2[:,None])<0)).dot(df2.name+'|').str[:-1]
s
Out[737]:
0 FOXP3
1 LOXL1
2 LOXL1|INSN
dtype: object
#df1['New']=s.values
```
|
The question you need to answer, from what you already have, is whether there is anything in the `range` you know.
```
if max(start_1, start_2) <= min(end_1, end_2):
```
You might find better tools in the `interval` module; this does a variety of operations on known intervals; I'm hopeful there are vectorized tools you can use.
|
13,482,532 |
I would like to calculate sums for certain columns and then apply this summation for every row. Unfortunately, I can only get to the first step. How do I now make it happen for each row? I know that R doesn't need loops; what are good approaches?
My matrix (zscore) looks like this:
```
a b c t y
1 3 4 7 7 4
2 4 56 6 6 4
3 3 3 2 1 7
4 3 88 9 9 9
```
Now I would want to calculate the row sum for each row, based on some of the columns. For one row it could look like this:
```
f1 <- sum(zscore[1,1:2], zscore[1,3], zscore[1,5])
```
How do I do that now for each row?
|
2012/11/20
|
[
"https://Stackoverflow.com/questions/13482532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807857/"
] |
You could do something like this:
```
summed <- rowSums(zscore[, c(1, 2, 3, 5)])
```
|
If you don't have NA you can apply this
```
suma.zscore = (zscore$a + zscore$c + zscore$t + zscore$y)
```
|
13,482,532 |
I would like to calculate sums for certain columns and then apply this summation for every row. Unfortunately, I can only get to the first step. How do I now make it happen for each row? I know that R doesn't need loops; what are good approaches?
My matrix (zscore) looks like this:
```
a b c t y
1 3 4 7 7 4
2 4 56 6 6 4
3 3 3 2 1 7
4 3 88 9 9 9
```
Now I would want to calculate the row sum for each row, based on some of the columns. For one row it could look like this:
```
f1 <- sum(zscore[1,1:2], zscore[1,3], zscore[1,5])
```
How do I do that now for each row?
|
2012/11/20
|
[
"https://Stackoverflow.com/questions/13482532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807857/"
] |
You could do something like this:
```
summed <- rowSums(zscore[, c(1, 2, 3, 5)])
```
|
The summation of all individual rows can also be done using the row-wise operations of dplyr (with `col1, col2, col3` defining three selected columns for which the row-wise sum is calculated):
```
library(tidyverse)
df <- df %>%
rowwise() %>%
mutate(rowsum = sum(c(col1, col2,col3)))
```
|
13,482,532 |
I would like to calculate sums for certain columns and then apply this summation for every row. Unfortunately, I can only get to the first step. How do I now make it happen for each row? I know that R doesn't need loops; what are good approaches?
My matrix (zscore) looks like this:
```
a b c t y
1 3 4 7 7 4
2 4 56 6 6 4
3 3 3 2 1 7
4 3 88 9 9 9
```
Now I would want to calculate the row sum for each row, based on some of the columns. For one row it could look like this:
```
f1 <- sum(zscore[1,1:2], zscore[1,3], zscore[1,5])
```
How do I do that now for each row?
|
2012/11/20
|
[
"https://Stackoverflow.com/questions/13482532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807857/"
] |
The summation of all individual rows can also be done using the row-wise operations of dplyr (with `col1, col2, col3` defining three selected columns for which the row-wise sum is calculated):
```
library(tidyverse)
df <- df %>%
rowwise() %>%
mutate(rowsum = sum(c(col1, col2,col3)))
```
|
If you don't have NA you can apply this
```
suma.zscore = (zscore$a + zscore$c + zscore$t + zscore$y)
```
|
117,716 |
I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting.
Creating them in the game scene gives me more options but I have trouble to manipulate the input.
Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not).
How do you make your toggle buttons and how do you develop your GUI?
Any help appreciated.
|
2016/03/04
|
[
"https://gamedev.stackexchange.com/questions/117716",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/76710/"
] |
I am using the canvas UI in Unity 5. And to add a button to screen, I just create a UI Image under my canvas object in Hierarchy view. Change the sprite as required.
Now add "Event Trigger" as shown below.
[](https://i.stack.imgur.com/ImP7I.png)
Next "Add new event type". I use "PointerUp".
[](https://i.stack.imgur.com/xgi6F.png)
You get an empty list.
[](https://i.stack.imgur.com/attAn.png)
Click + to add a function which will be called on the event ("PointerUp" in our case)
[](https://i.stack.imgur.com/2giwY.png)
In the third field insert the object which should have the script (you want to invoke) attached to it. In my example the object is called "LevelUIControls" and it has a script called "LevelControls" attached to it.
[](https://i.stack.imgur.com/ANYno.png)
This should make it easy for you to manipulate input.
|
I prefer UI Elements...
I mostly use UI Elements for static buttons and labels..
When I need dynamic stuff going on (an inventory for example) I just script-instantiate them (using object pools)
|
117,716 |
I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting.
Creating them in the game scene gives me more options but I have trouble to manipulate the input.
Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not).
How do you make your toggle buttons and how do you develop your GUI?
Any help appreciated.
|
2016/03/04
|
[
"https://gamedev.stackexchange.com/questions/117716",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/76710/"
] |
I prefer the scripting way to make the GUI, though it's probably because the only thing I like about making games is scripting.
---
**Slipting way :**
One way to do it is to use the [GUI.Toggle](http://docs.unity3d.com/ScriptReference/GUI.Toggle.html) function in Unity.
---
**Non Scripting Way :**
If you still want to use the new GUI, here's a good tutorial :
[Click me :)](https://www.youtube.com/watch?v=HhB-vTEZtg4)
|
I prefer UI Elements...
I mostly use UI Elements for static buttons and labels..
When I need dynamic stuff going on (an inventory for example) I just script-instantiate them (using object pools)
|
117,716 |
I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting.
Creating them in the game scene gives me more options but I have trouble to manipulate the input.
Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not).
How do you make your toggle buttons and how do you develop your GUI?
Any help appreciated.
|
2016/03/04
|
[
"https://gamedev.stackexchange.com/questions/117716",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/76710/"
] |
I am using the canvas UI in Unity 5. And to add a button to screen, I just create a UI Image under my canvas object in Hierarchy view. Change the sprite as required.
Now add "Event Trigger" as shown below.
[](https://i.stack.imgur.com/ImP7I.png)
Next "Add new event type". I use "PointerUp".
[](https://i.stack.imgur.com/xgi6F.png)
You get an empty list.
[](https://i.stack.imgur.com/attAn.png)
Click + to add a function which will be called on the event ("PointerUp" in our case)
[](https://i.stack.imgur.com/2giwY.png)
In the third field insert the object which should have the script (you want to invoke) attached to it. In my example the object is called "LevelUIControls" and it has a script called "LevelControls" attached to it.
[](https://i.stack.imgur.com/ANYno.png)
This should make it easy for you to manipulate input.
|
I prefer the scripting way to make the GUI, though it's probably because the only thing I like about making games is scripting.
---
**Slipting way :**
One way to do it is to use the [GUI.Toggle](http://docs.unity3d.com/ScriptReference/GUI.Toggle.html) function in Unity.
---
**Non Scripting Way :**
If you still want to use the new GUI, here's a good tutorial :
[Click me :)](https://www.youtube.com/watch?v=HhB-vTEZtg4)
|
40,203,874 |
Is there a way to disable all access to a variable in a certain scope?
Its usage might be similar to this :-
```
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
{//vvv The disable command may be in a block?
disable outerOnly; //<--- I want some thing like this.
outerOnly=4; //should compile error (may be assert fail?)
int c=outerOnly; //should compile error
}
outerOnly=4; //ok
```
If the answer is no, is there any feature closest to this one?
It would be useful in a few situation of debugging.
**Edit:** For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3577745/"
] |
Consider implementing something like this (perhaps with deleted copy constructors and assignment operators):
```
struct disable
{
private:
disable(const disable&) = delete;
disable& operator=(const disable&) = delete;
public:
disable() {}
};
```
Then, placing
```
disable outerOnly;
```
inside the inner scope would result pretty much in the desired errors.
Keep in mind though, as **@Cornstalks** commented, that it may lead to shadowing-related compiler warnings (which, in turn, can usually be disabled on case by case basis).
|
Simply do a `struct Outeronly;`.
Note that the error messages can be perplexing if one is unfamiliar with them.
|
40,203,874 |
Is there a way to disable all access to a variable in a certain scope?
Its usage might be similar to this :-
```
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
{//vvv The disable command may be in a block?
disable outerOnly; //<--- I want some thing like this.
outerOnly=4; //should compile error (may be assert fail?)
int c=outerOnly; //should compile error
}
outerOnly=4; //ok
```
If the answer is no, is there any feature closest to this one?
It would be useful in a few situation of debugging.
**Edit:** For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3577745/"
] |
Consider implementing something like this (perhaps with deleted copy constructors and assignment operators):
```
struct disable
{
private:
disable(const disable&) = delete;
disable& operator=(const disable&) = delete;
public:
disable() {}
};
```
Then, placing
```
disable outerOnly;
```
inside the inner scope would result pretty much in the desired errors.
Keep in mind though, as **@Cornstalks** commented, that it may lead to shadowing-related compiler warnings (which, in turn, can usually be disabled on case by case basis).
|
>
> Is there a way to disable all access to a variable in a certain scope?
>
>
>
No, there is no such feature.
>
> If the answer is no, is there any feature closest to this one?
>
>
>
Instead of a simple block, you could define and call a closure that doesn't capture the undesired variable:
```
int outerOnly;
int innerToo;
[&innerToo]()
{
innerToo = 42; // ok
outerOnly = 4; // fails to compile
int c = outerOnly; // fails to compile
}();
```
|
40,203,874 |
Is there a way to disable all access to a variable in a certain scope?
Its usage might be similar to this :-
```
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
{//vvv The disable command may be in a block?
disable outerOnly; //<--- I want some thing like this.
outerOnly=4; //should compile error (may be assert fail?)
int c=outerOnly; //should compile error
}
outerOnly=4; //ok
```
If the answer is no, is there any feature closest to this one?
It would be useful in a few situation of debugging.
**Edit:** For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3577745/"
] |
Consider implementing something like this (perhaps with deleted copy constructors and assignment operators):
```
struct disable
{
private:
disable(const disable&) = delete;
disable& operator=(const disable&) = delete;
public:
disable() {}
};
```
Then, placing
```
disable outerOnly;
```
inside the inner scope would result pretty much in the desired errors.
Keep in mind though, as **@Cornstalks** commented, that it may lead to shadowing-related compiler warnings (which, in turn, can usually be disabled on case by case basis).
|
Here is pretty straightforward solution:
```
int main()
{
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
#define outerOnly outerOnly_disabled
//outerOnly=4; //error outerOnly_disabled is not declared
//int c=outerOnly; //error
#undef outerOnly
outerOnly=4; //ok
}
```
|
40,203,874 |
Is there a way to disable all access to a variable in a certain scope?
Its usage might be similar to this :-
```
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
{//vvv The disable command may be in a block?
disable outerOnly; //<--- I want some thing like this.
outerOnly=4; //should compile error (may be assert fail?)
int c=outerOnly; //should compile error
}
outerOnly=4; //ok
```
If the answer is no, is there any feature closest to this one?
It would be useful in a few situation of debugging.
**Edit:** For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3577745/"
] |
>
> Is there a way to disable all access to a variable in a certain scope?
>
>
>
No, there is no such feature.
>
> If the answer is no, is there any feature closest to this one?
>
>
>
Instead of a simple block, you could define and call a closure that doesn't capture the undesired variable:
```
int outerOnly;
int innerToo;
[&innerToo]()
{
innerToo = 42; // ok
outerOnly = 4; // fails to compile
int c = outerOnly; // fails to compile
}();
```
|
Simply do a `struct Outeronly;`.
Note that the error messages can be perplexing if one is unfamiliar with them.
|
40,203,874 |
Is there a way to disable all access to a variable in a certain scope?
Its usage might be similar to this :-
```
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
{//vvv The disable command may be in a block?
disable outerOnly; //<--- I want some thing like this.
outerOnly=4; //should compile error (may be assert fail?)
int c=outerOnly; //should compile error
}
outerOnly=4; //ok
```
If the answer is no, is there any feature closest to this one?
It would be useful in a few situation of debugging.
**Edit:** For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3577745/"
] |
>
> Is there a way to disable all access to a variable in a certain scope?
>
>
>
No, there is no such feature.
>
> If the answer is no, is there any feature closest to this one?
>
>
>
Instead of a simple block, you could define and call a closure that doesn't capture the undesired variable:
```
int outerOnly;
int innerToo;
[&innerToo]()
{
innerToo = 42; // ok
outerOnly = 4; // fails to compile
int c = outerOnly; // fails to compile
}();
```
|
Here is pretty straightforward solution:
```
int main()
{
int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4; //ok
#define outerOnly outerOnly_disabled
//outerOnly=4; //error outerOnly_disabled is not declared
//int c=outerOnly; //error
#undef outerOnly
outerOnly=4; //ok
}
```
|
55,988,036 |
I created an apparatus maintenance board for my fire department. Each apparatus has its own tab with the name of that apparatus in cell A1.
Each row below that has room to list issues for that apparatus with column D being a drop-down list for the current progress. I want to be able to format the color of the apparatus name is cell A1 based on multiple values from the drop-down list in column D.
Example, when a maintenance issue is not completed we select from the drop-down list in column D of either `SERVICE SCHEDULED, PENDING, PARTS ORDERED`, etc. I want the apparatus name in A1 to turn red if any cell in column D contains one of those statuses.
|
2019/05/05
|
[
"https://Stackoverflow.com/questions/55988036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11453749/"
] |
1. Verify versions:
```
kubeadm version
kubeadm config view
```
2. Generate default settings for your init command to see your settings (should be modified):
```
kubeadm init --config defaults
```
3. Did you try the solution provided by the output?
```
kubeadm config migrate --old-config old.yaml --new-config new.yaml
```
You can find tutorial about [kubeadm init --config](https://medium.com/@kosta709/kubernetes-by-kubeadm-config-yamls-94e2ee11244)
In addition if you are using older version please take a look for [documentation](https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm-init/#config-file)
>
> It is recommended that you migrate your old v1alpha3 configuration to v1beta1 using the kubeadm config migrate command, because v1alpha3 will be removed in Kubernetes 1.15.
> For more details on each field in the v1beta1 configuration you can navigate to our [API reference pages](https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1)
>
>
>
Migration from old kubeadm config versions:
>
> kubeadm v1.11 should be used to migrate v1alpha1 to v1alpha2; kubeadm v1.12 should be used to translate v1alpha2 to v1alpha3)
>
>
>
Fo the second issue `no InitConfiguration or ClusterConfiguration kind was found in the YAML file` there is also answer in docs:
>
> When executing kubeadm init with the --config option, the following configuration types could be used: InitConfiguration, ClusterConfiguration, KubeProxyConfiguration, KubeletConfiguration, but only one between InitConfiguration and ClusterConfiguration is mandatory.
>
>
>
|
what is the kubernetes version are you using?
try below
apiVersion: kubeadm.k8s.io/v1alpha2
OR
apiVersion: kubeadm.k8s.io/v1alpha3
|
71,395,797 |
I have json file with the following data in it:
```
{
"item1": "value1",
"item2": "value2",
"item3": "value3"
}
```
I also have `Items()` class in a seperate file which has the method `getItems()` method which loads the json file:
```
class Items {
Future<Map<String, dynamic>> getItems() async {
String jsonData =
await rootBundle.loadString('assets/items.json');
Map<String, dynamic> data = jsonDecode(jsonData);
return data;
}
}
```
I also have a scaffold to show the items with `ListView.builder`. I first use `setState` to assign the returned value of `Items().getItems()` to the field `items`. I then use the value of the field inside the `LisView.builder`
```
class ItemList extends StatefulWidget {
const ItemList({Key? key}) : super(key: key);
@override
_ItemListState createState() => _ItemListState();
}
class _ItemListState extends State<ItemList> {
late String items = '';
setItems() async {
final item = await Items().getItems();
setState(() {
items = item.toString();
});
}
@override
initState() {
setItems();
}
@override
Widget build(BuildContext context) {
Map<String, dynamic> data = jsonDecode(items);
debugPrint(data.toString());
debugPrint(items);
return Scaffold(
body: ListView.builder(
itemCount: data.keys.length,
itemBuilder: (c, index) {
return ListTile(
title: Text("key " + data.keys.toList()[index]),
subtitle: Text("value " + data.values.toList()[index]),
);
},
),
);
}
}
```
I am able to show the list of items when i place string hardcoded like this :
`Map<String, dynamic> data = jsonDecode('{ "item1": "#48f542","item2": "value2","item3": "value3"}');`
But i get an error when i use the field `items` like this: `Map<String, dynamic> data = jsonDecode(items);`
I get the error `Unexpected character (at character 2) {item1: value1, item2: value2, item3: value3... ^`
Both ways should work because it is basicly the same data types. I don't know what i am doing wrong.
**Edit**
I want to avoid using models because in my use case for example if i add another item key in the json object then i also need to change the model.
|
2022/03/08
|
[
"https://Stackoverflow.com/questions/71395797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12182218/"
] |
The quick solution would be to replace `yield from io.BytesIO(resp.read())` with the one below (see [FastAPI documentation - `StreamingResponse`](https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects) for more details).
```py
yield from resp
```
However, instead of using `urllib.request` and `resp.read()` (which would read the entire file contents into memory, hence the reason for taking too long to respond), I would suggest you use the [`HTTPX`](https://www.python-httpx.org/) library, which, among other things, provides [`async` support](https://www.python-httpx.org/async/) as well. Also, it supports [Streaming Responses](https://www.python-httpx.org/quickstart/#streaming-responses) (see [`async` Streaming Responses](https://www.python-httpx.org/async/#streaming-responses) too), and thus, you can avoid loading the entire response body into memory at once (especially, when dealing with large files). Below are provided examples in both synchronous and asynchronous ways on how to stream a video from a given URL.
Note: Both versions below would allow multiple clients to connect to the server and get the video stream without being blocked, as a normal `def` endpoint in FastAPI is [run in an external threadpool that is then awaited, instead of being called directly (as it would block the server)](https://fastapi.tiangolo.com/async/#path-operation-functions)โthus ensuring that FastAPI will still work asynchronously. Even if you defined the endpoint of the first example below with `async def` instead, it would still not block the server, as `StreamingResponse` will run the code (for sending the body chunks) in an external threadpool that is then awaited (have a look at [this comment](https://stackoverflow.com/questions/71895250/fastapi-stream-multiple-videos/71896352#comment127047866_71896352) and the source code [here](https://github.com/encode/starlette/blob/31164e346b9bd1ce17d968e1301c3bb2c23bb418/starlette/responses.py#L238)), if the function for streaming the response body (i.e., `iterfile()` in the examples below) is a normal generator/iterator (as in the first example) and not an `async` one (as in the second example). However, if you had some other I/O or CPU blocking operations inside that endpoint, it would result in blocking the server, and hence, you should drop the `async` definition on that endpooint. The second example demonstrates how to implement the video streaming in an `async def` endpoint, which is useful when you have to call other `async` functions inside the endpoint that you have to `await`, as well as you thus save FastAPI from running the endpoint in an external threadpool. For more details on `def` vs `async def`, please have a look at [this answer](https://stackoverflow.com/a/71517830/17865804).
The below examples use `iter_bytes()` and `aiter_bytes()` methods, respectively, to get the response body in chunks. These functions, as described in the documentation links above and in the source code [here](https://github.com/encode/httpx/blob/f13ab4d288d0b790f6f1c515a6c0ea45e9615748/httpx/_models.py#L802), can handle gzip, deflate, and brotli encoded responses. One can alternatively use the [`iter_raw()`](https://github.com/encode/httpx/blob/f13ab4d288d0b790f6f1c515a6c0ea45e9615748/httpx/_models.py#L857) method to get the raw response bytes, without applying content decoding (if is not needed). This method, in contrast to `iter_bytes()`, allows you to optionally define the `chunk_size` for streaming the response content, e.g., `iter_raw(1024 * 1024)`. However, this doesn't mean that you read the body in chunks of that size from the server (that is serving the file) directly. If you had a closer look at the source code of [`iter_raw()`](https://github.com/encode/httpx/blob/f13ab4d288d0b790f6f1c515a6c0ea45e9615748/httpx/_models.py#L857), you would see that it just uses a [`ByteChunker`](https://github.com/encode/httpx/blob/f13ab4d288d0b790f6f1c515a6c0ea45e9615748/httpx/_decoders.py#L164) that stores the byte contents into memory (using `BytesIO()` stream) and returns the content in fixed-size chunks, depending the chunk size you passed to the function (whereas `raw_stream_bytes`, as shown in the linked source code above, contains the actual byte chunk read from the stream).
### Using `HTTPX` with `def` endpoint
```py
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import httpx
app = FastAPI()
@app.get('/video')
def get_video(url: str):
def iterfile():
with httpx.stream("GET", url) as r:
for chunk in r.iter_bytes():
yield chunk
return StreamingResponse(iterfile(), media_type="video/mp4")
```
### Using `HTTPX` with `async def` endpoint
```py
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import httpx
app = FastAPI()
@app.get('/video')
async def get_video(url: str):
async def iterfile():
async with httpx.AsyncClient() as client:
async with client.stream("GET", url) as r:
async for chunk in r.aiter_bytes():
yield chunk
return StreamingResponse(iterfile(), media_type="video/mp4")
```
You can use public videos provided [here](https://gist.github.com/jsturgis/3b19447b304616f18657) to test the above. Example:
```
http://127.0.0.1:8000/video?url=http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4
```
If you would like to return a custom `Response` or `FileResponse` insteadโwhich I wouldn't really recommend in case you are dealing with large video files, as you should either read the entire contents into memory, or save the contents to a temporary file on disk that you later have to read again into memory, in order to send it back to the clientโplease have a look at [this answer](https://stackoverflow.com/a/71728386/17865804) and [this answer](https://stackoverflow.com/a/73240097/17865804).
|
I encountered similar issues but solved all. The main idea is to create a session with requests.Session(), and yield a chunk one by one, instead of getting all the content and yield it at once. This works very nicely without making any memory issue at all.
```py
@app.get(params.api_video_route)
async def get_api_video(url=None):
def iter():
session = requests.Session()
r = session.get(url, stream=True)
r.raise_for_status()
for chunk in r.iter_content(1024*1024):
yield chunk
return StreamingResponse(iter(), media_type="video/mp4")
```
|
34,377,277 |
Recently I came across code where DAO has an instance of DAOFactory. And DAOFactory has Connection. DAO uses Connection of DAOFactory for its operations. Basically DAO was dependent on DAOFactory. This is the code:
**DAOFactory.java:**
```
public abstract class DAOFactory {
public static final int SQL_SERVER = 1;
public static final int MY_SQL = 2;
private Connection connection = null;
public static DAOFactory getDAOFactory(int daoFactoryType) {
DAOFactory daoFactory = null;
switch (daoFactoryType) {
case SQL_SERVER:
daoFactory = new SQLServerDAOFactory();
break;
case MY_SQL:
daoFactory = new MySQLDAOFactory();
break;
}
return daoFactory;
}
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public abstract UserDAO getUserDAO();
...
}
```
**BaseDAO.java:**
```
public abstract class BaseDAO {
protected DAOFactory daoFactory;
public BaseDAO(DAOFactory daoFactory) {
this.daoFactory = daoFactory;
}
}
```
**UserDAO.java:**
```
public interface UserDAO {
public User getUserById(int userId) throws DAOException;
...
}
```
**SQLServerUserDAO.java:**
```
public class SQLServerUserDAO extends BaseDAO implements UserDAO {
public SQLServerUserDAO (DAOFactory daoFactory) {
super(daoFactory);
}
@Override
public User getUserById(int userId) throws DAOException {
// it uses the connection this way: this.daoFactory.getConnection();
// implementation
}
}
```
**SQLServerDAOFactory.java:**
```
public final class SQLServerDAOFactory extends DAOFactory {
@Override
public UserDAO getUserDAO() {
UserDAO userDAO = null;
userDAO = new SQLServerUserDAO(this);
return userDAO;
}
}
```
I usually see DAO have Connection but this one have DAOFactory instead.
What are the pros and cons of using this approach of DAO having DAOFactory compared to DAO having Connection?
|
2015/12/20
|
[
"https://Stackoverflow.com/questions/34377277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4339178/"
] |
The DAO having a DAOFactory means that changing the connection in the factory will change the connection in every dao created from it. This allows the DAOs to be created before the connection instance is known.
It has the disadvantages of creating circular dependencies between DAOFactory and the DAOs, and causing the DAOs to have more dependencies than they need, which can increase the complexity of the code.
|
Pros :
1. Creates objects according to the required database connection.
2. Then according to the created database creates the User.
3. Follows standard Abstract Factory Design Pattern.
Cons:
1. There is no need to have seperate UserDAOs for separate connections. Could have been done with one class.
|
20,081,380 |
On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir\_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive\_update) and clientId are specified in the SignInButton which triggers "btnSignin\_SessionChanged".
```
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
```
|
2013/11/19
|
[
"https://Stackoverflow.com/questions/20081380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3010425/"
] |
I am not sure about minitest. But in rspec, you will have to stub the initialization part as well and return a mocked scheduler object
This is how i would do it in rspec.
```
mock_scheduler = double("scheduler")
Scheduler.stub(:new).and_return(mock_scheduler)
mock_scheduler.stub(:submit_request).and_return(response)
```
Other option would be
```
Scheduler.any_instance.stub(:submit_request).and_return(response)
```
|
As Vimsha noted you have to first stub out the class initialization. I couldn't get his code to work, but this revised test code below has the same idea:
```
def test_schedule_request
scheduler_response = 'Expected response string for RequestId X'
response = nil
scheduler = Scheduler.new
Scheduler.stub :new, scheduler do
scheduler.stub :submit_request, scheduler_response do
# This test method calls the RequestController schedule route above
response = send_schedule_request(TEST_DATA)
end
end
# Validate (assert) response
end
```
Thanks,
Dave
|
30,030,601 |
I need to create constant json string or a json sorted on keys. What do I mean by constant json string? Please look into following code sample, which I created.
**My Code 1:**
```
public class GsonTest
{
class DataObject {
private int data1 = 100;
private String data2 = "hello";
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 1:**
```
{"data1":100,"data2":"hello"}
```
**My Code 2:**
```
public class GsonTest
{
class DataObject {
private String data2 = "hello";
private int data1 = 100;
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 2:**
```
{"data2":"hello","data1":100}
```
If you see, if I switch variables (`data1` & `data2` in `DataObject` class), I get different json. My objective to get same json, even if somebody changes position of the class variables. I get it when somebody adds new variables, json would change. But json shouldn't change when variables are moved around. So, my objective is to get standard json, possibly in sorted keys order for same class. If there is nested json, then it should be sorted in the nested structure.
**Expected output on run of both the codes**:
```
{"data1":100,"data2":"hello"} //sorted on keys!! Here keys are data1 & data2
```
I understand, I need to change something in `String json = gson.toJson(obj2);` line, but what do I have to do?
**Why I need them to be order?**
I need to encode the json string and then pass it to another function. If I change the order of keys, even though value remain intact, the encoded value will change. I want to avoid that.
|
2015/05/04
|
[
"https://Stackoverflow.com/questions/30030601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3906965/"
] |
First of all, the keys of a json object are **unordered** by definition, see <http://json.org/>.
If you merely want a json string with ordered keys, you can try deserializing your json into a sorted map, and then serialize the map in order to get the sorted-by-key json string.
```
GsonTest obj=new GsonTest();
DataObject obj2 = new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
TreeMap<String, Object> map = gson.fromJson(json, TreeMap.class);
String sortedJson = gson.toJson(map);
```
|
Perhaps a work around is for your class wrap a TreeMap which maintains sort order of the keys. You can add getters and setters for convenience. When you gson the TreeMap, you'll get ordered keys.
|
30,030,601 |
I need to create constant json string or a json sorted on keys. What do I mean by constant json string? Please look into following code sample, which I created.
**My Code 1:**
```
public class GsonTest
{
class DataObject {
private int data1 = 100;
private String data2 = "hello";
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 1:**
```
{"data1":100,"data2":"hello"}
```
**My Code 2:**
```
public class GsonTest
{
class DataObject {
private String data2 = "hello";
private int data1 = 100;
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 2:**
```
{"data2":"hello","data1":100}
```
If you see, if I switch variables (`data1` & `data2` in `DataObject` class), I get different json. My objective to get same json, even if somebody changes position of the class variables. I get it when somebody adds new variables, json would change. But json shouldn't change when variables are moved around. So, my objective is to get standard json, possibly in sorted keys order for same class. If there is nested json, then it should be sorted in the nested structure.
**Expected output on run of both the codes**:
```
{"data1":100,"data2":"hello"} //sorted on keys!! Here keys are data1 & data2
```
I understand, I need to change something in `String json = gson.toJson(obj2);` line, but what do I have to do?
**Why I need them to be order?**
I need to encode the json string and then pass it to another function. If I change the order of keys, even though value remain intact, the encoded value will change. I want to avoid that.
|
2015/05/04
|
[
"https://Stackoverflow.com/questions/30030601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3906965/"
] |
First of all, the keys of a json object are **unordered** by definition, see <http://json.org/>.
If you merely want a json string with ordered keys, you can try deserializing your json into a sorted map, and then serialize the map in order to get the sorted-by-key json string.
```
GsonTest obj=new GsonTest();
DataObject obj2 = new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
TreeMap<String, Object> map = gson.fromJson(json, TreeMap.class);
String sortedJson = gson.toJson(map);
```
|
Like others have mentioned that by design JSON is not supposed to have sorted keys in itself. You can also come up with a recursive solution to do it. I won't say my solution is very efficient but it does the intended job. Please have a look at the following piece of code.
```
private static JsonObject sortAndGet(JsonObject jsonObject) {
List<String> keySet = jsonObject.keySet().stream().sorted().collect(Collectors.toList());
JsonObject temp = new JsonObject();
for (String key : keySet) {
JsonElement ele = jsonObject.get(key);
if (ele.isJsonObject()) {
ele = sortAndGet(ele.getAsJsonObject());
temp.add(key, ele);
} else if (ele.isJsonArray()) {
temp.add(key, ele.getAsJsonArray());
} else
temp.add(key, ele.getAsJsonPrimitive());
}
return temp;
}
```
Input:
```
{"c":"dhoni","a":"mahendra","b":"singh","d":{"c":"tendulkar","b":"ramesh","a":"sachin"}}
```
Output:
```
{"a":"mahendra","b":"singh","c":"dhoni","d":{"a":"sachin","b":"ramesh","c":"tendulkar"}}
```
|
30,030,601 |
I need to create constant json string or a json sorted on keys. What do I mean by constant json string? Please look into following code sample, which I created.
**My Code 1:**
```
public class GsonTest
{
class DataObject {
private int data1 = 100;
private String data2 = "hello";
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 1:**
```
{"data1":100,"data2":"hello"}
```
**My Code 2:**
```
public class GsonTest
{
class DataObject {
private String data2 = "hello";
private int data1 = 100;
}
public static void main(String[] args)
{
GsonTest obj=new GsonTest();
DataObject obj2 = obj.new DataObject();
Gson gson = new Gson();
String json = gson.toJson(obj2);
System.out.println(json);
}
}
```
**Output 2:**
```
{"data2":"hello","data1":100}
```
If you see, if I switch variables (`data1` & `data2` in `DataObject` class), I get different json. My objective to get same json, even if somebody changes position of the class variables. I get it when somebody adds new variables, json would change. But json shouldn't change when variables are moved around. So, my objective is to get standard json, possibly in sorted keys order for same class. If there is nested json, then it should be sorted in the nested structure.
**Expected output on run of both the codes**:
```
{"data1":100,"data2":"hello"} //sorted on keys!! Here keys are data1 & data2
```
I understand, I need to change something in `String json = gson.toJson(obj2);` line, but what do I have to do?
**Why I need them to be order?**
I need to encode the json string and then pass it to another function. If I change the order of keys, even though value remain intact, the encoded value will change. I want to avoid that.
|
2015/05/04
|
[
"https://Stackoverflow.com/questions/30030601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3906965/"
] |
Like others have mentioned that by design JSON is not supposed to have sorted keys in itself. You can also come up with a recursive solution to do it. I won't say my solution is very efficient but it does the intended job. Please have a look at the following piece of code.
```
private static JsonObject sortAndGet(JsonObject jsonObject) {
List<String> keySet = jsonObject.keySet().stream().sorted().collect(Collectors.toList());
JsonObject temp = new JsonObject();
for (String key : keySet) {
JsonElement ele = jsonObject.get(key);
if (ele.isJsonObject()) {
ele = sortAndGet(ele.getAsJsonObject());
temp.add(key, ele);
} else if (ele.isJsonArray()) {
temp.add(key, ele.getAsJsonArray());
} else
temp.add(key, ele.getAsJsonPrimitive());
}
return temp;
}
```
Input:
```
{"c":"dhoni","a":"mahendra","b":"singh","d":{"c":"tendulkar","b":"ramesh","a":"sachin"}}
```
Output:
```
{"a":"mahendra","b":"singh","c":"dhoni","d":{"a":"sachin","b":"ramesh","c":"tendulkar"}}
```
|
Perhaps a work around is for your class wrap a TreeMap which maintains sort order of the keys. You can add getters and setters for convenience. When you gson the TreeMap, you'll get ordered keys.
|
65,003 |
My requirement is to allow a user (other than salesforce admin) to allow to add picklist values by filling a value in text field and submitting form via a visualforce page. I am using javascript remoting for this. Below is my VF code :-
```
<apex:page controller="addfieldtopicklist" showHeader="false">
<apex:form id="frm">
<div id="nm0"></div>
<table>
<tr>
<td><input type="text" id="nm" /></td>
<td>
<input type="button" value="Add To Picklist" onclick="customjsfnc()" />
</td>
</tr>
</table>
</apex:form>
<script>
function customjsfnc(){
var p = document.getElementById('nm').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.addfieldtopicklist.PicklistField}',
p,
function(result, event){
alert(result);
},
{escape: true}
);
}
</script>
</apex:page>
```
And below is the Apex code :-
```
public class addfieldtopicklist {
public String plField{get;set;}
@RemoteAction
public static String PicklistField(String p) {
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();
MetadataService.CustomField customField = (MetadataService.CustomField) service.readMetadata('CustomField',new String[] { 'Scope_Of_Services_Tasks__c.Meeting_Type__c' }).getRecords()[0];
MetadataService.PicklistValue picklistField = new MetadataService.PicklistValue();
picklistField.fullName= p;
picklistField.default_x=false;
customField.picklist.picklistValues.add(picklistField);
return handleSaveResults(
service.updateMetadata(
new MetadataService.Metadata[] { customField })[0]);
}
public static MetadataService.MetadataPort createService(){
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();
return service;
}
private static String handleSaveResults(MetadataService.SaveResult saveResult){
// Nothing to see?
if(saveResult==null || saveResult.success){
return 'success';
}
List<String> messages = new List<String>();
// Construct error message
if(saveResult.errors!=null) {
messages.add('Error occured processing component ' + saveResult.fullName + '.');
}
}
return String.join(messages, ' ');
}
}
```
I am getting this error from api:-
"Error occured on processing component 'Scope\_Of\_Services\_Tasks\_\_c.Meeting\_Type\_\_c' insufficient access rights on cross-reference id insufficient\_access\_on\_cross\_reference\_entity"
I have given this user 'Modify All data' permission already. I think I have to allow more permissions from perimission sets but not sure. I am new to Salesforce please help me. Thanks in Advance.
Update:-
I figured that 'Scope\_Of\_Services\_Tasks\_\_c' is child object to some other object in master detail relationship. So that is why the above error is coming . But I still can't figure out what else I need to give this user in permissions since I have already given 'Modify all data' permission in profile. Please help me know. Thanks
|
2015/02/02
|
[
"https://salesforce.stackexchange.com/questions/65003",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/10167/"
] |
Updating metadata using the Apex wrapper to the Metadata API (which is what it appears you are using) requires the running user have `Customize Application` privileges
|
If this is a custom object, you should use the Delegated Administration functionality. [Delegated Administration](https://help.salesforce.com/HTViewHelpDochttps://help.salesforce.com/HTViewHelpDoc?id=admin_delegate.htm&language=en_US)
|
2,133 |
Obviously, the computing power necessary to create the blockchain requires access to fast hashing which requires electricity. Given that local power outages do occur, and this can cause a lack of network availability, does this act as the Achilles heel for Bitcoin?
Is it possible to conduct Bitcoin transactions in the absence of electricity?
|
2011/12/02
|
[
"https://bitcoin.stackexchange.com/questions/2133",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/117/"
] |
The network is distributed, so it won't go down everywhere at once.
Locally, on one hand it is similar to debit transactions - they need to get online to be processed. One can use cellphones though, which have their own batteries to run for awhile, so it's not too bad.
Lastly, one can accept transactions offline (using QR codes for example) and later transmit them through the network, but that carries the risk of double spending.
And if you want truly offline transactions with little risk, use things like [Casascius physical Bitcoins](https://en.bitcoin.it/wiki/Casascius_physical_bitcoins).
|
In theory Bitcoin could work without electricity or computers. The difficulty would be (manually) reduced so that calculating the hashes by hand (or mechanical means) was feasible. Transactions would have to propagate on paper by hand. Transaction fees would have to go up enormously. And the whole shebang would work at a medieval snail's pace. I imagine it would be like scribe monks copying and verifying bibles...
|
38,608,095 |
I'm making an order form and I want the user to be able to resume their order at a later time, so I create an order in an `IncompleteOrders` collection and save the `docId` of the incomplete order in the user's LocalStorage.
When the user returns to the page I want to read the `docId` stored in their LocalStorage, subscribe to the `IncompleteOrders` collection, and query for their incomplete order.
```
Template.order.onCreated(function(){
if (amplify.store('orders') && amplify.store('orders').docId){
//old order ID found in user's Local Storage
let docId = amplify.store('orders').docId;
let instance = this;
instance.autorun(function(){
let subscription = this.subscribe('incompleteOrders');
if(subscription.ready()){
console.log('IncompleteOrders subscription complete!');
Session.set('orderContents', IncompleteOrders.findOne(docId));
};
});
} else {
//no old order found, no need to subscribe to IncompleteOrders collection
Session.set('orderContents', {});
};
};
```
The problem is that the `orderContents` session variable gets changed in other parts of the code, and since it's a reactive data source, it always re-runs the `autorun` function, subscribes again, and re-runs the `Session.set` portion inside of my `onCreated` callback.
Is there a more intelligent way of going about this?
|
2016/07/27
|
[
"https://Stackoverflow.com/questions/38608095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2760030/"
] |
You can use c.stop() where c is a callback. Please go through code below it should help
```
instance.autorun(function(c){
let subscription = this.subscribe('incompleteOrders');
if(subscription.ready()){
console.log('IncompleteOrders subscription complete!');
Session.set('orderContents', IncompleteOrders.findOne(docId));
c.stop()
};
});
```
Thanks
|
Just an idea, how about doing it on router, i.e; when the router changes and the form isn't submitted but has some data than insert the available fields into incomplete collection?
|
229,021 |
This is a scaled down code of what I'm working with:
```
assoc1 = <|"T1" -> 1, "T2" -> 2, "T3" -> 3, "Z1" -> 4|>
lis1 = {{{"T1","T2","T1"}, {"Z1","T3","T2"}, {"T1","T1","Z1"}, {"T2","T3","T3"}}}
lis2 = lis1 /. assoc1
```
What I'm trying to do is to filter through `lis1` and make a few different lists which fit the criteria in which numbers in designated spots within sublists of `lis2` have the same value . For example let's say I wanted to create another list which is made up of pulled sublists from `lis1` in which the numbers in position 1 and position 3 of any sublist given by `lis2` had the same value, this would give us a new list of:
```
newlis1 = {{{"T1","T2","T1"}}}
```
Likewise, let's say I wanted to only pull out sublists in which the first two or last two numbers within a sublist were equal, this would give two new lists respectively:
`newlis2= {{{"T1","T1","Z1"}}}` and `newlis3 = {{{"T2","T3","T3"}}}`
Is there a generic way to do this? I was thinking maybe using `DeleteCases` but I hadn't gotten anything along those lines to work.
|
2020/08/25
|
[
"https://mathematica.stackexchange.com/questions/229021",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/74202/"
] |
First and third:
```
Cases[lis1, {x_, _, x_}, {2}]
```
>
> `{{"T1", "T2", "T1"}}`
>
>
>
First two and last two:
```
Cases[lis1, {x_, x_, _}, {2}]
```
>
> `{{"T1", "T1", "Z1"}}`
>
>
>
```
Cases[lis1, {_, x_, x_}, {2}]
```
>
> `{{"T2", "T3", "T3"}}`
>
>
>
I used `Cases` out of habit, but your idea with `DeleteCases` has the advantage that it doesn't change the structure (the level of nesting).
```
DeleteCases[lis1, Except[{_, x_, x_}], {2}]
```
>
> `{{{"T2", "T3", "T3"}}}`
>
>
>
|
Your example list *lis1* has 3 levels, but only one element at the first level. If this is always the case, you could use
```
Select[lis1 // First,
assoc1[#[[1]]] == assoc1[#[[2]]] ||
assoc1[#[[2]]] == assoc1[#[[3]]] &]
```
However, if *lis1* could have more than 1 "row", you could use something like
```
Select[#,
assoc1[#[[1]]] == assoc1[#[[2]]] ||
assoc1[#[[2]]] == assoc1[#[[3]]] &] & /@ lis1
```
|
229,021 |
This is a scaled down code of what I'm working with:
```
assoc1 = <|"T1" -> 1, "T2" -> 2, "T3" -> 3, "Z1" -> 4|>
lis1 = {{{"T1","T2","T1"}, {"Z1","T3","T2"}, {"T1","T1","Z1"}, {"T2","T3","T3"}}}
lis2 = lis1 /. assoc1
```
What I'm trying to do is to filter through `lis1` and make a few different lists which fit the criteria in which numbers in designated spots within sublists of `lis2` have the same value . For example let's say I wanted to create another list which is made up of pulled sublists from `lis1` in which the numbers in position 1 and position 3 of any sublist given by `lis2` had the same value, this would give us a new list of:
```
newlis1 = {{{"T1","T2","T1"}}}
```
Likewise, let's say I wanted to only pull out sublists in which the first two or last two numbers within a sublist were equal, this would give two new lists respectively:
`newlis2= {{{"T1","T1","Z1"}}}` and `newlis3 = {{{"T2","T3","T3"}}}`
Is there a generic way to do this? I was thinking maybe using `DeleteCases` but I hadn't gotten anything along those lines to work.
|
2020/08/25
|
[
"https://mathematica.stackexchange.com/questions/229021",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/74202/"
] |
First and third:
```
Cases[lis1, {x_, _, x_}, {2}]
```
>
> `{{"T1", "T2", "T1"}}`
>
>
>
First two and last two:
```
Cases[lis1, {x_, x_, _}, {2}]
```
>
> `{{"T1", "T1", "Z1"}}`
>
>
>
```
Cases[lis1, {_, x_, x_}, {2}]
```
>
> `{{"T2", "T3", "T3"}}`
>
>
>
I used `Cases` out of habit, but your idea with `DeleteCases` has the advantage that it doesn't change the structure (the level of nesting).
```
DeleteCases[lis1, Except[{_, x_, x_}], {2}]
```
>
> `{{{"T2", "T3", "T3"}}}`
>
>
>
|
```
newlis1 = List /@ Cases[lis1, {a_, _, b_} /;assoc1[a] == assoc1[b], All]
```
>
>
> ```
> {{{"T1", "T2", "T1"}}}
>
> ```
>
>
```
{newlis2, newlis3} = List /@ Cases[lis1, {a_, b_, _} | {_, a_, b_} /;
assoc1[a] == assoc1[b], All]
```
>
>
> ```
> {{{"T1", "T1", "Z1"}}, {{"T2", "T3", "T3"}}}
>
> ```
>
>
```
pIck = Pick[#, Apply[Equal, (# /. #2)[[All, #3]], {-2}]] &;
pIck[First@lis1, assoc1, {1, 3}]
```
>
>
> ```
> {{"T1", "T2", "T1"}}
>
> ```
>
>
```
pIck[First@lis1, assoc1, ;; 2]
```
>
>
> ```
> {{"T1", "T1", "Z1"}}
>
> ```
>
>
```
pIck[First@lis1, assoc1, 2 ;;]
```
>
>
> ```
> {{"T2", "T3", "T3"}}
>
> ```
>
>
|
30,866,718 |
Edit: Oops my bad! I wasn't clear enough... I guess I need to explain more...
I need to create a package installer for my customers. I want them to extract and overwrite the contents only in their specific folder.
I don't want them to be able to extract the contents wherever they want to let them steal my work /or know what my files are all about.
So I was thinking maybe the installer could be created in a way to check for a file name inside the folder and after the file name has been recognized then it can be simply extracted and overwritten and if not then the operation will be cancelled.
Any Idea ?
|
2015/06/16
|
[
"https://Stackoverflow.com/questions/30866718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4442072/"
] |
Just increment before, not on every substitution:
```
awk '{i++; gsub(/a/,i)}1' file
```
This way, the variable gets updated once per line, not once per record.
The same applies to the Perl script:
```
perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' file
```
### Test
```
$ cat a
0 0 a a a
2 3 a a a
$ awk '{i++; gsub(/a/,i)}1' a
0 0 1 1 1
2 3 2 2 2
$ perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' a
0 0 1 1 1
2 3 2 2 2
```
|
```
perl -pe'$i++;s/a/$i/g'
```
or if you like to increment only for lines with any substitution
```
perl -pe'/a/&&$i++;s/a/$i/g'
```
In action:
```
$ cat a
0 0 a a a
1 2 0 0 0
2 3 a a a
$ perl -pe'$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 3 3 3
$ perl -pe'/a/&&$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 2 2 2
```
|
30,866,718 |
Edit: Oops my bad! I wasn't clear enough... I guess I need to explain more...
I need to create a package installer for my customers. I want them to extract and overwrite the contents only in their specific folder.
I don't want them to be able to extract the contents wherever they want to let them steal my work /or know what my files are all about.
So I was thinking maybe the installer could be created in a way to check for a file name inside the folder and after the file name has been recognized then it can be simply extracted and overwritten and if not then the operation will be cancelled.
Any Idea ?
|
2015/06/16
|
[
"https://Stackoverflow.com/questions/30866718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4442072/"
] |
Just increment before, not on every substitution:
```
awk '{i++; gsub(/a/,i)}1' file
```
This way, the variable gets updated once per line, not once per record.
The same applies to the Perl script:
```
perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' file
```
### Test
```
$ cat a
0 0 a a a
2 3 a a a
$ awk '{i++; gsub(/a/,i)}1' a
0 0 1 1 1
2 3 2 2 2
$ perl -pe 'BEGIN { our $i = 0; } $i++; s/a/$i/ge;' a
0 0 1 1 1
2 3 2 2 2
```
|
You can simply replace every occurrence of `a` with the current line number
```
perl -pe 's/a/$./g' FILE > NEW_FILE
```
|
30,866,718 |
Edit: Oops my bad! I wasn't clear enough... I guess I need to explain more...
I need to create a package installer for my customers. I want them to extract and overwrite the contents only in their specific folder.
I don't want them to be able to extract the contents wherever they want to let them steal my work /or know what my files are all about.
So I was thinking maybe the installer could be created in a way to check for a file name inside the folder and after the file name has been recognized then it can be simply extracted and overwritten and if not then the operation will be cancelled.
Any Idea ?
|
2015/06/16
|
[
"https://Stackoverflow.com/questions/30866718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4442072/"
] |
You can simply replace every occurrence of `a` with the current line number
```
perl -pe 's/a/$./g' FILE > NEW_FILE
```
|
```
perl -pe'$i++;s/a/$i/g'
```
or if you like to increment only for lines with any substitution
```
perl -pe'/a/&&$i++;s/a/$i/g'
```
In action:
```
$ cat a
0 0 a a a
1 2 0 0 0
2 3 a a a
$ perl -pe'$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 3 3 3
$ perl -pe'/a/&&$i++;s/a/$i/g' a
0 0 1 1 1
1 2 0 0 0
2 3 2 2 2
```
|
17,924,267 |
I'd like to compare Windows Azure SQL Database and SQL Server on VM. So I'd like to ask:
which SQL server edition on Windows Azure(S,M edition; Web or Standard) should I choose to compare it with Windows Azure SQL Database Web. I know that these are different concepts PaaS IaaS and so on. In my question I am referring to your experience with these two technologies and their performance. I know that it would be roughly comparison
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17924267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2225591/"
] |
Roughly, [Windows Azure SQL Database](http://www.windowsazure.com/en-us/services/data-management/) is comparable to the features of [SQL Server 2012 Standard Edition](http://msdn.microsoft.com/en-us/library/cc645993.aspx), but this comparison is only approximate, because each offer is meant for a different use case and offers a different balance of features.
In [Understanding Azure SQL Database and SQL Server in Azure VMs](https://azure.microsoft.com/en-us/documentation/articles/data-management-azure-sql-database-and-sql-server-iaas/) you'll find a detailed comparison. Some distinctive characteristics are:
* SQL Database is highly available; each database is backed by 3 servers; each operation will only be completed when it is accepted by at least 2 servers. This leads to a higher latency than SQL Server on a single server.
* SQL Database runs on cloud infrastructure. Client applications must be fault-tolerant.
* SQL Database runs on shared resources, so clients may experience performance fluctuations. The [Premium Offer for Windows Azure SQL Database](http://blogs.technet.com/b/dataplatforminsider/archive/2013/07/09/a-closer-look-at-the-premium-offer-for-windows-azure-sql-database.aspx) delivers more powerful and predictable performance.
* SQL Database has a few [limitations](http://msdn.microsoft.com/en-us/library/ff394102.aspx) on support for [features](http://msdn.microsoft.com/en-us/library/ff394115.aspx), [Transact-SQL](http://msdn.microsoft.com/en-us/library/ee336250.aspx), [Data Types](http://msdn.microsoft.com/en-us/library/ee336233.aspx) and [Tools and Utilities](http://msdn.microsoft.com/en-us/library/ee621784.aspx).
See also how to [Compare SQL Server with Windows Azure SQL Database](http://social.technet.microsoft.com/wiki/contents/articles/996.compare-sql-server-with-windows-azure-sql-database.aspx) and the guidance on [SQL Server in Windows Azure Virtual Machines](http://msdn.microsoft.com/en-us/library/windowsazure/jj823132.aspx).
|
Regarding Windows Azure SQL Database Web edition: Web and Business editions are identical except for storage capacity (see my detailed SO answer about this, [here](https://stackoverflow.com/a/3521506/272109)), so it doesn't matter for your comparison.
Regarding SQL Server editions, I think this is going to be primarily a [difference in features](http://msdn.microsoft.com/en-us/library/cc645993.aspx) and licensing, not performance. That said: If you choose the Enterprise edition, you may find more features are active, therefore consuming more resources. Fortunately the Web, Standard, and Enterprise editions are all in the Virtual Machine gallery, so you can deploy any of them without having to do a custom install.
When comparing Windows Azure SQL Database with SQL Server, you should probably start with [this MSDN article](http://msdn.microsoft.com/en-us/library/windowsazure/ee336279.aspx) which goes into detail about the limitations of SQL Database as well as T-SQL differences.
|
17,924,267 |
I'd like to compare Windows Azure SQL Database and SQL Server on VM. So I'd like to ask:
which SQL server edition on Windows Azure(S,M edition; Web or Standard) should I choose to compare it with Windows Azure SQL Database Web. I know that these are different concepts PaaS IaaS and so on. In my question I am referring to your experience with these two technologies and their performance. I know that it would be roughly comparison
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17924267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2225591/"
] |
I made comparison for Azure SQL and SQL Server Std hosted on Azure VM (Large (A3)) for 2GB database. I just copied DB from Azure to VM, so, basically, I had 2 Databases with identical data and was able to run same queries.
SQL Azure DB has known advantages, but when it goes to performance people starts crying:
* Getting last 1000 transactions from ~100k transactions with many joins takes:
>
> Azure SQL: 7:40 mins
>
>
> SQLServer on VM: 2:30 mins
>
>
>
* Getting 10 transactions with specific parameter's:
>
> Azure SQL: 3:57 mins
>
>
> SQLServer on VM: 1:05 mins
>
>
>
In this test I didn't care about query performance, I just want to see the difference for the same data/queries between Azure SQL and SQL Server on Azure VM. As you see, it's very differ.
|
Regarding Windows Azure SQL Database Web edition: Web and Business editions are identical except for storage capacity (see my detailed SO answer about this, [here](https://stackoverflow.com/a/3521506/272109)), so it doesn't matter for your comparison.
Regarding SQL Server editions, I think this is going to be primarily a [difference in features](http://msdn.microsoft.com/en-us/library/cc645993.aspx) and licensing, not performance. That said: If you choose the Enterprise edition, you may find more features are active, therefore consuming more resources. Fortunately the Web, Standard, and Enterprise editions are all in the Virtual Machine gallery, so you can deploy any of them without having to do a custom install.
When comparing Windows Azure SQL Database with SQL Server, you should probably start with [this MSDN article](http://msdn.microsoft.com/en-us/library/windowsazure/ee336279.aspx) which goes into detail about the limitations of SQL Database as well as T-SQL differences.
|
9,731,866 |
i have a password box and i want to get the input data to check for verification.
My passwordbox c# code
```
public void textBox2_TextInput(object sender, TextCompositionEventArgs e)
{
//pass = textBox2.ToString();
}
```
and the xaml code
```
<PasswordBox Name="textBox2"
PasswordChar="*"
TextInput="textBox2_TextInput" />
```
this is what i have written to capture the password
```
private void loginbutton_Click(object sender, RoutedEventArgs e)
{
usr = textBox1.Text;
SecureString passdat =textBox2.SecurePassword;
pass = passdat.ToString();
}
```
it returns null.This is a dummy demo so no encryption is required.I was using a text box earlier and the verification worked.using a password box just complicated things.
|
2012/03/16
|
[
"https://Stackoverflow.com/questions/9731866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1151462/"
] |
Putting some work on a background thread is easy: fire off your block with `dispatch_async()`, `-[NSOperationQueue addOperationWithBlock:]`, or possibly even something related to the server connection you're using, like `+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]`. (Look up any of those in the docs for usage examples.)
If you're looking to do Core Data stuff on your background thread, it gets nasty unless you're on iOS 5.0 or newer. Apple has a big writeup on [Concurrency and Core Data](http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/Articles/cdConcurrency.html#//apple_ref/doc/uid/TP40003385-SW1) for the pre-5.0 case, but the new stuff, while a whole lot easier for simple uses like you're proposing, isn't as well documented. [This question](https://stackoverflow.com/questions/8305227) should give you a good start, though.
|
The block that you're passing is an object that the server will execute at some point. If you want the block to be executed on a different thread, you'll need to change SomeServer's implementation of `-doServerCallCallback:`.
See the [*Grand Central Dispatch Reference*](https://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html) manual for complete information about using blocks. In short, the server should create a dispatch queue when it starts up. You can then use a function like `dispatch_async()` to execute the block.
|
29,989,854 |
I am iterating a JavaScript array object. I have written a function which iterates the array element. it works but above the result there is written 'undefined'. I don't want to see this, it would be great help to know how to solve this undefine word thing.
```js
var userlist = [{
"username": "Tom",
"Current_latitude": 23.752805,
"Current_longitude": 90.375433,
"radius": 500
},
{
"username": "Jane",
"Current_latitude": 23.752805,
"Current_longitude": 90.375433,
"radius": 400
},
{
"username": "Dave",
"Current_latitude": 23.765138,
"Current_longitude": 90.362601,
"radius": 450
}, {
"username": "Sarah",
"Current_latitude": 23.792452,
"Current_longitude": 90.416696,
"radius": 600
},
{
"username": "John",
"Current_latitude": 23.863064,
"Current_longitude": 90.400126,
"radius": 640
}
];
var x = Tom(userlist);
function Tom(user) {
var text;
for (var i = 0; i < user.length; i++) {
text += "<li>" + user[i].username + "</li>";
};
//text+="</ul>"
document.getElementById("demo").innerHTML = text;
}
//document.getElementById("demo").innerHTML=userlist[0].username+" "+userlist[0].Current_latitude + " " + userlist[0].Current_latitude+"" + userlist[0].Current_longitude+" "+ userlist[0].radius;
```
```html
<p>How to create A javaScript Object Array.</p>
<p id="demo"></p>
```
|
2015/05/01
|
[
"https://Stackoverflow.com/questions/29989854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1080145/"
] |
You need to initialize your valiable `text` to an empty string, like this:
```
var text = "";
```
Uninitialized variables in JavaScript default to the special value [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), which is found as text in the concatenation.
As noted in the comments, there's an in issue in your HTML too: `<li>` tags should only appear inside a containing `<ul>`, `<ol>` or `<menu>` tag.
You may consider changing your `<li>`...`</li>` to something like `<div>`...`</div>` or wrapping the text concatendated text with `<ul>`...`</ul>`.
|
It's because you haven't initialised your variable:
```
var text; //text is undefined at this point
for (var i = 0; i < user.length; i++)
{
//the first iteration of the loop will append to "undefined"
text+="<li>"+ user[i].username+"</li>";
};
```
Simply give it an initial value:
```
var text = '';
for (var i = 0; i < user.length; i++)
{
text+="<li>"+ user[i].username+"</li>";
};
```
As noted by Juhana, however, this isn't generating valid markup. You can uncomment your closing tag, and initialise `text` to `<ul>` instead:
```
var text = '<ul>';
for (var i = 0; i < user.length; i++)
{
text+="<li>"+ user[i].username+"</li>";
};
text += "</ul>";
```
|
47,157,832 |
I have a maxtrix data which shape is 10201\*101,and only contains 0 and 1. the codes below is same peocession by matlab/python,but it get different result,I don't know why...
```
BOUND = load('C:\Users\1\Desktop\ct06\result_data116.dat');
BOUND = reshape(BOUND,101,101,101);
BOUND(:,:,[1,101]) = 1;
BOUND(:,[1,101],:) = 1;
Boundary = find(BOUND>0); #matlab > Boubdary ๏ผ 808243x1 double
import numpy as np
BOUND = np.loadtxt(r'C:\Users\1\Desktop\ct06\result_data116.dat').reshape([101,101,101])
BOUND[:,:,[0,100]] = 1
BOUND[:,[0,100],:] = 1
Boundary = np.where(BOUND>0)
print(Boundary[0].size) #python > 809074
```
I really don't konw why it have a two different Boundary (808243 and 809074)?
I guess that the assignment operation is the reason result to the difference(I put off the assignment part,then them got same results).But I still don't konw why...
|
2017/11/07
|
[
"https://Stackoverflow.com/questions/47157832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8057143/"
] |
Matlab uses column major ordering, while python uses row major (read <https://en.wikipedia.org/wiki/Row-_and_column-major_order> for more details on what this means). As an example, in python
```
t = np.eye(3)
t[0,1] = 3
np.reshape(t, (9, 1))
```
results in
```
array([[ 1.],
[ 3.],
[ 0.],
[ 0.],
[ 1.],
[ 0.],
[ 0.],
[ 0.],
[ 1.]])
```
While in matlab the same command
```
t = eye(3)
t(1,2) = 3
reshape(t, 9, 1)
```
results in
ans =
```
1
0
0
3
1
0
0
0
1
```
Just because commands have the same name in two different programming languages does not mean they will do the same thing. Just because two commands claim to do the same thing does not mean the results will not be subtly different. Always test your code with a simple input before throwing all of your data files at it.
|
The likely cause is that Matlab uses column-major order, so when you do
```
BOUND[:,[0,100],:] = 1
```
the behavior is different in Matlab and Python.
|
59,202,279 |
Given:
```
const a = () => true
const b = () => false
const t = [a, b]
```
How can I generate an additive AND:
`a() && b()`
In this case, it would return `false`.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59202279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402561/"
] |
You could reduce the array by using `true` as *startValue* and perform a [logical AND `&&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND) by using the result of the function call.
This approach keeps the value of the function calls.
```js
const a = () => true
const b = () => false
const t = [a, b]
console.log(t.reduce((r, f) => r && f(), true));
```
Approach with a stored value for the result and a short circuit.
```
const AND = array => {
var result = true;
array.every(fn => result = result && fn());
return result;
};
```
|
Use [`array.every()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every):
```js
const a = () => true
const b = () => false
const t = [a, b]
console.log(t.every(f => f()));
```
This will only produce a boolean value, so if you were intending to get a different result as if short circuiting you'll have to use a `reduce()` solution or other.
|
59,202,279 |
Given:
```
const a = () => true
const b = () => false
const t = [a, b]
```
How can I generate an additive AND:
`a() && b()`
In this case, it would return `false`.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59202279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402561/"
] |
Use [`array.every()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every):
```js
const a = () => true
const b = () => false
const t = [a, b]
console.log(t.every(f => f()));
```
This will only produce a boolean value, so if you were intending to get a different result as if short circuiting you'll have to use a `reduce()` solution or other.
|
Use `Array.find()` to get the 1st function with a falsy value. If none found, take the last function in the array, and if the array is empty use the fallback function that returns `undefined`. Invoke the function that you got.
```js
const fn = arr => (
arr.find(f => !f()) || arr[arr.length - 1] || (() => undefined)
)()
console.log(fn([() => true, () => false])) // false
console.log(fn([() => 1, () => 2])) // 2
console.log(fn([() => 1, () => 0, () => 2])) // 0
console.log(fn([])) // undefined
```
|
59,202,279 |
Given:
```
const a = () => true
const b = () => false
const t = [a, b]
```
How can I generate an additive AND:
`a() && b()`
In this case, it would return `false`.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59202279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402561/"
] |
You could reduce the array by using `true` as *startValue* and perform a [logical AND `&&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND) by using the result of the function call.
This approach keeps the value of the function calls.
```js
const a = () => true
const b = () => false
const t = [a, b]
console.log(t.reduce((r, f) => r && f(), true));
```
Approach with a stored value for the result and a short circuit.
```
const AND = array => {
var result = true;
array.every(fn => result = result && fn());
return result;
};
```
|
In your case, using `a() && b()` will work perfectly. If you want to use the `t` array, you can do it like this: `t[0]() && t[1]()`. However, if you want multiple inputs, I think it would be good to use an array function (`Array.prototype.reduce`):
```js
t.reduce((previous, item) => previous && item(), true)
```
|
59,202,279 |
Given:
```
const a = () => true
const b = () => false
const t = [a, b]
```
How can I generate an additive AND:
`a() && b()`
In this case, it would return `false`.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59202279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402561/"
] |
You could reduce the array by using `true` as *startValue* and perform a [logical AND `&&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND) by using the result of the function call.
This approach keeps the value of the function calls.
```js
const a = () => true
const b = () => false
const t = [a, b]
console.log(t.reduce((r, f) => r && f(), true));
```
Approach with a stored value for the result and a short circuit.
```
const AND = array => {
var result = true;
array.every(fn => result = result && fn());
return result;
};
```
|
Use `Array.find()` to get the 1st function with a falsy value. If none found, take the last function in the array, and if the array is empty use the fallback function that returns `undefined`. Invoke the function that you got.
```js
const fn = arr => (
arr.find(f => !f()) || arr[arr.length - 1] || (() => undefined)
)()
console.log(fn([() => true, () => false])) // false
console.log(fn([() => 1, () => 2])) // 2
console.log(fn([() => 1, () => 0, () => 2])) // 0
console.log(fn([])) // undefined
```
|
59,202,279 |
Given:
```
const a = () => true
const b = () => false
const t = [a, b]
```
How can I generate an additive AND:
`a() && b()`
In this case, it would return `false`.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59202279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402561/"
] |
In your case, using `a() && b()` will work perfectly. If you want to use the `t` array, you can do it like this: `t[0]() && t[1]()`. However, if you want multiple inputs, I think it would be good to use an array function (`Array.prototype.reduce`):
```js
t.reduce((previous, item) => previous && item(), true)
```
|
Use `Array.find()` to get the 1st function with a falsy value. If none found, take the last function in the array, and if the array is empty use the fallback function that returns `undefined`. Invoke the function that you got.
```js
const fn = arr => (
arr.find(f => !f()) || arr[arr.length - 1] || (() => undefined)
)()
console.log(fn([() => true, () => false])) // false
console.log(fn([() => 1, () => 2])) // 2
console.log(fn([() => 1, () => 0, () => 2])) // 0
console.log(fn([])) // undefined
```
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
I dont think you need regex for this.
```
var parts = myString.Split('|').Select(p => p.Trim());
var result = string.Join(" | ", parts);
```
As @I4V's answer shows you can split on carriage return line feed, then handle each row.
To use my answer in this way try this:
```
var splitLines = input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var result = splitLines.Select(eachLine => string.Join(" | ", eachLine.Split('|').Select(p => p.Trim());
```
|
>
> this happens many times in a multi-line text (Commented on a deleted answer)
>
>
>
```
string input =
@"a | b
a|b
a| b
a |b";
var result =
String.Join(Environment.NewLine,
input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(line => String.Join(" ", Regex.Matches(line, @"\w|\|")
.Cast<Match>()
.Select(m => m.Value))));
```
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
This one will do as well:
```
input = Regex.Replace(input, "\\s*\\|\\s*", " | ");
```
|
I dont think you need regex for this.
```
var parts = myString.Split('|').Select(p => p.Trim());
var result = string.Join(" | ", parts);
```
As @I4V's answer shows you can split on carriage return line feed, then handle each row.
To use my answer in this way try this:
```
var splitLines = input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var result = splitLines.Select(eachLine => string.Join(" | ", eachLine.Split('|').Select(p => p.Trim());
```
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
I dont think you need regex for this.
```
var parts = myString.Split('|').Select(p => p.Trim());
var result = string.Join(" | ", parts);
```
As @I4V's answer shows you can split on carriage return line feed, then handle each row.
To use my answer in this way try this:
```
var splitLines = input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var result = splitLines.Select(eachLine => string.Join(" | ", eachLine.Split('|').Select(p => p.Trim());
```
|
you can try this
```
Regex.Replace(str, "([a-zA-Z]+)(\s*)\|(\s*)([a-zA-Z]+)", "$1 | $4");
```
I may be mistaking about $1,$4 location. It may be "$4 | $5". Though it is not complete answer but may be close.
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
This one will do as well:
```
input = Regex.Replace(input, "\\s*\\|\\s*", " | ");
```
|
>
> this happens many times in a multi-line text (Commented on a deleted answer)
>
>
>
```
string input =
@"a | b
a|b
a| b
a |b";
var result =
String.Join(Environment.NewLine,
input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(line => String.Join(" ", Regex.Matches(line, @"\w|\|")
.Cast<Match>()
.Select(m => m.Value))));
```
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
you can try this
```
Regex.Replace(str, "([a-zA-Z]+)(\s*)\|(\s*)([a-zA-Z]+)", "$1 | $4");
```
I may be mistaking about $1,$4 location. It may be "$4 | $5". Though it is not complete answer but may be close.
|
>
> this happens many times in a multi-line text (Commented on a deleted answer)
>
>
>
```
string input =
@"a | b
a|b
a| b
a |b";
var result =
String.Join(Environment.NewLine,
input.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(line => String.Join(" ", Regex.Matches(line, @"\w|\|")
.Cast<Match>()
.Select(m => m.Value))));
```
|
22,118,546 |
I'm trying to do something like this:
Input:
```
"a | b"
"a|b"
"a| b"
"a |b"
```
Output for all of above Inputs must be:
```
"a | b"
```
I tried lots of things but couldn't achieve what I meant for.
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22118546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079221/"
] |
This one will do as well:
```
input = Regex.Replace(input, "\\s*\\|\\s*", " | ");
```
|
you can try this
```
Regex.Replace(str, "([a-zA-Z]+)(\s*)\|(\s*)([a-zA-Z]+)", "$1 | $4");
```
I may be mistaking about $1,$4 location. It may be "$4 | $5". Though it is not complete answer but may be close.
|
5,328 |
I'm learning Sagang Textbook, and in the book has a homework like that:
"Read the following summary, find the mistakes and correct them (3 things)
>
> ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์. ์์ธ ์๋น์ ์ผ์์ง์ด์์. ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์์ด์. ๊ทธ๋์ ๋ง์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์. ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์. ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์. ํ์ง๋ง ์์ธ ์๋น ์์ ์จ๋ "ํ๋ ๋ ์ํค์ธ์"๋ผ๊ณ ๋งํ์ด์"
>
>
>
I think i know the other mistakes in this paragraph, but i am not sure about the phrase "๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์". I think it is not correct because ๋น๋น๋ฐฅ is object, so it must be ๋น๋น๋ฐฅ์, right? And because ๋ฏธ์์ฝ ์จ๋ is third person, so i think it must be ์ถ์ดํด์, so "๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์" must be "๋น๋ฐฅ์ ๋จน๊ณ ์ถ์ดํด์". Can you explain it for me? Thank you!
|
2019/06/16
|
[
"https://korean.stackexchange.com/questions/5328",
"https://korean.stackexchange.com",
"https://korean.stackexchange.com/users/1194/"
] |
I am afraid to say this, but there are more than three mistakes.
First of all, ์์ธ ์๋น is used too many times, although it is *not* a *grammatical* mistake. Even if ์์ธ ์๋น is a name of a restaurant, the repetitive use of *proper names for places* seems clumsy. You may use ์ด ์๋น, ๊ทธ ์๋น, ๊ทธ๊ณณ, or ๊ฑฐ๊ธฐ in place of ์์ธ ์๋น. Nonetheless, it is advisable to avoid using pronouns (๊ทธ๊ณณ and ๊ฑฐ๊ธฐ) repetitively.
Now, let me examine all the sentences. There are four people involved in the paragraph: one is the writer, and the others are ์งํ, ๋ฏธ์์ฝ, and ์์ธ ์๋น ์์ ์จ. The writer mentions what ์งํ and ๋ฏธ์์ฝ did.
>
> ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์.
>
>
>
Nothing is incorrect here.
>
> A. ์์ธ ์๋น์ ์ผ์์ง์ด์์.
>
>
> B. ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์์ด์.
>
>
> C. ๊ทธ๋์ ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์.
>
>
>
A lot of things should be considered:
* If ์์ธ ์๋น is a proper name, Sentence A is grammatically correct; if ์์ธ ์๋น refers to a/the restaurant in Seoul, it is logically *incorrect*.
* There are no clear reasons that Sentences A and B should be placed here in the paragraph, as they express what the writer thinks *not* what ์งํ thought. If you are not going to remove both Sentence A and Sentence B, it is one option to connect Sentence A to Sentence B; you might say "์์ธ ์๋น์ ์ผ์์ง**์ธ๋ฐ** ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ๊ณณ์ด์์**." *However*, this complex sentence does *not* relate to Sentence C.
* In Sentence C, there is *no* explicit subject. "Who did it?" You could assume that ์งํ introduced the restaurant to ๋ฏธ์์ฝ, but you should note that the previous subject is ์์ธ ์๋น [Note: ๋น๋น๋ฐฅ is kind of a sub-subject here] unless you remove Sentences A and B. "๊ทธ๋์ **์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์." will clearly show the subject, but Sentence C itself has insignificant problems without Sentences A and B because the repetitive indication of the same subject for consecutive sentences is usually avoided in Korean. Nonetheless, using Sentence C leaves a possibility that the writer (*not* ์งํ) told ๋ฏธ์์ฝ about the restaurant.
* You *cannot* simply remove Sentences A and B because the following sentence of Sentence C mentions ๋น๋น๋ฐฅ. If you would like to erase them, you have to use part of Sentence B somewhere before mentioning ๋ฏธ์์ฝ.
So, what would be a possible correction including the first sentence in the paragraph? I will mention only three as follows, but others' corrections could be better:
* ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์. **๊ทธ** ์๋น์ ์ผ์์ง**์ธ๋ฐ** ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ๊ณณ์ด์ฃ **. **๊ทธ๊ณณ ์์์ด ์ ๋ง ๋ง์์๋์ง ์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
**๊ทธ ์๋น**์ ์๊ฐํด ์คฌ์ด์.
* ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ**์ ๋น๋น๋ฐฅ์ ์์ฃผ ๋ง์๊ฒ ๋จน์ ์ ์ด ์์ด์**. ๊ทธ๋์ **์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
**๊ทธ ์๋น**์ ์๊ฐํด ์คฌ์ด์.
* ์งํ ์จ**๊ฐ** ์์ธ ์๋น**์ด ์ด๋ค์ง ์๊ธฐํด ์ค ์ ์ด ์์ด์**. **๊ทธ** ์๋น์ ์ผ์์ง์ธ๋ฐ ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ์ง์ด๋ผ๋๊ตฐ์**. ๊ทธ๋์ **์ ๋** ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์.
Please be aware that those three have totally different meanings. *You should rewrite the summary according to the original text*.
Here, another sentence comes.
>
> ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์.
>
>
>
"How does it relate to the previous sentence?" For cohesion, it will be clever to add when she wanted to eat ๋น๋น๋ฐฅ or other information. The following are two (*but not* the only) options:
* ๋ฏธ์์ฝ ์จ๋ **์๋น ์ถ์ฒ์ ๋ฐ์ ๋ค์** ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์.
* **๊ทธ ํ์** ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ **์๊ฐ๋ฐ์** ์๋น์ ๊ฐ์ด์.
>
> ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
>
>
>
"Who did this?" There is a possibility that the writer ordered ๋น๋น๋ฐฅ, but it is far more likely that she ordered the food.
There are some options to improve the sentence:
* **๊ทธ๋ฌ๊ณ ๋ ๊ทธ๊ณณ์์** ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
* **๋ฏธ์์ฝ ์จ๋ ๊ทธ๊ณณ์์** ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
>
> ํ์ง๋ง ์์ธ ์๋น ์์ ์จ๋ "ํ๋ ๋ ์ํค์ธ์"๋ผ๊ณ ๋งํ์ด์.
>
>
>
Four points I can point out:
* ํ๋ ๋ ์ํค์ธ์ is a sentence quote. It is advisable to place a period at its end, although it is allowed to omit a period there.
* It is difficult for me to judge whether ํ์ง๋ง is correct, but I would use ๊ทธ๋ฐ๋ฐ instead.
* I feel it somewhat rude to call a male person ์์ ์จ although some people use it. I would use ์ฃผ์ธ or ์ฌ์ฅ instead if he is an/the owner; ์ง์, if he is an employee.
* If you would like to keep ์์ ์จ here, it will be better to erase ์์ธ because the reader(s) now knows what the restaurant is.
So, I would put it as
* **๊ทธ๋ฐ๋ฐ** ์๋น **์ฃผ์ธ**์ **(๋ฏธ์์ฝ ์จ์๊ฒ)** "ํ๋ ๋ ์ํค์ธ์."๋ผ๊ณ ๋งํ์ด์.
or
* **๊ทธ๋ฐ๋ฐ** ์๋น **์ง์**์ **(๋ฏธ์์ฝ ์จ์๊ฒ)** "ํ๋ ๋ ์ํค์ธ์."๋ผ๊ณ ๋งํ์ด์.
---
To have more corrections, you may visit [Lang-8](https://lang-8.com/), but you should *not* trust all the users; some of them do *not* care much about grammar.
---
Edit:
I have noticed that the current rules allow the omission of the period at the end of a sentence quote. Accordingly, I have edited the relevant line.
|
A partial answer to the โ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ(์/์ด) ๋จน๊ณ ์ถ์ดโโ question.
==========================================================
>
> ์ด27
> ===
>
>
> ### Sense โ
ฃ
>
>
> * (โโธป๊ณ ์ถ๋คโ ๊ตฌ์ฑ์์ ๋ณธ๋์ฌ์ **๋ชฉ์ ์ด**๋ ๋ฐ์นจ ์๋ ๋ถ์ฌ์ด ๋ค์ ๋ถ์ด) ์๋ง์ ์ง์ ํ์ฌ *๊ฐ์กฐํ๋ ๋ป*์ ๋ํ๋ด๋ ๋ณด์กฐ์ฌ.
> * A postposition which (slightly) *emphasizes* what it follows, following **the object** of a main verb or an adverbial having a final consonant (๋ฐ์นจ) in a โโธป๊ณ ์ถ๋คโ construction.
>
>
>
> >
> > โ๋๋ ๋ฐฑ๋์ฐ์ด ์ ์ผ ๋ณด๊ณ ์ถ๋ค.โ
> >
> >
> >
>
>
>
Sometimes it works for an object, too. I cannot quite explain the connotation though.
|
5,328 |
I'm learning Sagang Textbook, and in the book has a homework like that:
"Read the following summary, find the mistakes and correct them (3 things)
>
> ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์. ์์ธ ์๋น์ ์ผ์์ง์ด์์. ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์์ด์. ๊ทธ๋์ ๋ง์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์. ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์. ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์. ํ์ง๋ง ์์ธ ์๋น ์์ ์จ๋ "ํ๋ ๋ ์ํค์ธ์"๋ผ๊ณ ๋งํ์ด์"
>
>
>
I think i know the other mistakes in this paragraph, but i am not sure about the phrase "๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์". I think it is not correct because ๋น๋น๋ฐฅ is object, so it must be ๋น๋น๋ฐฅ์, right? And because ๋ฏธ์์ฝ ์จ๋ is third person, so i think it must be ์ถ์ดํด์, so "๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์" must be "๋น๋ฐฅ์ ๋จน๊ณ ์ถ์ดํด์". Can you explain it for me? Thank you!
|
2019/06/16
|
[
"https://korean.stackexchange.com/questions/5328",
"https://korean.stackexchange.com",
"https://korean.stackexchange.com/users/1194/"
] |
I am afraid to say this, but there are more than three mistakes.
First of all, ์์ธ ์๋น is used too many times, although it is *not* a *grammatical* mistake. Even if ์์ธ ์๋น is a name of a restaurant, the repetitive use of *proper names for places* seems clumsy. You may use ์ด ์๋น, ๊ทธ ์๋น, ๊ทธ๊ณณ, or ๊ฑฐ๊ธฐ in place of ์์ธ ์๋น. Nonetheless, it is advisable to avoid using pronouns (๊ทธ๊ณณ and ๊ฑฐ๊ธฐ) repetitively.
Now, let me examine all the sentences. There are four people involved in the paragraph: one is the writer, and the others are ์งํ, ๋ฏธ์์ฝ, and ์์ธ ์๋น ์์ ์จ. The writer mentions what ์งํ and ๋ฏธ์์ฝ did.
>
> ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์.
>
>
>
Nothing is incorrect here.
>
> A. ์์ธ ์๋น์ ์ผ์์ง์ด์์.
>
>
> B. ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์์ด์.
>
>
> C. ๊ทธ๋์ ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์.
>
>
>
A lot of things should be considered:
* If ์์ธ ์๋น is a proper name, Sentence A is grammatically correct; if ์์ธ ์๋น refers to a/the restaurant in Seoul, it is logically *incorrect*.
* There are no clear reasons that Sentences A and B should be placed here in the paragraph, as they express what the writer thinks *not* what ์งํ thought. If you are not going to remove both Sentence A and Sentence B, it is one option to connect Sentence A to Sentence B; you might say "์์ธ ์๋น์ ์ผ์์ง**์ธ๋ฐ** ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ๊ณณ์ด์์**." *However*, this complex sentence does *not* relate to Sentence C.
* In Sentence C, there is *no* explicit subject. "Who did it?" You could assume that ์งํ introduced the restaurant to ๋ฏธ์์ฝ, but you should note that the previous subject is ์์ธ ์๋น [Note: ๋น๋น๋ฐฅ is kind of a sub-subject here] unless you remove Sentences A and B. "๊ทธ๋์ **์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์." will clearly show the subject, but Sentence C itself has insignificant problems without Sentences A and B because the repetitive indication of the same subject for consecutive sentences is usually avoided in Korean. Nonetheless, using Sentence C leaves a possibility that the writer (*not* ์งํ) told ๋ฏธ์์ฝ about the restaurant.
* You *cannot* simply remove Sentences A and B because the following sentence of Sentence C mentions ๋น๋น๋ฐฅ. If you would like to erase them, you have to use part of Sentence B somewhere before mentioning ๋ฏธ์์ฝ.
So, what would be a possible correction including the first sentence in the paragraph? I will mention only three as follows, but others' corrections could be better:
* ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ ๋ดค์ด์. **๊ทธ** ์๋น์ ์ผ์์ง**์ธ๋ฐ** ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ๊ณณ์ด์ฃ **. **๊ทธ๊ณณ ์์์ด ์ ๋ง ๋ง์์๋์ง ์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
**๊ทธ ์๋น**์ ์๊ฐํด ์คฌ์ด์.
* ์งํ ์จ๋ ์์ธ ์๋น์ ๊ฐ**์ ๋น๋น๋ฐฅ์ ์์ฃผ ๋ง์๊ฒ ๋จน์ ์ ์ด ์์ด์**. ๊ทธ๋์ **์งํ ์จ๋** ๋ฏธ์์ฝ ์จํํ
**๊ทธ ์๋น**์ ์๊ฐํด ์คฌ์ด์.
* ์งํ ์จ**๊ฐ** ์์ธ ์๋น**์ด ์ด๋ค์ง ์๊ธฐํด ์ค ์ ์ด ์์ด์**. **๊ทธ** ์๋น์ ์ผ์์ง์ธ๋ฐ ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์**๋ ์ง์ด๋ผ๋๊ตฐ์**. ๊ทธ๋์ **์ ๋** ๋ฏธ์์ฝ ์จํํ
์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์.
Please be aware that those three have totally different meanings. *You should rewrite the summary according to the original text*.
Here, another sentence comes.
>
> ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์.
>
>
>
"How does it relate to the previous sentence?" For cohesion, it will be clever to add when she wanted to eat ๋น๋น๋ฐฅ or other information. The following are two (*but not* the only) options:
* ๋ฏธ์์ฝ ์จ๋ **์๋น ์ถ์ฒ์ ๋ฐ์ ๋ค์** ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ ์์ธ ์๋น์ ๊ฐ์ด์.
* **๊ทธ ํ์** ๋ฏธ์์ฝ ์จ๋ ๋น๋น๋ฐฅ์ด ๋จน๊ณ ์ถ์ด์ **์๊ฐ๋ฐ์** ์๋น์ ๊ฐ์ด์.
>
> ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
>
>
>
"Who did this?" There is a possibility that the writer ordered ๋น๋น๋ฐฅ, but it is far more likely that she ordered the food.
There are some options to improve the sentence:
* **๊ทธ๋ฌ๊ณ ๋ ๊ทธ๊ณณ์์** ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
* **๋ฏธ์์ฝ ์จ๋ ๊ทธ๊ณณ์์** ๋น๋น๋ฐฅ ๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์.
>
> ํ์ง๋ง ์์ธ ์๋น ์์ ์จ๋ "ํ๋ ๋ ์ํค์ธ์"๋ผ๊ณ ๋งํ์ด์.
>
>
>
Four points I can point out:
* ํ๋ ๋ ์ํค์ธ์ is a sentence quote. It is advisable to place a period at its end, although it is allowed to omit a period there.
* It is difficult for me to judge whether ํ์ง๋ง is correct, but I would use ๊ทธ๋ฐ๋ฐ instead.
* I feel it somewhat rude to call a male person ์์ ์จ although some people use it. I would use ์ฃผ์ธ or ์ฌ์ฅ instead if he is an/the owner; ์ง์, if he is an employee.
* If you would like to keep ์์ ์จ here, it will be better to erase ์์ธ because the reader(s) now knows what the restaurant is.
So, I would put it as
* **๊ทธ๋ฐ๋ฐ** ์๋น **์ฃผ์ธ**์ **(๋ฏธ์์ฝ ์จ์๊ฒ)** "ํ๋ ๋ ์ํค์ธ์."๋ผ๊ณ ๋งํ์ด์.
or
* **๊ทธ๋ฐ๋ฐ** ์๋น **์ง์**์ **(๋ฏธ์์ฝ ์จ์๊ฒ)** "ํ๋ ๋ ์ํค์ธ์."๋ผ๊ณ ๋งํ์ด์.
---
To have more corrections, you may visit [Lang-8](https://lang-8.com/), but you should *not* trust all the users; some of them do *not* care much about grammar.
---
Edit:
I have noticed that the current rules allow the omission of the period at the end of a sentence quote. Accordingly, I have edited the relevant line.
|
First, `์ผ์์ง` is Japanese restaurant but `๋น๋น๋ฐฅ` is Korean food, so `...์ผ์์ง์ด์์. ํนํ ๋น๋น๋ฐฅ์ด ์์ฃผ ๋ง์์ด์` is ridiculous.
Second, `๊ทธ๋์ ๋ง์์ฝ ์จ์๊ฒ ์์ธ ์๋น์ ์๊ฐํด ์คฌ์ด์` has no subject. I think it can be skipped, but it is still somewhat awkward. Same thing with 6th sentence.
Third, this one is most obvious : `...๋ ๊ทธ๋ฆ์ ์์ผฐ์ด์. ํ์ง๋ง ์์ธ ์๋น ์์ ์จ๋ "ํ๋ ๋ ์ํค์ธ์"๋ผ๊ณ ๋งํ์ด์.` `ํ์ง๋ง` is inversion, like but. I think last sentence doesn't make any sense, even if `ํ์ง๋ง` changed to `๊ทธ๋์`.
Well, this is what I can find, but I think (specially) second one is not obvious.
|
73,132,473 |
Getting class as undefined for img tag in react.js
This is the component Header.jsx,
Here is the Header.jsx I'm using `<img>`, but the CSS properties are not not being implemented in the image, and I'm getting error as `class=undefined`
```
import React from 'react';
import classes from './header.css';
import { Box,Grid, Typography} from '@mui/material';
const Header = () => {
return (
<>
<Box sx={{ flexGrow: 1 }}>
<Grid container spacing={3}>
<Grid item xs>
<img src='./images/logo.svg' className={`${classes.header__logo}`} alt='Logo'/>
</Grid>
<Grid item xs={6}>
<Typography>gbr</Typography>
</Grid>
<Grid item xs>
<Typography>gbr</Typography>
</Grid>
</Grid>
</Box>
</>
)
}
export default Header
```
This is the css file for the header
```
/* header.css */
.header__logo{
height: 20px;
width: 50px;
}
```
In the console I'm getting this error, `class="undefined"`
```
<img src="./images/logo.svg" class="undefined" alt="Logo">
```
|
2022/07/27
|
[
"https://Stackoverflow.com/questions/73132473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18629021/"
] |
Add properties listed below to your `application.properties` and application name will be appended to all your logs:
```
spring.application.name=my-spring-boot-application
logging.pattern.level= %5p [${spring.application.name}]
```
|
In your application.properties you configured the name with:
```
spring.application.name=your-app-name
```
Then you can just Autowire it in with:
```
@Value("${spring.application.name}")
private String applicationName;
```
And then finally just log it:
```
LOGGER.info("Your application name: {}", applicationName);
```
|
5,870,809 |
I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file that can store this entry, which the I can easy custom the company id.
`config.py`
```
company_no = "Company id"
```
This can work in my forms.py file. I can import `company_no` by saying
`forms.py`
```
from mmc.config import company_no
```
But then how can I do the same thing for templates? Importing company\_no in a template - is there a way round?
|
2011/05/03
|
[
"https://Stackoverflow.com/questions/5870809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/512002/"
] |
As Blender stated, you need to pass variables like this in as part of the context when you render the template. You might make a dictionary or a namedtuple that has common items stored in configuration loaded in a function.
You should also consider using template inheritance if many templates will be display the same data, then you can have methods that load the pieces of context that go with certain base templates.
|
You could create a shared template and use [include](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include) to load it in to the main template. Then in the shared template you could load and call a [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) that produces a context variable and render it as usual.
Alternatively, you could create a [custom context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors) that loads the data automatically in to the context instance and then render it as usual in the shared template.
|
5,870,809 |
I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file that can store this entry, which the I can easy custom the company id.
`config.py`
```
company_no = "Company id"
```
This can work in my forms.py file. I can import `company_no` by saying
`forms.py`
```
from mmc.config import company_no
```
But then how can I do the same thing for templates? Importing company\_no in a template - is there a way round?
|
2011/05/03
|
[
"https://Stackoverflow.com/questions/5870809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/512002/"
] |
This is what [context processors](https://docs.djangoproject.com/en/1.11/ref/templates/api/#writing-your-own-context-processors) are for. Define your company name in settings.py, then write a context processor that imports it from there and returns it in a dictionary - it will then be available in every template (as long as you use RequestContext to render the template).
|
You could create a shared template and use [include](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include) to load it in to the main template. Then in the shared template you could load and call a [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) that produces a context variable and render it as usual.
Alternatively, you could create a [custom context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors) that loads the data automatically in to the context instance and then render it as usual in the shared template.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.