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
|
---|---|---|---|---|---|
8,638,109 | I saw a class "AttributeSelectedClassifier" was once created in the following ways:
```
AttributeSelectedClassifier classifier = new AttributeSelectedClassifier();
classifier.setClassifier(base);
classifier.setEvaluator(eval);
```
This above one looks natural to me. But how about the following one.
```
classifier = new AttributeSelectedClassifier();
((AttributeSelectedClassifier)classifier).setClassifier(base);
((AttributeSelectedClassifier)classifier).setEvaluator(eval);
```
I think it should be right, but I am not quite sure about the way of of defining classifier as ((AttributeSelectedClassifier)classifier), how to understand this usage? | 2011/12/26 | [
"https://Stackoverflow.com/questions/8638109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288609/"
] | This means that the classifier variable is declared as a superclass or superinterface of `AttributeSelectedClassifier`, and that you need to call a method which is not defined in the class or interface, but only on `AttributeSelectedClassifier`. This notation *casts* the variable to `AttributeSelectedClassifier`:
```
Object classifier = new AttributeSelectedClassifier();
// classifier is a AttributeSelectedClassifier, but references as Object
// to call the following method, we need to cast it to AttributeSelectedClassifier
((AttributeSelectedClassifier)classifier).setClassifier(base);
((AttributeSelectedClassifier)classifier).setEvaluator(eval);
```
This is usually the sign of a design problem. Either the methods should be in the superclass or interface, or the variable should be declared as `AttributeSelectedClassifier`. | By doing `((AttributeSelectedClassifier)classifier)` you are casting ("*forcing*") the `classifier` object to behave like an instance of `AttributeSelectedClassifier`.
The `classifier` variable was probably previously declared as a superclass of AttributeSelectedClassifier. |
8,638,109 | I saw a class "AttributeSelectedClassifier" was once created in the following ways:
```
AttributeSelectedClassifier classifier = new AttributeSelectedClassifier();
classifier.setClassifier(base);
classifier.setEvaluator(eval);
```
This above one looks natural to me. But how about the following one.
```
classifier = new AttributeSelectedClassifier();
((AttributeSelectedClassifier)classifier).setClassifier(base);
((AttributeSelectedClassifier)classifier).setEvaluator(eval);
```
I think it should be right, but I am not quite sure about the way of of defining classifier as ((AttributeSelectedClassifier)classifier), how to understand this usage? | 2011/12/26 | [
"https://Stackoverflow.com/questions/8638109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288609/"
] | Look at the below code. Person implements the `CanWalk` interface. If you assign a `Person` to `CanWalk` interface as shown in the main method, which is a common practice, you can only invoke the methods that are specified in the `CanWalk` interface i.e. `walk()`. If you want to invoke `f()`, that **isn't** declared in the `CanWalk` interface, then you would use the 2nd mechanism you have specified in your post. i.e. **cast** it to `Person` class and then invoke the method.
It is a good practice for the user's of the API (main method here) to use the correct abstraction while working with an object. For e.g. if the client is mainly focused on moving Person's then it should use CanWalk. This way client is not effected by changes to the Person class that are not related to movement. Read [this article](http://www.markhneedham.com/blog/2009/10/18/coding-role-based-interfaces/) for more details.
```
interface CanWalk
{
void walk();
}
class Person implements CanWalk
{
void walk()
{
System.out.println("I am walking");
}
void f()
{
///some arbitrary method
}
}
public stativ void main(String a[])
{
CanWalk cw=new Person();
((Person)cw).f();
}
``` | By doing `((AttributeSelectedClassifier)classifier)` you are casting ("*forcing*") the `classifier` object to behave like an instance of `AttributeSelectedClassifier`.
The `classifier` variable was probably previously declared as a superclass of AttributeSelectedClassifier. |
113,098 | I’m building a character for a one shot and my DM has okay’d my character being a vampire using the rules from the *Monster Manual* (under the ["Player Characters as Vampires"](https://www.dndbeyond.com/sources/mm/monsters-v#RegionalEffects) sidebar on p. 295).
What I am unsure on is what exactly it means when it says I gain the traits:
>
> In addition, the character gains the vampire’s damage resistances, darkvision, traits, and actions.
>
>
>
Does this mean PC vampires gain the Shapechanger, Legendary Resistance, Misty Escape, Regeneration, Spider Climb, and the Vampire Weaknesses traits?
If so this seems very strong, especially the Legendary Resistances and the regeneration.
I would be grateful for any clarification. | 2018/01/09 | [
"https://rpg.stackexchange.com/questions/113098",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/35947/"
] | RAW: yes, you gain the traits listed
------------------------------------
You have listed the traits correctly. According to the rules as written, not even Legendary Resistance gets special treatment. It is most likely because a PC-turned-vampire is more often than not an NPC. If you (or your GM or both of you) consider this to be too powerful, you could say that the transformation is not yet complete:
>
> The game statistics of a player character transformed into a vampire
> spawn and then a vampire... (MM 295)
>
>
>
And use the traits of the vampire spawn, found on the next page of the MM. You would "lose" Shapechanger, Misty Escape, Legendary Resistance, Children of the Night (action), and Charm (action), and the Regeneration is weaker. You could also say that Str, Dex, and Con are set to 16 only, as those are the stats of a spawn. | If balance is a key issue for you and your DM there are a couple of provisions in the MM that you should bear in mind.
First, one way to look at it is, as the commenter above me put it, whether or not the transformation to becoming a full-fledged vampire is complete. You and your DM would have to work together to determine what were the conditions under which you became a vampire and how long ago it happened. Note that becoming a vampire from being **bitten** by another one states that:
>
> A humanoid slain in this way and then buried in the ground rises the
> following night as a vampire spawn under the vampire's control (MM 297)
>
>
>
This means that if your character were a "fresh" or recently turned vampire, you'd likely be a spawn and not a full-fledged vampire. It would probably be a long time before you can become a full vampire if you didn't have the means to take the position by force. This is because, as the ***born from death*** entry on MM 295 states that:
>
> Most of a vampire's victims become vampire spawn- ravenous creatures with a vampire's hunger for blood, but under the control of the vampire that created them. If a true vampire allows a spawn to draw blood from its own body, the spawn transforms into a true vampire no longer under its master's control. Few vampires are willing to relinquish their control in this manner. ***Vampire spawn become free-willed when their creator dies.*** *[my emphasis]*
>
>
>
Even if being a spawn is not what you're going for and you only want to be a full vampire, you and your DM should remember that the bundle of negative traits that come with the positive ones can be played in ways to meaningfully limit your character (such as *Forbiddance*, *Harmed by Running Water*, *Stake to the Heart*, and *Sunlight Hypersensitivity*; MM 297/298).
Any time you have to enter a building, or go into the sun, or be near running water, your character could be severely gimped or face a skill challenge that no one else in your party would have to do. This may add some interesting mechanical and RP dimensions to your character. Ultimately whether or not that's enough to be considered an acceptable trade off for legendary resistance is up to you and your group. |
46,586,701 | I am trying to compare the current row value to the previous row value but only within the same group.
I have Group1 (Plant), ChildGroup1 (DeviceTag), Details Group,
I have tried this code within the Fill property but it does not work, it just seems to change the color of the first row every time per group regardless of the value of the previous row.
```
=IIf(Fields!DeviceTag.Value <> Previous(Fields!DeviceTag.Value), "Yellow", "White")
```
So my data set looks like this:
```
Plant DeviceTag Description Location
A Tag1 ABCD West
Tag1 WXYZ West DeviceTag Group 1
_____________________________________________
A Tag2 EFGH East
Tag2 IJKL East DeviceTag Group 2
Tag2 IJKL West
```
In both these DeviceTag Groups, the description changed so I would like to change the color of ABCD to yellow and EFGH to yellow but not WXYZ because it is not in the same group as EFGH. Also the Second row that says East should be Yellow since it is different than the previous West location.
In Crystal Reports you would do:
```
if {#ChangeCounter}=1 then nocolor else
if currentfieldvalue <> previous({DataSet.Field}) then cryellow else nocolor
```
Where the formula #ChangeCounter is just 1
Clear as mud?? | 2017/10/05 | [
"https://Stackoverflow.com/questions/46586701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996493/"
] | I always find this kind of thing easier to do in the dataset query (assuming you can control the query in the dataset).
Manipulate your final dataset (the one SSRS will receive) to have another column which tells SSRS to color the cell or not. And keep your business logic in the DB query.
You could number each row (within each group) using `row_number()` and then join the table back into itself on the new row number column.
Something like this perhaps? I am not sure I 100% follow your cell shading logic and I am sure your dataset is larger than what you provided, but you may be able to adapt this to meet your needs.
```
;with Data as
(
select 'A' as Plant, 'Tag1' as DeviceTag, 'ABCD' as Description, 'West' as Location union all
select 'A' as Plant, 'Tag1' as DeviceTag, 'WXYZ' as Description, 'West' as Location union all
select 'A' as Plant, 'Tag2' as DeviceTag, 'EFGH' as Description, 'East' as Location union all
select 'A' as Plant, 'Tag2' as DeviceTag, 'IJKL' as Description, 'East' as Location union all
select 'A' as Plant, 'Tag2' as DeviceTag, 'IJKL' as Description, 'West' as Location
),
DataWithRowNumbers as
(
select
*,
row_number() over (partition by DeviceTag order by Description) as DeviceTagGroupRowNumber
from
Data
)
select
a.*,
case when a.Description != b.Description then 'Yellow' else 'Transparent' end as CellColor
from
DataWithRowNumbers a
left join DataWithRowNumbers b on a.DeviceTag = b.DeviceTag and a.DeviceTagGroupRowNumber = b.DeviceTagGroupRowNumber - 1
```
Then you can set the background in the cell (in SSRS) to an expression which will just be `Fields!CellColor.Value`. | You need to use the Scope parameter of the Previous function, providing the name of your ChildGroup1 (DeviceTag). e.g.
=IIf(Fields!DeviceTag.Value <> Previous(Fields!DeviceTag.Value , "ChildGroup1" ), "Yellow", "White")
Here's the doco:
<https://learn.microsoft.com/en-us/sql/reporting-services/report-design/report-builder-functions-previous-function> |
61,575,944 | I want to create a menu that works with embedded systems. I use C.
This is how I plan to make it:
1. First, the pressed keys are identified by the interrupts.
2. A array is update on those identifications.
3. Find the corresponding term acording to array content.
4. The operation is performed.
My array is like this. Array nth item represent different levels.
Each element represent level item number.
```
uint8_t menu_map[5] = {2, 3, 1, 0, 0};
```
My question is:
How to choose a function pointer or structure acording to array content?
like this(acording to array content i mentioned as before example).
```
function_23100(){
// Function content
}
```
Is there a way to do that?
Is there any other good alternative to do this kind of menu? | 2020/05/03 | [
"https://Stackoverflow.com/questions/61575944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are several ways to archive but in the end, they are both hard to maintain and cause performance down. Let's say you would build a lookup table to ref to, assume you have 4 buttons, an array with 5 entries -> the size of lookup table(worse case) is `4x4x4x4x4 = 1024` entries. Finding the corresponding action in this table per each button press is not that good in term of performance.
Let's back to what you wanna to archive, check below code for your ref.
By create a menu tree, bind callback to each menu item and keep track the path of current menu item, it's not that difficult to travel back and forth in menu tree. Once you enter a specific menu item, it's easy to access to its callback by the pointer that was assigned to.
```
#include <stdio.h>
#define MENU(name, text, nr_item, ...) \
static menu_t name = { \
{ text, NULL, nr_item, __VA_ARGS__ }, { 0 }, -1 \
}
#define MENU_ITEMS(...) (menu_item_t[]) { __VA_ARGS__ }
#define MAX_DEPTH 10
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
typedef struct menu_item menu_item_t;
struct menu_item {
const char *text;
void (*action)(menu_item_t*);
int nr_of_children;
menu_item_t *children;
};
typedef struct {
menu_item_t item;
menu_item_t* _history[MAX_DEPTH];
int _history_index;
} menu_t;
static inline void print_menu_history(menu_t *menu) {
int i = 0;
for (i = 0; i < MAX_DEPTH; i++) {
if (!menu->_history[i]) break;
printf("> %s ", menu->_history[i]->text);
}
printf("\n");
}
static inline void print_menu(menu_t *menu) {
menu_item_t *item = menu->_history[menu->_history_index];
int i;
printf("= %s\n", item->text);
for (i = 0; i < item->nr_of_children; i++) {
printf("- [%2d] %s\n", i, item->children[i].text);
}
printf("==========================================\n");
print_menu_history(menu);
printf("==========================================\n");
}
static inline void add_item_to_history(menu_t *menu, int position) {
if (menu->_history_index < 0) {
menu->_history_index = 0;
menu->_history[menu->_history_index] = &menu->item;
} else {
if (position < menu->_history[menu->_history_index]->nr_of_children)
menu->_history[++menu->_history_index] =
&menu->_history[menu->_history_index]->children[position];
}
}
static inline void exec_menu_action(menu_t *menu, int position) {
if (menu->_history[menu->_history_index]->action)
menu->_history[menu->_history_index]->action(menu->_history[menu->_history_index]);
}
static inline void exit_menu(menu_t *menu) {
if (menu->_history_index > 0)
menu->_history[menu->_history_index--] = NULL;
print_menu(menu);
}
static inline void enter_menu(menu_t *menu, int position) {
add_item_to_history(menu, position);
exec_menu_action(menu, position);
print_menu(menu);
}
static void menu_item_action(menu_item_t *item) {
if (item) printf("=========='%s' selected\n", item->text);
}
MENU(main_menu, "Menu", 2,
MENU_ITEMS(
{ "Item 1", menu_item_action, 3,
MENU_ITEMS(
{ "Item 1.1", menu_item_action, 3,
MENU_ITEMS(
{ "Item 1.1.1", menu_item_action, 0, NULL },
{ "Item 1.1.2", menu_item_action, 0, NULL },
{ "Item 1.1.3", menu_item_action, 0, NULL }
)
},
{ "Item 1.2", menu_item_action, 0, NULL },
{ "Item 1.3", menu_item_action, 0, NULL }
)
},
{ "Item 2", menu_item_action, 2,
MENU_ITEMS(
{ "Item 2.1", menu_item_action, 0, NULL },
{ "Item 2.2", menu_item_action, 0, NULL }
)
}
)
);
int main(int argc, char *argv[]) {
unsigned char c = 0;
int samples[] = {1, 0, 1, 0, 0};
enter_menu(&main_menu, -1);
for (c = 0; c < ARRAY_SIZE(samples); c++) {
enter_menu(&main_menu, c);
}
while(c != 'q') {
c = getchar();
if ('b' == c) exit_menu(&main_menu);
if ((c <= '9') && (c >= '0')) enter_menu(&main_menu, c - '0');
}
return 0;
}
``` | You can use simple conditionals and assign a dictionary for each value.
Firstly, convert the array of numbers into just a singular number-
```c
int arr_to_int(int* arr, int len)
{
int number = 0;
for (int i = 0, val; i < len; i++)
{
val = arr[i];
while (val != 0)
{
val = val / 10;
number = number * 10;
}
number = number + arr[i];
}
return number;
}
```
Now pass the number to a switch case-
```c
switch(number)
{
case 23100:
function_23100();
break;
.....
}
```
Unfortunately, there's no easier way. Perhaps you were thinking about some hacky c macro. But that's not going to work because the preprocessor cannot evaluate a variable as it happens before the code is compiled.
Edit: Something I should mention, this would work for languages that support **reflection**. i.e languages that can call a function according to its string representation. So if you could do `find_method("function_23100")`, it'd find the corresponding function and call it. And really all you need to get the string `function_23100` is just have a helper function, that can concatenate `function_` and the string representation of `num`. Now, there are ways to implement reflection in `C`. If you'd like to do that (and think it's not absolutely overkill), then read [this](https://stackoverflow.com/questions/1353022/reflection-support-in-c) |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | ***Basic form:*** space bias
this is a basic form that has no anchors or boundrys
`(?:[ ]|\d(?![ ])){8}\d`
[dem0](https://regex101.com/r/rS05bf/1)
feature:
* block of 9
* minimum block size of 2
* match takes maximum spaces vs minimal digits
---
***Basic form:*** number bias
same basic form that has been modified to get number bias.
`(?=((?:[ ]|\d(?![ ])){8}\d(?!\d)|\d{9}))\1`
[dem1](https://regex101.com/r/aEiR2p/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
---
End of line ***Anchor method*** (numeric bias) :
`(?=[ ]{0,8}?\d{1,9}(.*)$)[ \d]{9}(?=\1$)`
[dem2](https://regex101.com/r/doHs1H/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
* single capture is not part of match
* line orientated regex, needs `multi-line option` if string is more than 1 line | 1. Add a comma before the spaces
2. split at the comma
3. keep only either space or digits
4. Count number of characters and see if it matches the required size
```
s = c("123456789", "kfasdf 3456789asdf",
"a 1", "12345 789", "1 9",
"a 678a")
sapply(strsplit(gsub("(\\s+)", ",\\1", s), ","), function(x) {
any(nchar(gsub("[A-Za-z]", "", x)) == 9)
})
#[1] TRUE TRUE TRUE FALSE FALSE FALSE
``` |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | Another option is to match 8 times either a digit OR a space not preceded by a digit and then match a digit at the end.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d
```
*In parts*
* `(?<![\d\h])` Negative lookbehind, assert what is on the left is not a horizontal whitespace char or digit
* `(?>` Atomic group (no backtracking)
+ `\d` Match a digit
+ `|` Or
+ `\h(?<!\d\h)` Match a horizontal whitespace char asserting that it is not preceded by a digit
* `){8}` Close the group and repeat 8 times
* `\d` Match the last digit
[Regex demo](https://regex101.com/r/d6P6MI/1) | [R demo](https://ideone.com/sdRSch)
Example code, using *perl=TRUE*
```
x <- "123456789
kfasdf 3456789asdf
a 1
12345 789
1 9
a 678a"
regmatches(x, gregexpr("(?<![\\d\\h])(?>\\d|(?<!\\d)\\h){8}\\d", x, perl=TRUE))
```
Output
```
[[1]]
[1] "123456789" " 3456789" " 1"
```
If there can not be a digit present after matching the last 9th digit, you could end the pattern with a negative lookahead asserting not a digit.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/8qz1cd/1)
If there can not be any digits on any side:
```
(?<!\d)(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/mtGB7T/1) | If you are looking for a clean **regex** solution, then you should use the following pattern:
```
(?=[ \\d]{9}(.*$))[ ]*\\d+\\1$
```
...where you combine a positive lookahead with a regular matching that includes a match from the lookahead.
The **R** syntax is then
```
str_extract(x, regex('(?=[ \\d]{9}(.*$))[ ]*\\d+\\1$'))
```
and you can test this code [here](https://ideone.com/20Q11B).
---
If your desire is also to catch a matching N-character long substring, then use
```
str_match(x, regex('(?=[ \\d]{9}(.*$))([ ]*\\d+)\\1$')) [,3]
```
as shown in [this demo](https://ideone.com/7JeBU1). |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | ***Basic form:*** space bias
this is a basic form that has no anchors or boundrys
`(?:[ ]|\d(?![ ])){8}\d`
[dem0](https://regex101.com/r/rS05bf/1)
feature:
* block of 9
* minimum block size of 2
* match takes maximum spaces vs minimal digits
---
***Basic form:*** number bias
same basic form that has been modified to get number bias.
`(?=((?:[ ]|\d(?![ ])){8}\d(?!\d)|\d{9}))\1`
[dem1](https://regex101.com/r/aEiR2p/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
---
End of line ***Anchor method*** (numeric bias) :
`(?=[ ]{0,8}?\d{1,9}(.*)$)[ \d]{9}(?=\1$)`
[dem2](https://regex101.com/r/doHs1H/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
* single capture is not part of match
* line orientated regex, needs `multi-line option` if string is more than 1 line | If you are looking for a clean **regex** solution, then you should use the following pattern:
```
(?=[ \\d]{9}(.*$))[ ]*\\d+\\1$
```
...where you combine a positive lookahead with a regular matching that includes a match from the lookahead.
The **R** syntax is then
```
str_extract(x, regex('(?=[ \\d]{9}(.*$))[ ]*\\d+\\1$'))
```
and you can test this code [here](https://ideone.com/20Q11B).
---
If your desire is also to catch a matching N-character long substring, then use
```
str_match(x, regex('(?=[ \\d]{9}(.*$))([ ]*\\d+)\\1$')) [,3]
```
as shown in [this demo](https://ideone.com/7JeBU1). |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | Another option is to match 8 times either a digit OR a space not preceded by a digit and then match a digit at the end.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d
```
*In parts*
* `(?<![\d\h])` Negative lookbehind, assert what is on the left is not a horizontal whitespace char or digit
* `(?>` Atomic group (no backtracking)
+ `\d` Match a digit
+ `|` Or
+ `\h(?<!\d\h)` Match a horizontal whitespace char asserting that it is not preceded by a digit
* `){8}` Close the group and repeat 8 times
* `\d` Match the last digit
[Regex demo](https://regex101.com/r/d6P6MI/1) | [R demo](https://ideone.com/sdRSch)
Example code, using *perl=TRUE*
```
x <- "123456789
kfasdf 3456789asdf
a 1
12345 789
1 9
a 678a"
regmatches(x, gregexpr("(?<![\\d\\h])(?>\\d|(?<!\\d)\\h){8}\\d", x, perl=TRUE))
```
Output
```
[[1]]
[1] "123456789" " 3456789" " 1"
```
If there can not be a digit present after matching the last 9th digit, you could end the pattern with a negative lookahead asserting not a digit.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/8qz1cd/1)
If there can not be any digits on any side:
```
(?<!\d)(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/mtGB7T/1) | ***Basic form:*** space bias
this is a basic form that has no anchors or boundrys
`(?:[ ]|\d(?![ ])){8}\d`
[dem0](https://regex101.com/r/rS05bf/1)
feature:
* block of 9
* minimum block size of 2
* match takes maximum spaces vs minimal digits
---
***Basic form:*** number bias
same basic form that has been modified to get number bias.
`(?=((?:[ ]|\d(?![ ])){8}\d(?!\d)|\d{9}))\1`
[dem1](https://regex101.com/r/aEiR2p/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
---
End of line ***Anchor method*** (numeric bias) :
`(?=[ ]{0,8}?\d{1,9}(.*)$)[ \d]{9}(?=\1$)`
[dem2](https://regex101.com/r/doHs1H/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
* single capture is not part of match
* line orientated regex, needs `multi-line option` if string is more than 1 line |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | The desired substring contains 9 digits or fewer than 9 digits. In the second case it begins with a space, ends with a digit and each of the 7 characters in between is a space preceded by a space or a digit followed by a digit. We therefore could use the following regular expression.
```
\d{9}|\s(?:(?<=\s)\s|\d(?=\d)){7}\d
```
[Demo](https://regex101.com/r/P9wNDC/1/)
The regex engine performs the following operations.
```
\d{9} : match 9 digits
| : or
\s : match a space
(?: : begin non-capture group
(?<=\s) : next character must be preceded by a space
\s : match a space
| : or
\d : match a digit
(?=\d) : next character must be a digit
) : end non-capture group
{7} : execute non-capture group 7 times
\d : match a digit
``` | That's not an easy task for regexp-s. You really should consider parsing the string yourself. At least partially. Because you need the lengths of capturing groups and regexp-s do not have this feature.
But if you really want to use them, then there's a workaround:
I'll use JS so that the code can be ran right here.
```js
const re = /^(.*)(\s*\d+)(.*)$(?<=\1.{9}\3)/
console.log(re.test("123456789"))
console.log(re.test("kfasdf 3456789asdf"))
console.log(re.test("a 1"))
console.log(re.test("12345 789"))
console.log(re.test("1 9" ))
console.log(re.test("a 678a"))
```
where
1. `\s*\d+` meets your base condition of zero or more spaces followed by one or more digits
2. we can't get groups' lengths, but we can get everything before and after the main group. That is what `^(.*)` and `(.*)$` are for.
3. Now we need to check that all three groups add up to a full string, for that we use look behind assertion `(?<=\1.{9}\3)` and we set the desired `N` for a number of symbols allowed in the main group (9 in this case)
You didn't mention how the regexp should behave in all situations, for example in this one:
```
" 3456780000000"
```
with extra spaces and extra digits.
So I won't try to guess. But it's easy to fix the regexp I've provided for all your cases.
**Update:**
I think the Edward's [**original** answer](https://stackoverflow.com/a/62226300/12610347) is the best for you (look in the history). But not sure about boundary constraints. They are not clear from your question.
But I'll still leave mine because, while Edward's answer is shortest and fastest for your specific case, mine is more general and better suits the **title of the question**.
And I added performance tests:
```js
const chars = Array(1000000)
const half_len = chars.length/2
chars.fill("a", 0, half_len)
chars.fill("1", half_len, half_len + 9)
chars.fill("a", half_len + 9)
const str = chars.join("")
function test(name, re) {
console.log(name)
console.time(re.toString())
const res = re.test(str)
console.timeEnd(re.toString())
console.log("res",res)
}
test("Edward's original", /((?<!\d)\s|\d){9}(?<=\d)/)
test("Ωmega's" , /(?=[ \d]{9}(.*$))[ ]*\d+\1$/)
test("Edward's modified", /(?=[ ]{0,8}?\d{1,9}(.*))[ \d]{9}(?=\1$)/)
test("mine" , /^(.*)(\s*\d+)(.*)$(?<=\1.{9}\3)/)
```
Surely lookbehinds are not cheap! |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | Another option is to match 8 times either a digit OR a space not preceded by a digit and then match a digit at the end.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d
```
*In parts*
* `(?<![\d\h])` Negative lookbehind, assert what is on the left is not a horizontal whitespace char or digit
* `(?>` Atomic group (no backtracking)
+ `\d` Match a digit
+ `|` Or
+ `\h(?<!\d\h)` Match a horizontal whitespace char asserting that it is not preceded by a digit
* `){8}` Close the group and repeat 8 times
* `\d` Match the last digit
[Regex demo](https://regex101.com/r/d6P6MI/1) | [R demo](https://ideone.com/sdRSch)
Example code, using *perl=TRUE*
```
x <- "123456789
kfasdf 3456789asdf
a 1
12345 789
1 9
a 678a"
regmatches(x, gregexpr("(?<![\\d\\h])(?>\\d|(?<!\\d)\\h){8}\\d", x, perl=TRUE))
```
Output
```
[[1]]
[1] "123456789" " 3456789" " 1"
```
If there can not be a digit present after matching the last 9th digit, you could end the pattern with a negative lookahead asserting not a digit.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/8qz1cd/1)
If there can not be any digits on any side:
```
(?<!\d)(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/mtGB7T/1) | 1. Add a comma before the spaces
2. split at the comma
3. keep only either space or digits
4. Count number of characters and see if it matches the required size
```
s = c("123456789", "kfasdf 3456789asdf",
"a 1", "12345 789", "1 9",
"a 678a")
sapply(strsplit(gsub("(\\s+)", ",\\1", s), ","), function(x) {
any(nchar(gsub("[A-Za-z]", "", x)) == 9)
})
#[1] TRUE TRUE TRUE FALSE FALSE FALSE
``` |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | ***Basic form:*** space bias
this is a basic form that has no anchors or boundrys
`(?:[ ]|\d(?![ ])){8}\d`
[dem0](https://regex101.com/r/rS05bf/1)
feature:
* block of 9
* minimum block size of 2
* match takes maximum spaces vs minimal digits
---
***Basic form:*** number bias
same basic form that has been modified to get number bias.
`(?=((?:[ ]|\d(?![ ])){8}\d(?!\d)|\d{9}))\1`
[dem1](https://regex101.com/r/aEiR2p/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
---
End of line ***Anchor method*** (numeric bias) :
`(?=[ ]{0,8}?\d{1,9}(.*)$)[ \d]{9}(?=\1$)`
[dem2](https://regex101.com/r/doHs1H/1)
feature:
* block of 9
* minimum block size of 2
* match takes minimal spaces vs maximum digits
* single capture is not part of match
* line orientated regex, needs `multi-line option` if string is more than 1 line | You may use the [regex pattern](https://regex101.com/r/7IlxOa/2)
```
[ \d](?:(?<=[ ])[ ]|\d){7}\d
```
and in **R** use
```
str_extract(x, regex('[ \\d](?:(?<=[ ])[ ]|\\d){7}\\d'))
```
See [this demo](https://ideone.com/tWIouq).
---
[](https://i.stack.imgur.com/a2fOG.png)
*Please note that in the above regex pattern the `[ ]` may be replaced by a simple space character. Using `[ ]` is a common practice to increase readability.* |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | Using string `s` from @d.b's answer.
Extract optional whitespace followed by numbers.
```
library(stringr)
str_extract(s, '(\\s+)?\\d+')
#[1] "123456789" " 3456789" " 1" "12345" "1" " 678"
```
Check their length using `nchar`.
```
nchar(str_extract(s, '(\\s+)?\\d+')) == 9
#[1] TRUE TRUE TRUE FALSE FALSE FALSE
```
Using the same logic in base R function.
```
nchar(regmatches(s, regexpr('(\\s+)?\\d+', s))) == 9
#[1] TRUE TRUE TRUE FALSE FALSE FALSE
```
---
If there could be multiple such instances we can use `str_extract_all` :
```
sapply(str_extract_all(s, '(\\s+)?\\d+'), function(x) any(nchar(x) == 9))
``` | 1. Add a comma before the spaces
2. split at the comma
3. keep only either space or digits
4. Count number of characters and see if it matches the required size
```
s = c("123456789", "kfasdf 3456789asdf",
"a 1", "12345 789", "1 9",
"a 678a")
sapply(strsplit(gsub("(\\s+)", ",\\1", s), ","), function(x) {
any(nchar(gsub("[A-Za-z]", "", x)) == 9)
})
#[1] TRUE TRUE TRUE FALSE FALSE FALSE
``` |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | You may use the [regex pattern](https://regex101.com/r/7IlxOa/2)
```
[ \d](?:(?<=[ ])[ ]|\d){7}\d
```
and in **R** use
```
str_extract(x, regex('[ \\d](?:(?<=[ ])[ ]|\\d){7}\\d'))
```
See [this demo](https://ideone.com/tWIouq).
---
[](https://i.stack.imgur.com/a2fOG.png)
*Please note that in the above regex pattern the `[ ]` may be replaced by a simple space character. Using `[ ]` is a common practice to increase readability.* | That's not an easy task for regexp-s. You really should consider parsing the string yourself. At least partially. Because you need the lengths of capturing groups and regexp-s do not have this feature.
But if you really want to use them, then there's a workaround:
I'll use JS so that the code can be ran right here.
```js
const re = /^(.*)(\s*\d+)(.*)$(?<=\1.{9}\3)/
console.log(re.test("123456789"))
console.log(re.test("kfasdf 3456789asdf"))
console.log(re.test("a 1"))
console.log(re.test("12345 789"))
console.log(re.test("1 9" ))
console.log(re.test("a 678a"))
```
where
1. `\s*\d+` meets your base condition of zero or more spaces followed by one or more digits
2. we can't get groups' lengths, but we can get everything before and after the main group. That is what `^(.*)` and `(.*)$` are for.
3. Now we need to check that all three groups add up to a full string, for that we use look behind assertion `(?<=\1.{9}\3)` and we set the desired `N` for a number of symbols allowed in the main group (9 in this case)
You didn't mention how the regexp should behave in all situations, for example in this one:
```
" 3456780000000"
```
with extra spaces and extra digits.
So I won't try to guess. But it's easy to fix the regexp I've provided for all your cases.
**Update:**
I think the Edward's [**original** answer](https://stackoverflow.com/a/62226300/12610347) is the best for you (look in the history). But not sure about boundary constraints. They are not clear from your question.
But I'll still leave mine because, while Edward's answer is shortest and fastest for your specific case, mine is more general and better suits the **title of the question**.
And I added performance tests:
```js
const chars = Array(1000000)
const half_len = chars.length/2
chars.fill("a", 0, half_len)
chars.fill("1", half_len, half_len + 9)
chars.fill("a", half_len + 9)
const str = chars.join("")
function test(name, re) {
console.log(name)
console.time(re.toString())
const res = re.test(str)
console.timeEnd(re.toString())
console.log("res",res)
}
test("Edward's original", /((?<!\d)\s|\d){9}(?<=\d)/)
test("Ωmega's" , /(?=[ \d]{9}(.*$))[ ]*\d+\1$/)
test("Edward's modified", /(?=[ ]{0,8}?\d{1,9}(.*))[ \d]{9}(?=\1$)/)
test("mine" , /^(.*)(\s*\d+)(.*)$(?<=\1.{9}\3)/)
```
Surely lookbehinds are not cheap! |
60,777,481 | I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
```
then dashpercent and dashsubject give an error that they are not declared.
Adapter
```
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
@Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
```
dashboadfragment:
```
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
```
dashbord\_recycler\_componets:
```
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
```
MainActivity:
```
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60777481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12505541/"
] | Another option is to match 8 times either a digit OR a space not preceded by a digit and then match a digit at the end.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d
```
*In parts*
* `(?<![\d\h])` Negative lookbehind, assert what is on the left is not a horizontal whitespace char or digit
* `(?>` Atomic group (no backtracking)
+ `\d` Match a digit
+ `|` Or
+ `\h(?<!\d\h)` Match a horizontal whitespace char asserting that it is not preceded by a digit
* `){8}` Close the group and repeat 8 times
* `\d` Match the last digit
[Regex demo](https://regex101.com/r/d6P6MI/1) | [R demo](https://ideone.com/sdRSch)
Example code, using *perl=TRUE*
```
x <- "123456789
kfasdf 3456789asdf
a 1
12345 789
1 9
a 678a"
regmatches(x, gregexpr("(?<![\\d\\h])(?>\\d|(?<!\\d)\\h){8}\\d", x, perl=TRUE))
```
Output
```
[[1]]
[1] "123456789" " 3456789" " 1"
```
If there can not be a digit present after matching the last 9th digit, you could end the pattern with a negative lookahead asserting not a digit.
```
(?<![\d\h])(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/8qz1cd/1)
If there can not be any digits on any side:
```
(?<!\d)(?>\d|(?<!\d)\h){8}\d(?!\d)
```
[Regex demo](https://regex101.com/r/mtGB7T/1) | The desired substring contains 9 digits or fewer than 9 digits. In the second case it begins with a space, ends with a digit and each of the 7 characters in between is a space preceded by a space or a digit followed by a digit. We therefore could use the following regular expression.
```
\d{9}|\s(?:(?<=\s)\s|\d(?=\d)){7}\d
```
[Demo](https://regex101.com/r/P9wNDC/1/)
The regex engine performs the following operations.
```
\d{9} : match 9 digits
| : or
\s : match a space
(?: : begin non-capture group
(?<=\s) : next character must be preceded by a space
\s : match a space
| : or
\d : match a digit
(?=\d) : next character must be a digit
) : end non-capture group
{7} : execute non-capture group 7 times
\d : match a digit
``` |
49,272,176 | I'm trying to initialise a value in dictionary as follow,
```
var og:image: String
```
But after `og:` it tries to assign the type considering `og` as the variable to site\_name, which is obviously wrong.
>
> Is there a way to assign `og:image` as variable to `String` type using
> special or escape characters?
>
>
>
In [reference](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/decimal-digits) to this, apple does not provide any meaningful explanations to variable naming conventions in such a situation.
Edit-1:
Here is code snippet to clarify dictionary `usage` is in JSON parsing data structure,
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
``` | 2018/03/14 | [
"https://Stackoverflow.com/questions/49272176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5484311/"
] | You cannot use : (colon). But if you really want:
```
var ogCOLONimage: String
```
Joking apart. You could use a Dictionary or something like that:
```
var images: [String: String] = ["og:image" : "your string"]
```
Now you can access your `og:image` data with `images["og:image"]`. | Swift allow you to use almost any character when naming variables. You can even use Unicode characters.
However, there are a few restrictions:
>
> Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.
>
>
>
Said that, it is not possible to use `:` in the name of a variable. However, you can use a Unicode character similar to that symbol. Depending on what you want it for, this may be a valid solution.
Here you have a list of the Unicode characters similar to `:` that can be used in the name of a variable:
* `︓`
* `﹕`
* `:`
(<https://www.compart.com/en/unicode/based/U+003A>)
Based on the example you provided it would be this:
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
``` |
49,272,176 | I'm trying to initialise a value in dictionary as follow,
```
var og:image: String
```
But after `og:` it tries to assign the type considering `og` as the variable to site\_name, which is obviously wrong.
>
> Is there a way to assign `og:image` as variable to `String` type using
> special or escape characters?
>
>
>
In [reference](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/decimal-digits) to this, apple does not provide any meaningful explanations to variable naming conventions in such a situation.
Edit-1:
Here is code snippet to clarify dictionary `usage` is in JSON parsing data structure,
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
``` | 2018/03/14 | [
"https://Stackoverflow.com/questions/49272176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5484311/"
] | Turns out swift has it's own feature in terms of naming specificity of variables in structs i.e. `CodingKeys`, so in terms for me the below naming convention worked,
```
struct Metadata: Decodable{
var metatags: [enclosedTags]
}
struct enclosedTags: Decodable{
let image: String
let title: String
let description: String
let siteName: String
private enum CodingKeys : String, CodingKey{
case image = "og:image", title = "og:title", description = "og:description", siteName = "og:site_name"
}
```
This was rightfully pointed out by `@hamish` in comments (Thanks mate!) | Swift allow you to use almost any character when naming variables. You can even use Unicode characters.
However, there are a few restrictions:
>
> Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.
>
>
>
Said that, it is not possible to use `:` in the name of a variable. However, you can use a Unicode character similar to that symbol. Depending on what you want it for, this may be a valid solution.
Here you have a list of the Unicode characters similar to `:` that can be used in the name of a variable:
* `︓`
* `﹕`
* `:`
(<https://www.compart.com/en/unicode/based/U+003A>)
Based on the example you provided it would be this:
```
struct Metadata: Decodable{
var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
var image: String
var title: String
var description: String
var og:site_name: String
}
``` |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | Yes, as long as you are responsible with the payments and treat it as a cash substitute, and not a loan. I waited until I was 21 to apply for my first credit card, which gave me a later start to my credit history.
That led to an embarrassing credit rejection when I went to buy some furniture after I graduated college. You'd think $700 split into three interest-free payments wouldn't be too big of a risk, but I was rejected since my credit history was only 4 months long, even though I had zero late payments.
So I ended up paying cash for the furniture instead, but it was still a horrible feeling when the sales rep came back to me and quietly told me my credit application had been denied. | >
> Assuming I only use it to buy things I can afford (which I trust
> myself to do), essentially treating it as a debit card, is this a good
> idea?
>
>
>
This is definitely a good idea.
From my own experience, before I got my first credit card through my local bank (age 18), I tired to apply for a card that has cash back rewards and was rejected because I didn't have any credit history. After I had the card from my bank for 6 months, I applied for [this Capital One](http://www.capitalone.com/credit-cards/quicksilver/) card that I've had ever since. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | I also feel it's important to NOT get a credit card. I'm in my mid 30's and have had credit cards since I was 20, as has everyone I know. Every single one of those people, with the exception of my dad, is currently carrying some amount of credit card debt - almost always in the thousands of dollars.
Here is the essential problem with credit cards. Everyone sets out with good intentions, to use the credit card like a debit card, and pay charges off before interest accrues. However, almost no-one has the discipline to remember to do this, and a balance quickly builds up on the card. Also, it's extremely easy to prioritize other bill payments before credit card payments, resulting in a balance building up on the card.
It's almost magical how quickly a balance will build up on a credit card. Ultimately, they are simply too convenient, too tempting for most human beings.
The world, and especially the North American world, is in a massive debt crisis. It is very easy to borrow money these days, and our culture is at the point where "buy now pay later" is an accepted practice.
Now that I have young children, I will be teaching them the golden rule of "don't buy something until you have cash to pay for it in full!" It sounds like an over simplification but this one rule will save you an incredible amount of financial grief over time. | I will disagree with the other answers. The idea that there is some to establish a "credit history" is largely a myth propagated by loaners who see it as positive propaganda to increase the numbers of their prospective customers.
You will find some people who claim they were rejected for a card because they had no "credit history," but in every case what these people are not telling you is they also had no income (were students, house wives, or others with no steady income). Anyone who has income can get a credit card or other line of credit regardless of their "credit history." Even people who have gone bankrupt can get credit cards if they have proven income.
If your answer to this is that "you have no income, but still want a credit card", I would advise you to re-read that sentence several times and think carefully about it.
I have never had a credit card and never missed having one, except when trying to rent cars which was somewhat complex and annoying to do in the 2005-2010 time period without a credit card.
Credit cards have a number of disadvantages:
* They provide a temptation to waste money on luxury goods you do not
need
* The interest rates on credit cards are relatively high
* You greatly increase your chances for having your identity stolen
* All your purchases using the card are tracked and the information is
provided to various organizations and people around the world, many
of whom you would not want having your purchase information if you
knew who they were.
I definitely agree with those who will tell you credit cards are convenient, they are, but for someone who wants to be financially prudent and build wealth they are unnecessary and unwise.
If you don't believe me, read "The Total Money Makeover" by David Ramsey, one of the most famous and best-selling books ever written on personal finance. He actually will give you much better and detailed reasons to avoid CCs than me. After all, who am I, just some dumb rich schmuck with lots of money and no debt and a happy life.
**Comment on Culture**
I think it is pretty funny we have a lot of spendthrift Americans in this thread basically telling the OP to get lots of credit cards as soon as possible. If you asked the same question in Japan you would get completely different answers and votes. In Japan its hard to even use credit cards. The people there are much more responsible financially than Americans; the average Japanese person has much higher wealth than a person with the same income in the United States. One of the reasons for this, among many, is that the average Japanese person does not use credit cards. A Japanese person, if you translated this question for them, would think the whole thing a typical example of how foolish Americans are. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | The length of time you have established credit does improve your credit score in the long run.
As long as you can avoid paying interest, you might see if you can get a card with cash back rewards. I have one from Citi that sends me a $50 check every so often when I have enough rewards built up. | I will disagree with the other answers. The idea that there is some to establish a "credit history" is largely a myth propagated by loaners who see it as positive propaganda to increase the numbers of their prospective customers.
You will find some people who claim they were rejected for a card because they had no "credit history," but in every case what these people are not telling you is they also had no income (were students, house wives, or others with no steady income). Anyone who has income can get a credit card or other line of credit regardless of their "credit history." Even people who have gone bankrupt can get credit cards if they have proven income.
If your answer to this is that "you have no income, but still want a credit card", I would advise you to re-read that sentence several times and think carefully about it.
I have never had a credit card and never missed having one, except when trying to rent cars which was somewhat complex and annoying to do in the 2005-2010 time period without a credit card.
Credit cards have a number of disadvantages:
* They provide a temptation to waste money on luxury goods you do not
need
* The interest rates on credit cards are relatively high
* You greatly increase your chances for having your identity stolen
* All your purchases using the card are tracked and the information is
provided to various organizations and people around the world, many
of whom you would not want having your purchase information if you
knew who they were.
I definitely agree with those who will tell you credit cards are convenient, they are, but for someone who wants to be financially prudent and build wealth they are unnecessary and unwise.
If you don't believe me, read "The Total Money Makeover" by David Ramsey, one of the most famous and best-selling books ever written on personal finance. He actually will give you much better and detailed reasons to avoid CCs than me. After all, who am I, just some dumb rich schmuck with lots of money and no debt and a happy life.
**Comment on Culture**
I think it is pretty funny we have a lot of spendthrift Americans in this thread basically telling the OP to get lots of credit cards as soon as possible. If you asked the same question in Japan you would get completely different answers and votes. In Japan its hard to even use credit cards. The people there are much more responsible financially than Americans; the average Japanese person has much higher wealth than a person with the same income in the United States. One of the reasons for this, among many, is that the average Japanese person does not use credit cards. A Japanese person, if you translated this question for them, would think the whole thing a typical example of how foolish Americans are. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | The length of time you have established credit does improve your credit score in the long run.
As long as you can avoid paying interest, you might see if you can get a card with cash back rewards. I have one from Citi that sends me a $50 check every so often when I have enough rewards built up. | No, don't open a credit card. Get used to paying cash for everything from the beginning. The best situation you can be in is not to have any credit. When it comes time to buy a house, put down %30 percent and your 0 credit score won't matter.
This will keep you within your means, and, with governments gathering more and more data, help preserve your anonimity. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | Yes, it is a very good idea to start your credit history early. It sounds like you have a good understanding of the appropriate use of credit, as a substitute for cash rather than a supplement to income. As long as you keep your expenses under control and pay off your card each month, I see no problems with the idea.
Try to find a card with no annual fees, a low interest rate if possible (which will be difficult at your age), and with some form of rewards such as cash back. Look for a reputable issuing bank, and keep the account open even after you get a new card down the road. Your credit score is positively correlated with having an account open for a long time, having a good credit usage to credit limit ratio, and having accounts in good standing and paid on time. | >
> Assuming I only use it to buy things I can afford (which I trust
> myself to do), essentially treating it as a debit card, is this a good
> idea?
>
>
>
This is definitely a good idea.
From my own experience, before I got my first credit card through my local bank (age 18), I tired to apply for a card that has cash back rewards and was rejected because I didn't have any credit history. After I had the card from my bank for 6 months, I applied for [this Capital One](http://www.capitalone.com/credit-cards/quicksilver/) card that I've had ever since. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | I want to recommend an exercise:
Find all the people nearby who you can talk to in less than 24 hours about credit cards: Your family, whoever lives with you, and friends.
Now, ask each of them "what's the worst situation you've gotten yourself into with a credit card?"
Personally, the ratio of people who I asked who had credit cards to the ratio of people *with horror stories* about how credit cards screwed up their credit was **nearly 1:1**. Pretty much, only one of them had managed to avoid the trap that credit cards created (that sole exception had worked for the government at a high paying job and was now retired with adult children and a lucrative pension). Because it's trivially easy over-extend yourself, as a result of how credit cards work (if you had the cash at any second, you would have no need for the credit).
But do your own straw poll, and then see what the experience of people around you has been. And if there's a lot more bad than good out there, then ask yourself "am I somehow more fiscally responsible than all of these people?". | Definitely not. Credit cards only exist to suck you into the soulless corporate system. What you want to remember here is that you can't trust banks, so you'll want to convert all your savings into some durable asset, say, bitcoins for example, and then hoard them like Smaug until after the Fall. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | >
> Assuming I only use it to buy things I can afford (which I trust
> myself to do), essentially treating it as a debit card, is this a good
> idea?
>
>
>
This is definitely a good idea.
From my own experience, before I got my first credit card through my local bank (age 18), I tired to apply for a card that has cash back rewards and was rejected because I didn't have any credit history. After I had the card from my bank for 6 months, I applied for [this Capital One](http://www.capitalone.com/credit-cards/quicksilver/) card that I've had ever since. | Definitely not. Credit cards only exist to suck you into the soulless corporate system. What you want to remember here is that you can't trust banks, so you'll want to convert all your savings into some durable asset, say, bitcoins for example, and then hoard them like Smaug until after the Fall. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | The length of time you have established credit does improve your credit score in the long run.
As long as you can avoid paying interest, you might see if you can get a card with cash back rewards. I have one from Citi that sends me a $50 check every so often when I have enough rewards built up. | This is a good idea, but it will barely affect your credit score at all.
Credit cards, while a good tool to use for giving a minor boost to your credit score and for purchasing things while also building up rewards with those purchases, aren't very good for building credit.
This is because when banks calculate your credit report, they look at your *long-term* credit history, and weigh larger, longer-term debt much higher than short-term debt that you pay off right away. While having your credit card is better than nothing, it's a relatively small drop in the pond when it comes to credit.
I would still recommend getting a credit card though - it will, if you haven't already started paying off a debt like a student or car loan, give you a credit identity and rewards depending on the credit card you choose. But if you do, **do not ever let yourself fall into delinquency**. Failing to pay off loans will damage your credit score. So if you do plan to get a credit card, it is much better to do as you've said and pay it all off as soon as possible.
Edit:
In addition to the above, using a credit card has the added benefit of having greater security over Debit cards, and ensures that your own money won't be stolen (though you will still have to report a fraudulent charge). |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | I will disagree with the other answers. The idea that there is some to establish a "credit history" is largely a myth propagated by loaners who see it as positive propaganda to increase the numbers of their prospective customers.
You will find some people who claim they were rejected for a card because they had no "credit history," but in every case what these people are not telling you is they also had no income (were students, house wives, or others with no steady income). Anyone who has income can get a credit card or other line of credit regardless of their "credit history." Even people who have gone bankrupt can get credit cards if they have proven income.
If your answer to this is that "you have no income, but still want a credit card", I would advise you to re-read that sentence several times and think carefully about it.
I have never had a credit card and never missed having one, except when trying to rent cars which was somewhat complex and annoying to do in the 2005-2010 time period without a credit card.
Credit cards have a number of disadvantages:
* They provide a temptation to waste money on luxury goods you do not
need
* The interest rates on credit cards are relatively high
* You greatly increase your chances for having your identity stolen
* All your purchases using the card are tracked and the information is
provided to various organizations and people around the world, many
of whom you would not want having your purchase information if you
knew who they were.
I definitely agree with those who will tell you credit cards are convenient, they are, but for someone who wants to be financially prudent and build wealth they are unnecessary and unwise.
If you don't believe me, read "The Total Money Makeover" by David Ramsey, one of the most famous and best-selling books ever written on personal finance. He actually will give you much better and detailed reasons to avoid CCs than me. After all, who am I, just some dumb rich schmuck with lots of money and no debt and a happy life.
**Comment on Culture**
I think it is pretty funny we have a lot of spendthrift Americans in this thread basically telling the OP to get lots of credit cards as soon as possible. If you asked the same question in Japan you would get completely different answers and votes. In Japan its hard to even use credit cards. The people there are much more responsible financially than Americans; the average Japanese person has much higher wealth than a person with the same income in the United States. One of the reasons for this, among many, is that the average Japanese person does not use credit cards. A Japanese person, if you translated this question for them, would think the whole thing a typical example of how foolish Americans are. | Definitely not. Credit cards only exist to suck you into the soulless corporate system. What you want to remember here is that you can't trust banks, so you'll want to convert all your savings into some durable asset, say, bitcoins for example, and then hoard them like Smaug until after the Fall. |
48,490 | I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older?
Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have.
Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions | 2015/05/28 | [
"https://money.stackexchange.com/questions/48490",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/13558/"
] | Yes, it is a very good idea to start your credit history early. It sounds like you have a good understanding of the appropriate use of credit, as a substitute for cash rather than a supplement to income. As long as you keep your expenses under control and pay off your card each month, I see no problems with the idea.
Try to find a card with no annual fees, a low interest rate if possible (which will be difficult at your age), and with some form of rewards such as cash back. Look for a reputable issuing bank, and keep the account open even after you get a new card down the road. Your credit score is positively correlated with having an account open for a long time, having a good credit usage to credit limit ratio, and having accounts in good standing and paid on time. | I will disagree with the other answers. The idea that there is some to establish a "credit history" is largely a myth propagated by loaners who see it as positive propaganda to increase the numbers of their prospective customers.
You will find some people who claim they were rejected for a card because they had no "credit history," but in every case what these people are not telling you is they also had no income (were students, house wives, or others with no steady income). Anyone who has income can get a credit card or other line of credit regardless of their "credit history." Even people who have gone bankrupt can get credit cards if they have proven income.
If your answer to this is that "you have no income, but still want a credit card", I would advise you to re-read that sentence several times and think carefully about it.
I have never had a credit card and never missed having one, except when trying to rent cars which was somewhat complex and annoying to do in the 2005-2010 time period without a credit card.
Credit cards have a number of disadvantages:
* They provide a temptation to waste money on luxury goods you do not
need
* The interest rates on credit cards are relatively high
* You greatly increase your chances for having your identity stolen
* All your purchases using the card are tracked and the information is
provided to various organizations and people around the world, many
of whom you would not want having your purchase information if you
knew who they were.
I definitely agree with those who will tell you credit cards are convenient, they are, but for someone who wants to be financially prudent and build wealth they are unnecessary and unwise.
If you don't believe me, read "The Total Money Makeover" by David Ramsey, one of the most famous and best-selling books ever written on personal finance. He actually will give you much better and detailed reasons to avoid CCs than me. After all, who am I, just some dumb rich schmuck with lots of money and no debt and a happy life.
**Comment on Culture**
I think it is pretty funny we have a lot of spendthrift Americans in this thread basically telling the OP to get lots of credit cards as soon as possible. If you asked the same question in Japan you would get completely different answers and votes. In Japan its hard to even use credit cards. The people there are much more responsible financially than Americans; the average Japanese person has much higher wealth than a person with the same income in the United States. One of the reasons for this, among many, is that the average Japanese person does not use credit cards. A Japanese person, if you translated this question for them, would think the whole thing a typical example of how foolish Americans are. |
10,997,719 | I'm in the process of learning Databases and SQL. From what I have read adding an index to a table can increase performance to from around (log(n)) to even constant time.
Considering the increased space usage, at what point does it make sense to add an index to a table?
For example if i was using an employees table at how many records would the table have to have before you would add an index?
In this specific case would a clustered index make sense? | 2012/06/12 | [
"https://Stackoverflow.com/questions/10997719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1207026/"
] | Here are two examples that might help you think about this. These are not to be relied on as technically accurate (e.g. because of the effect of consecutive reads on the disk being more efficient than random seeks) but they are an illustration.
The first example is to think of a small table that is a couple of blocks in size. To find a particular row in the table, the database would read those two blocks and get the data you require.
If there were an index on that table, the index is likely to be smaller than the table. Maybe one block in size. If the optimiser chose to use this index then the database would read the one block index and then read the one block of the table containing the row you require.
As mentioned above this is only an example and is meant to model reality rather than be accurate. In reality, Oracle will often do a full table scan of a table with an index even if the index would return as little as 5% of the rows (or is it less now with 11G?).
The second example involves making data modifications on the table. Whenever a change to a row in a table is made (`INSERT`, `UPDATE`, `DELETE`, `MERGE`), every index on the table will need to be updated.
So, indexes may make queries faster and updates slower. And indexes take up space. That's the price you pay.
You ask "at how many records would the table have to have before you would add an index"? I think you are looking at it the wrong way because that shouldn't be for you to worry about. Add the index when the table has zero rows. The optimiser will work out the right thing to do. If it is quicker to use the index, it will use it. If it is quicker to avoid the index and do a full scan of the table then it will do that.
I would generally index columns that are used for the primary key and foreign keys plus any columns that are used frequently for access.
In general, I wouldn't worry too much about the space used by an index unless the tables are very large (in which case it might be worth looking at bitmap indexes). It is a trade off of space vs time but an index is going to be smaller than the table that is being indexed.
Another option if you are worried about space it to compress the index. This shouldn't have much impact on the performance but will take less space. Note that this is different to table compression.
This is a long way of giving the Tom Kyte answer of "It depends". The best thing you can probably do is benchmark your particular problem and go from there. You seem to be trying to do premature optimisation which is never a good thing. | My opinion is use index on columns you access frequently (like Primary Keys (this should be default), columns in Search criteria), you used in `WHERE` clause. It will speed up retrieval.
You should consider the fact that the table may grow in the future, putting indexes on it now prepare you for that. |
10,997,719 | I'm in the process of learning Databases and SQL. From what I have read adding an index to a table can increase performance to from around (log(n)) to even constant time.
Considering the increased space usage, at what point does it make sense to add an index to a table?
For example if i was using an employees table at how many records would the table have to have before you would add an index?
In this specific case would a clustered index make sense? | 2012/06/12 | [
"https://Stackoverflow.com/questions/10997719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1207026/"
] | Here are two examples that might help you think about this. These are not to be relied on as technically accurate (e.g. because of the effect of consecutive reads on the disk being more efficient than random seeks) but they are an illustration.
The first example is to think of a small table that is a couple of blocks in size. To find a particular row in the table, the database would read those two blocks and get the data you require.
If there were an index on that table, the index is likely to be smaller than the table. Maybe one block in size. If the optimiser chose to use this index then the database would read the one block index and then read the one block of the table containing the row you require.
As mentioned above this is only an example and is meant to model reality rather than be accurate. In reality, Oracle will often do a full table scan of a table with an index even if the index would return as little as 5% of the rows (or is it less now with 11G?).
The second example involves making data modifications on the table. Whenever a change to a row in a table is made (`INSERT`, `UPDATE`, `DELETE`, `MERGE`), every index on the table will need to be updated.
So, indexes may make queries faster and updates slower. And indexes take up space. That's the price you pay.
You ask "at how many records would the table have to have before you would add an index"? I think you are looking at it the wrong way because that shouldn't be for you to worry about. Add the index when the table has zero rows. The optimiser will work out the right thing to do. If it is quicker to use the index, it will use it. If it is quicker to avoid the index and do a full scan of the table then it will do that.
I would generally index columns that are used for the primary key and foreign keys plus any columns that are used frequently for access.
In general, I wouldn't worry too much about the space used by an index unless the tables are very large (in which case it might be worth looking at bitmap indexes). It is a trade off of space vs time but an index is going to be smaller than the table that is being indexed.
Another option if you are worried about space it to compress the index. This shouldn't have much impact on the performance but will take less space. Note that this is different to table compression.
This is a long way of giving the Tom Kyte answer of "It depends". The best thing you can probably do is benchmark your particular problem and go from there. You seem to be trying to do premature optimisation which is never a good thing. | In general every table should be indexed. In particular, every table should have a primary key, which will automatically create an index (most likely a clustered index).
However, even if you didn't create a primary key, even very small tables will benefit from indexing. |
26,455,856 | so this is my code
```
function func_readmsg () {
$targetmessage = $_POST['inquiry_no'];
$result = mysqli_query(mysqli_connect("localhost", "root", "", "dbbyahenijuan"),
"SELECT * FROM tblinquiry where finquiry_no='$targetmessage' ");
while($row = mysqli_fetch_array($result)) {
global $sender, $message, $date;
$sender = $row['ffull_name'];
$message = $row['fmessage'];
$date = $row['fdate'];
}
echo "
<script>
$(document).ready(function(){
$('#messagewindow').fadeIn('show');
});
</script>";
}
function func_delmsg () {
echo $targetmessage;
}
```
I need to transfer or read the value of `$targetmessage` from `func_readmsg` to `func_delmsg`.
I have already tried `$GLOBALS['targetmessage']`, `global $targetmessage`. Please help. | 2014/10/19 | [
"https://Stackoverflow.com/questions/26455856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159902/"
] | First, add a method to your class that determines if a String is numeric:
```
private boolean isNumeric(String number)
{
try
{
Integer.parseInt(number);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
```
The way this method works is that we attempt to parse the String as an int, and if that fails, because we are using a try/catch statement, we can prevent the program from throwing an error and instead just `return false;`. If it doesn't fail, it will continue on to the `return true;`
Now that we have a way of determining what is an isn't a number, we can rework the `while` loop to take advantage of the new method:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(lineCount == 1)
{
if(line.startsWith("case"))
{
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed: First, I added a new `int caseNumber` to represent the case number. Then I added a new `String contents` to represent the contents of the case. Next, I changed:
```
String line = scanner.nextLine();
```
to
```
String line = scanner.nextLine().trim();
```
and got rid of the other `String line1 = line.trim();` because there is no reason to create two new variables when we can do both operations on just one.
Next I added an if-statement to see if we are on the first line so we can determine the case number. If the line starts with `"case"` then we take the substring from `e` to `:`, represented as `subStr`, to get the case number. Run `subStr` through our `isNumeric` method, and we can determine if the case number can be parsed as an int. If that returns true, we set `caseNumber` equal to `Integer.parseInt(subStr)` which will turn the String into an int.
Then I added an else-statement to handle all the lines after the first line. For each of these lines, all we have to do is determine if the line is a number using `isNumeric`. If it is numeric, we append it to the end of `contents` using the `+=` operator. If it isn't, we skip over it.
Lastly, I made sure to **close the scanner** by executing `scanner.close()` so that we don't have a resource leak.
And there you go! I hope you can understand and learn from all the changes made. Here is the output of this program:
```
Case Number: 0
Case Contents: 000000100
Line Count: 19
```
---
To answer your follow-up question:
Here is the while loop that will allow you to print out multiple cases and their contents:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(line.startsWith("case"))
{
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed from the previous answer to make it work:
First I removed the if-statement that checks if the lineCount == 1, and attached the else-statement to the end of the second if-statement that checks if the line begins with "case".
So in other words, this:
```
if(lineCount == 1)
{
if(line.startsWith("case"))
{
...
}
}
else if(isNumeric(line))
...
```
Became this:
```
if(line.startsWith("case"))
{
...
}
else if(isNumeric(line))
...
```
Next, I added a new if-statement within the `if(line.startsWith("case"))` statement that checks if we are on a new case or not. Basically what it does is check if the `contents` string is empty. If it is, we are on case `0`. If it isn't, we are on a case greater than `0`. If the statement is true, we print out the case number and contents, then reset the values of the two variables so they can be used again:
```
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
```
And that's it! Really!
Here is the output:
```
Case Number: 0
Case Contents: 000000100
Case Number: 1
Case Contents: 101001001
Line Count: 38
```
Enjoy! | you can readfile line by line:
```
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
```
after you can check line string if it is numeric with a boolean function
```
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
```
OR you can read file and keep a counter for lines OR you can have a flag that change every time OR you can use str.contains(":"); while you reading the file and understand with this way that there is not a content you want.
this is one posible solution:
```
package test;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
*
* @author Alex
*/
public class encrypt {
public static boolean isNumeric(String str)
{
str.contains(str);
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String mycase="caseNumber :", case_cont="case content :";
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
if(line.contains("case"))
{
mycase=mycase+line.replace("case", "").replace(":", "");
}
else if(isNumeric(line)==true)
{
case_cont=case_cont+line.replaceAll("\\s+","");
}
}
System.out.println(mycase);
System.out.println(case_cont);
}
}
``` |
26,455,856 | so this is my code
```
function func_readmsg () {
$targetmessage = $_POST['inquiry_no'];
$result = mysqli_query(mysqli_connect("localhost", "root", "", "dbbyahenijuan"),
"SELECT * FROM tblinquiry where finquiry_no='$targetmessage' ");
while($row = mysqli_fetch_array($result)) {
global $sender, $message, $date;
$sender = $row['ffull_name'];
$message = $row['fmessage'];
$date = $row['fdate'];
}
echo "
<script>
$(document).ready(function(){
$('#messagewindow').fadeIn('show');
});
</script>";
}
function func_delmsg () {
echo $targetmessage;
}
```
I need to transfer or read the value of `$targetmessage` from `func_readmsg` to `func_delmsg`.
I have already tried `$GLOBALS['targetmessage']`, `global $targetmessage`. Please help. | 2014/10/19 | [
"https://Stackoverflow.com/questions/26455856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159902/"
] | First, add a method to your class that determines if a String is numeric:
```
private boolean isNumeric(String number)
{
try
{
Integer.parseInt(number);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
```
The way this method works is that we attempt to parse the String as an int, and if that fails, because we are using a try/catch statement, we can prevent the program from throwing an error and instead just `return false;`. If it doesn't fail, it will continue on to the `return true;`
Now that we have a way of determining what is an isn't a number, we can rework the `while` loop to take advantage of the new method:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(lineCount == 1)
{
if(line.startsWith("case"))
{
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed: First, I added a new `int caseNumber` to represent the case number. Then I added a new `String contents` to represent the contents of the case. Next, I changed:
```
String line = scanner.nextLine();
```
to
```
String line = scanner.nextLine().trim();
```
and got rid of the other `String line1 = line.trim();` because there is no reason to create two new variables when we can do both operations on just one.
Next I added an if-statement to see if we are on the first line so we can determine the case number. If the line starts with `"case"` then we take the substring from `e` to `:`, represented as `subStr`, to get the case number. Run `subStr` through our `isNumeric` method, and we can determine if the case number can be parsed as an int. If that returns true, we set `caseNumber` equal to `Integer.parseInt(subStr)` which will turn the String into an int.
Then I added an else-statement to handle all the lines after the first line. For each of these lines, all we have to do is determine if the line is a number using `isNumeric`. If it is numeric, we append it to the end of `contents` using the `+=` operator. If it isn't, we skip over it.
Lastly, I made sure to **close the scanner** by executing `scanner.close()` so that we don't have a resource leak.
And there you go! I hope you can understand and learn from all the changes made. Here is the output of this program:
```
Case Number: 0
Case Contents: 000000100
Line Count: 19
```
---
To answer your follow-up question:
Here is the while loop that will allow you to print out multiple cases and their contents:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(line.startsWith("case"))
{
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed from the previous answer to make it work:
First I removed the if-statement that checks if the lineCount == 1, and attached the else-statement to the end of the second if-statement that checks if the line begins with "case".
So in other words, this:
```
if(lineCount == 1)
{
if(line.startsWith("case"))
{
...
}
}
else if(isNumeric(line))
...
```
Became this:
```
if(line.startsWith("case"))
{
...
}
else if(isNumeric(line))
...
```
Next, I added a new if-statement within the `if(line.startsWith("case"))` statement that checks if we are on a new case or not. Basically what it does is check if the `contents` string is empty. If it is, we are on case `0`. If it isn't, we are on a case greater than `0`. If the statement is true, we print out the case number and contents, then reset the values of the two variables so they can be used again:
```
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
```
And that's it! Really!
Here is the output:
```
Case Number: 0
Case Contents: 000000100
Case Number: 1
Case Contents: 101001001
Line Count: 38
```
Enjoy! | Try this code
```
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileScanner {
File f = new File("test.txt");
public static void main(String[] args) {
FileScanner fs = new FileScanner();
fs.readfile();
}
public void readfile() {
try {
Scanner scanner = new Scanner(f);
StringBuilder builder = new StringBuilder();
List<String>strings = new ArrayList<String>();
StringTokenizer st ;
int lineCount = 0;
while (scanner.hasNextLine()) {
lineCount++;
String line = scanner.nextLine();
line = line.trim();
builder.append(line +" "); //better then String s+= line
}
scanner.close();
st = new StringTokenizer(builder.toString()," ");
builder = new StringBuilder();
while(st.hasMoreElements()){
String s = st.nextElement().toString();
if(s.contains("a")&&s.contains(":")&&!s.contains("case")){
continue;
}
else if(s.contains("case")){
builder.append(":"+s);
}
else{
builder.append(s);
}
}
st = new StringTokenizer(builder.toString(),":");
while(st.hasMoreElements()){
strings.add(st.nextElement().toString());
}
for(int i=0;i<strings.size()-1;i++){
if(strings.get(i).contains("case")){
System.out.println("Case Number: " + strings.get(i));
if(i+1 <strings.size()){
System.out.println("Case Contents: " + strings.get(i+1));
}
}
}
System.out.println("line count : " + lineCount);
} catch (FileNotFoundException e) {
}
}
}
``` |
26,455,856 | so this is my code
```
function func_readmsg () {
$targetmessage = $_POST['inquiry_no'];
$result = mysqli_query(mysqli_connect("localhost", "root", "", "dbbyahenijuan"),
"SELECT * FROM tblinquiry where finquiry_no='$targetmessage' ");
while($row = mysqli_fetch_array($result)) {
global $sender, $message, $date;
$sender = $row['ffull_name'];
$message = $row['fmessage'];
$date = $row['fdate'];
}
echo "
<script>
$(document).ready(function(){
$('#messagewindow').fadeIn('show');
});
</script>";
}
function func_delmsg () {
echo $targetmessage;
}
```
I need to transfer or read the value of `$targetmessage` from `func_readmsg` to `func_delmsg`.
I have already tried `$GLOBALS['targetmessage']`, `global $targetmessage`. Please help. | 2014/10/19 | [
"https://Stackoverflow.com/questions/26455856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159902/"
] | First, add a method to your class that determines if a String is numeric:
```
private boolean isNumeric(String number)
{
try
{
Integer.parseInt(number);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
```
The way this method works is that we attempt to parse the String as an int, and if that fails, because we are using a try/catch statement, we can prevent the program from throwing an error and instead just `return false;`. If it doesn't fail, it will continue on to the `return true;`
Now that we have a way of determining what is an isn't a number, we can rework the `while` loop to take advantage of the new method:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(lineCount == 1)
{
if(line.startsWith("case"))
{
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed: First, I added a new `int caseNumber` to represent the case number. Then I added a new `String contents` to represent the contents of the case. Next, I changed:
```
String line = scanner.nextLine();
```
to
```
String line = scanner.nextLine().trim();
```
and got rid of the other `String line1 = line.trim();` because there is no reason to create two new variables when we can do both operations on just one.
Next I added an if-statement to see if we are on the first line so we can determine the case number. If the line starts with `"case"` then we take the substring from `e` to `:`, represented as `subStr`, to get the case number. Run `subStr` through our `isNumeric` method, and we can determine if the case number can be parsed as an int. If that returns true, we set `caseNumber` equal to `Integer.parseInt(subStr)` which will turn the String into an int.
Then I added an else-statement to handle all the lines after the first line. For each of these lines, all we have to do is determine if the line is a number using `isNumeric`. If it is numeric, we append it to the end of `contents` using the `+=` operator. If it isn't, we skip over it.
Lastly, I made sure to **close the scanner** by executing `scanner.close()` so that we don't have a resource leak.
And there you go! I hope you can understand and learn from all the changes made. Here is the output of this program:
```
Case Number: 0
Case Contents: 000000100
Line Count: 19
```
---
To answer your follow-up question:
Here is the while loop that will allow you to print out multiple cases and their contents:
```
Scanner scanner = new Scanner(f);
int lineCount = 0;
int caseNumber = -1;
String contents = "";
while(scanner.hasNextLine())
{
lineCount++;
String line = scanner.nextLine().trim();
if(line.startsWith("case"))
{
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
String subStr = line.substring(line.indexOf("e") + 1,
line.indexOf(":"));
if(isNumeric(subStr))
caseNumber = Integer.parseInt(subStr);
}
else if(isNumeric(line))
contents += line;
}
scanner.close();
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
System.out.println("Line Count: " + lineCount);
```
Here is what I changed from the previous answer to make it work:
First I removed the if-statement that checks if the lineCount == 1, and attached the else-statement to the end of the second if-statement that checks if the line begins with "case".
So in other words, this:
```
if(lineCount == 1)
{
if(line.startsWith("case"))
{
...
}
}
else if(isNumeric(line))
...
```
Became this:
```
if(line.startsWith("case"))
{
...
}
else if(isNumeric(line))
...
```
Next, I added a new if-statement within the `if(line.startsWith("case"))` statement that checks if we are on a new case or not. Basically what it does is check if the `contents` string is empty. If it is, we are on case `0`. If it isn't, we are on a case greater than `0`. If the statement is true, we print out the case number and contents, then reset the values of the two variables so they can be used again:
```
if(!contents.isEmpty())
{
System.out.println("Case Number: " + caseNumber);
System.out.println("Case Contents: " + contents);
caseNumber = -1;
contents = "";
}
```
And that's it! Really!
Here is the output:
```
Case Number: 0
Case Contents: 000000100
Case Number: 1
Case Contents: 101001001
Line Count: 38
```
Enjoy! | I make some modification to let you choose what case do you want print
```
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileScanner {
File f = new File("test.txt");
List<String>cases = new ArrayList<String>();
List<String>contents = new ArrayList<String>();
List<String>strings = new ArrayList<String>();
public static void main(String[] args) {
FileScanner fs = new FileScanner();
fs.readfile();
for(int i = 0; i<fs.getCases().size();i++){
System.out.println("case number is : "+ fs.getCase(i));
System.out.println("case content is : "+fs.getContent(i) );
}
}
public void readfile() {
try {
Scanner scanner = new Scanner(f);
StringBuilder builder = new StringBuilder();
StringTokenizer st ;
int lineCount = 0;
while (scanner.hasNextLine()) {
lineCount++;
String line = scanner.nextLine();
line = line.trim();
builder.append(line +" "); //better then String s+= line
}
scanner.close();
st = new StringTokenizer(builder.toString()," ");
builder = new StringBuilder();
while(st.hasMoreElements()){
String s = st.nextElement().toString();
if(s.contains("a")&&s.contains(":")&&!s.contains("case")){
continue;
}
else if(s.contains("case")){
builder.append(":"+s);
}
else{
builder.append(s);
}
}
st = new StringTokenizer(builder.toString(),":");
while(st.hasMoreElements()){
strings.add(st.nextElement().toString());
}
for(int i=0;i<strings.size();i++){
if(strings.get(i).contains("case")){
cases.add(strings.get(i));
}
else{
contents.add(strings.get(i));
}
}
System.out.println("line count : " + lineCount);
} catch (FileNotFoundException e) {
}
}
public String getCase(int index) {
if(!cases.isEmpty() &&index <cases.size()){
return cases.get(index);
}
return "NaN";
}
public String getContent(int index) {
if(!contents.isEmpty() &&index <contents.size()){
return contents.get(index);
}
return "NaN";
}
public List<String> getCases() {
return cases;
}
public void setCases(List<String> cases) {
this.cases = cases;
}
public List<String> getContents() {
return contents;
}
public void setContents(List<String> contents) {
this.contents = contents;
}
}
``` |
20,778,839 | I'm trying to automate a click when visting a website. This is the HTML I'm looking at.
```
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
```
when I select the size, say for instance size 8, the class= tag turns to "box active" like so,
```
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box active">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
```
How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this,
```
<div class="add_to_cart">
<div class="add_to_cart_left">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
<img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img>
</div>
</div>
```
Is this the correct chunk of HTML I should be looking at for a simulation of a click? | 2013/12/26 | [
"https://Stackoverflow.com/questions/20778839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535164/"
] | The problem is the 9 patch itself: it's **malformed**.
The black line on the **left side** is simply WRONG (it "touches" the lens).
It should be a single pixel near the lower part, so that its prolongation doesn't touch the lens.
This is it

Note that the lens will be **up-right aligned**.
If you want it **centered**, you have to add another black pixel near the upper left border (but you have to replace some pixels near the upper lens frame, too).
Also not thet you don't need the horizontal part being that wide, you can make it **much narrower**, to save on the final patch size. | After using 9patch to create a photo, you can a image file which it's file extension is XX.9.png.
For example, search.9.png in drawable folder and you should use "android:background=@drawable/search" in xml. |
64,528 | I am planning to study abroad in Japan in two years through my college for a year at a Japanese speaking university. I also have goals/aspirations to one day work/live in Japan. Is it weird/acceptable to give myself a kanji name based off of meaning or sound of my current name? My name is Ruth which means "friend" and "beautiful" so I was thinking of 朋麗 (ともれい). Or, I could use kanji based off of my sound to have a name that means 'dragon state' or "state of the dragon" (I was also born in the year of the dragon so it may be fitting) but sounds like Ruth 竜州 (りゅうす). I know a closer approximation would be ルース, but I like the idea of my name meaning dragon if I were to go that route. I also have an idea for my surname, which means "gentle beauty" and I came to the kanji 泰美 (やすみ). So either 泰美竜州 or 泰美朋麗. Is it weird for foreigners to do this when they move to Japan or Study abroad in Japan? I know some people who came to study abroad in the US from China and Korea and they both took American names. Is the reverse true for in Japan? Can I do this if I'm expecting to work in Japan? Could I use this name on legal documents in Japan if I did choose to use a kanji name? I'm really curios about the whole prospect. | 2018/12/21 | [
"https://japanese.stackexchange.com/questions/64528",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/32328/"
] | Firstly, for legal documents you should always be writing your name as it appears on your passport. When documents ask for your name, age, etc. they're trying to confirm your identity. If you supply a false name then they won't be able to tell whether you're a real person or not.
As for the social part, I think it's up to the people who will be calling you what you want to be called. After you've made some friends at your new University, ask them if it's weird for you to take on a Japanese alias. I had one friend who came to work in Australia from Korea who had also worked / lived in Japan. He has unique Japanese, Korean and English names.
I hope you have a great trip! | I think it's more natural to write your name in English form as we're familiar with English, but I like your try.
The reasons we call ourselves in another name are
1: 70% we find it fancy
2: 30% some people are difficult to be called with the original one like りゅ りょ sounds |
106,380 | What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers)
The web server will only host files, with no need for cookies, reading a database, etc. The requirements are;
1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as.
2. Stream FLVs, MP3, OGG, MP4
3. Allow file transfer resuming
I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case?
A plus would be if it could also serve thumbnails well but that may not be an issue. | 2010/01/26 | [
"https://serverfault.com/questions/106380",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | I would recommend looking into Puppet/Facter or OCS Inventory NG.
Puppet
------
Puppet (which uses Facter), can be used to push out updates and configure nodes. It retrives information (or facts) about your nodes via Facter. Even though Puppet (via Facter) doesn't know who the primary user is, you can add facts (information) to your nodes that Facter will pick up on, and report back to the central server. It also includes a powerful Domain Specific Language written using Ruby, but very easy to learn even if you have no ruby experience. They have a great user group if you have any questions and are currently working on additional external software like Puppet Dashboard to make it easier to manage your infrastructure.
One downside of Puppet is that it only works on Linux machines currently. This can be a non-issue if you are only concerned with Linux machines.
Website: <http://docs.reductivelabs.com/>
OCS Invetory NG
---------------
OCS Invetory NG also does updates and can gather a lot of information off nodes. It is easy to use. The central server interface is accessed via a browser. From this interface you can see view your nodes, and get reports that contain detailed information on the hardware and software installed. This product works for both Linux and Windows environments.
Website: <http://www.ocsinventory-ng.org/>
Summary
-------
Both products have a client/server architecture in which you have to install client software on each node for information to be polled and updates to be pushed out. Each product is open source, so licensing is not an issue.
Puppet is a very powerful tool. With its own DSL, you can for the most part do anything you need. It is scalable and has been used by many big companies such as Google and Redhat.
OCS Inventory NG is an easy to use tool that works both on Windows and Linux environments. It is accessed through a web interface in which you can have printable reports.
If you have a mixed infrastructure (Windows and Linux) you may want to go with OCS, but if you are using solely Linux machines, Puppet is the best tool out their to manage your infrastructure. | Have you looked at www.spiceworks.com software? I'm in a Microsoft environment, so I don't know if it will also perform on Linux clients, but it does a good job of inventorying both hardware and software. It's also free. Microsoft System Center is also very helpful. |
106,380 | What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers)
The web server will only host files, with no need for cookies, reading a database, etc. The requirements are;
1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as.
2. Stream FLVs, MP3, OGG, MP4
3. Allow file transfer resuming
I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case?
A plus would be if it could also serve thumbnails well but that may not be an issue. | 2010/01/26 | [
"https://serverfault.com/questions/106380",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | Have you looked at www.spiceworks.com software? I'm in a Microsoft environment, so I don't know if it will also perform on Linux clients, but it does a good job of inventorying both hardware and software. It's also free. Microsoft System Center is also very helpful. | JDisc Discovery creates an inventory for Windows and many Unix operating systems (including Linux).
<http://www.jdisc.com> |
106,380 | What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers)
The web server will only host files, with no need for cookies, reading a database, etc. The requirements are;
1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as.
2. Stream FLVs, MP3, OGG, MP4
3. Allow file transfer resuming
I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case?
A plus would be if it could also serve thumbnails well but that may not be an issue. | 2010/01/26 | [
"https://serverfault.com/questions/106380",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | I would recommend looking into Puppet/Facter or OCS Inventory NG.
Puppet
------
Puppet (which uses Facter), can be used to push out updates and configure nodes. It retrives information (or facts) about your nodes via Facter. Even though Puppet (via Facter) doesn't know who the primary user is, you can add facts (information) to your nodes that Facter will pick up on, and report back to the central server. It also includes a powerful Domain Specific Language written using Ruby, but very easy to learn even if you have no ruby experience. They have a great user group if you have any questions and are currently working on additional external software like Puppet Dashboard to make it easier to manage your infrastructure.
One downside of Puppet is that it only works on Linux machines currently. This can be a non-issue if you are only concerned with Linux machines.
Website: <http://docs.reductivelabs.com/>
OCS Invetory NG
---------------
OCS Invetory NG also does updates and can gather a lot of information off nodes. It is easy to use. The central server interface is accessed via a browser. From this interface you can see view your nodes, and get reports that contain detailed information on the hardware and software installed. This product works for both Linux and Windows environments.
Website: <http://www.ocsinventory-ng.org/>
Summary
-------
Both products have a client/server architecture in which you have to install client software on each node for information to be polled and updates to be pushed out. Each product is open source, so licensing is not an issue.
Puppet is a very powerful tool. With its own DSL, you can for the most part do anything you need. It is scalable and has been used by many big companies such as Google and Redhat.
OCS Inventory NG is an easy to use tool that works both on Windows and Linux environments. It is accessed through a web interface in which you can have printable reports.
If you have a mixed infrastructure (Windows and Linux) you may want to go with OCS, but if you are using solely Linux machines, Puppet is the best tool out their to manage your infrastructure. | Your likely not looking for split solutions BUT for the Microsoft Licenses I like to stay with the tool that they will use should you get audited and that is a version of MSIA. Microsoft Software Inventory Analyzer, <http://www.microsoft.com/sam/en/us/msia.aspx>
It however only audits Microsoft apps, but it can be referenced via another Excel spreadsheet. |
106,380 | What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers)
The web server will only host files, with no need for cookies, reading a database, etc. The requirements are;
1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as.
2. Stream FLVs, MP3, OGG, MP4
3. Allow file transfer resuming
I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case?
A plus would be if it could also serve thumbnails well but that may not be an issue. | 2010/01/26 | [
"https://serverfault.com/questions/106380",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | I would recommend looking into Puppet/Facter or OCS Inventory NG.
Puppet
------
Puppet (which uses Facter), can be used to push out updates and configure nodes. It retrives information (or facts) about your nodes via Facter. Even though Puppet (via Facter) doesn't know who the primary user is, you can add facts (information) to your nodes that Facter will pick up on, and report back to the central server. It also includes a powerful Domain Specific Language written using Ruby, but very easy to learn even if you have no ruby experience. They have a great user group if you have any questions and are currently working on additional external software like Puppet Dashboard to make it easier to manage your infrastructure.
One downside of Puppet is that it only works on Linux machines currently. This can be a non-issue if you are only concerned with Linux machines.
Website: <http://docs.reductivelabs.com/>
OCS Invetory NG
---------------
OCS Invetory NG also does updates and can gather a lot of information off nodes. It is easy to use. The central server interface is accessed via a browser. From this interface you can see view your nodes, and get reports that contain detailed information on the hardware and software installed. This product works for both Linux and Windows environments.
Website: <http://www.ocsinventory-ng.org/>
Summary
-------
Both products have a client/server architecture in which you have to install client software on each node for information to be polled and updates to be pushed out. Each product is open source, so licensing is not an issue.
Puppet is a very powerful tool. With its own DSL, you can for the most part do anything you need. It is scalable and has been used by many big companies such as Google and Redhat.
OCS Inventory NG is an easy to use tool that works both on Windows and Linux environments. It is accessed through a web interface in which you can have printable reports.
If you have a mixed infrastructure (Windows and Linux) you may want to go with OCS, but if you are using solely Linux machines, Puppet is the best tool out their to manage your infrastructure. | JDisc Discovery creates an inventory for Windows and many Unix operating systems (including Linux).
<http://www.jdisc.com> |
106,380 | What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers)
The web server will only host files, with no need for cookies, reading a database, etc. The requirements are;
1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as.
2. Stream FLVs, MP3, OGG, MP4
3. Allow file transfer resuming
I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case?
A plus would be if it could also serve thumbnails well but that may not be an issue. | 2010/01/26 | [
"https://serverfault.com/questions/106380",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | Your likely not looking for split solutions BUT for the Microsoft Licenses I like to stay with the tool that they will use should you get audited and that is a version of MSIA. Microsoft Software Inventory Analyzer, <http://www.microsoft.com/sam/en/us/msia.aspx>
It however only audits Microsoft apps, but it can be referenced via another Excel spreadsheet. | JDisc Discovery creates an inventory for Windows and many Unix operating systems (including Linux).
<http://www.jdisc.com> |
26,126,363 | I am trying to call a web service of a shipping company in my php code and get the result xml. I have this sample code and i want to know if there is an alternative using curl.
Code:
```
function doPost($_postContent) {
$postContent = "xml_in=".$_postContent;
$host="test.company.com";
$contentLen = strlen($postContent);
$httpHeader ="POST /shippergate2.asp HTTP/1.1\r\n"
."Host: $host\r\n"
."User-Agent: PHP Script\r\n"
."Content-Type: application/x-www-form-urlencoded\r\n"
."Content-Length: $contentLen\r\n"
."Connection: close\r\n"
."\r\n";
$httpHeader.=$postContent;
$fp = fsockopen($host, 81);
fputs($fp, $httpHeader);
$result = "";
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
$result = explode("\r\n\r\n", $result,3);
}
```
Can i call it using curl? | 2014/09/30 | [
"https://Stackoverflow.com/questions/26126363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1059261/"
] | You can use the `CURLOPT_PORT` option to change the port to 81. See <http://php.net/manual/en/function.curl-setopt.php>
```
$url = "http://test.company.com/shippergate2.asp";
$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, 81);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "PHP Script");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postContent);
$data = curl_exec($ch);
``` | I guess a complete solution is needed but I suggest checking this basic CURL wrapper for PHP <https://github.com/shuber/curl> |
52,349,928 | How could I create a conditional statement that prevents entering the fail state, and asks the user for new data when either the data is invalid or the data is not 1, 2, 3 OR 4 ?
```
int choice;
while ( !choice || choice != 1 || 2 || 3 || 4){
cout << "Entry Invalid. Enter again: ";
cin >> choice
}
```
For example, If the user enters 'f', then the fail state would be taken care of, and the program would ask for new data. And when they enter 5, the program would say "Not a valid number", and ask for new data. | 2018/09/16 | [
"https://Stackoverflow.com/questions/52349928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9183124/"
] | Let's suppose your input `011R0` is stored in array `buf` then to print ASCII value of each character, you'll have to access each character and print it as if you are printing an integer:
```
int i;
while(buf[i])
{
printf("%d\n",buf[i]);
++i;
}
```
By using indices `[i]` one can access each character if the string. Besides that have a look at this: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) | *I thought printing out %c would give me the ASCII value ?* **No**, the format specifier `%c` prints equivalents `char` value, since `buf4`, `buf5`..etc are char array, so when you prints `*buf5` it prints first char of array & if you print `ascii` value of that, you have to subtract it from `48`(ASCII value of 0) if `*buf` contains digits(0 - 9). For e.g
```
printf("%d\n",(*buf4) - 48);
```
Or
```
printf("%d\n",(*buf4) - '0');
```
Also for this particular case its wstage of stack memory to declare five char array like `buf3`,`buf4`..`buf9`. you can use just one char array & do the operation. For e.g
```
int index = 0 ;
char buf[20]; /* lets say each word of file are length of 20 char, you can change it */
while (fscanf(fp,"%s",buf) != EOF) {
while(buf[index] != '\0') {
if(buf[index] >= '0' && buf[index] <= '9') { /*or use isdigit() */
printf("%d",buf[index] - 48);
}
else { /* apart from 0,1,...9 */
printf("%d",buf[index]);
}
index++;
}
printf(" ");
index = 0;
}
```
Also read why its wrong to use `feof()` [here](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) |
990,285 | $e^x$$(1+e^x)^{1\over{2}}$
why can't use integration by part,
What is meant by in the form of f(g(x))g'(x)?
Can you give a few example?
Thank you | 2014/10/25 | [
"https://math.stackexchange.com/questions/990285",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/173339/"
] | Integration by substitution says that
$$
\int f(g(x))g'(x) \; dx = \int f(u)\;du
$$
where $u = g(x)$. This is a tool that will let you compute the integral of all functions that look exactly like $f(g(x))g'(x)$. When you first see this, you might be thinking that this seems like a very specialised rule that only seem good for very special cases. But it turns out that this is very useful.
In your example, you have
$$
\int (1 + e^x)^{1/2}e^x\; dx.
$$
If you want to know whether or not you can use substitution you just have to determine if it is possible to write $(1 + e^x)^{1/2}e^x$ as $f(g(x))g'(x)$ for some functions $f$ and $g$. Mabe by trail and error you find that indeed if $f(x) = x^{1/2}$ and $g(x) = 1+e^x$, then $f(g(x))g'(x) = (1 + e^x)^{1/2}e^x$. And so with $u = g(x) = 1+e^x$, you get
$$
\int (1 + e^x)^{1/2}e^x\; dx = \int u^{1/2} \; du = \frac{2}{3}u^{3/2} + C = \frac{2}{3}(1+e^x)^{3/2} + C.
$$
---
You ask why you you can't use integration by parts. Integration by parts says that
$$
\int f(x)g'(x)\; dx = f(x)g(x) - \int f'(x)g(x)\; dx.
$$
So you would have to find $f$ and $g$ such that $f(x)g'(x) = e^x(1+e^e)^{1/2}$. You can of course choose $f(x) = (1 + e^x)^{1/2}$ and $g(x) = e^x$, so then you get
$$
(1 + e^x)^{1/2}e^x - \int \frac{1}{2}(1+e^x)^{1/2}e^xe^x\;dx.
$$
This is perfectly fine, but it doesn't do you any good. You wanted to find one complicated integral and now you just have another complicated integral. So you *can* use integration by parts, but, again, it doesn't help you much. It would be a good exercise to try other choices of $f$ and $g$ to convince yourself that this indeed doesn't help much. | in your example i would set $t=\sqrt{1+e^{x}}$ then we get $t^2=1+e^{x}$ and we have $2tdt=e^xdx$ thus your integral is $2\int t^2dt$ |
990,285 | $e^x$$(1+e^x)^{1\over{2}}$
why can't use integration by part,
What is meant by in the form of f(g(x))g'(x)?
Can you give a few example?
Thank you | 2014/10/25 | [
"https://math.stackexchange.com/questions/990285",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/173339/"
] | Integration by substitution says that
$$
\int f(g(x))g'(x) \; dx = \int f(u)\;du
$$
where $u = g(x)$. This is a tool that will let you compute the integral of all functions that look exactly like $f(g(x))g'(x)$. When you first see this, you might be thinking that this seems like a very specialised rule that only seem good for very special cases. But it turns out that this is very useful.
In your example, you have
$$
\int (1 + e^x)^{1/2}e^x\; dx.
$$
If you want to know whether or not you can use substitution you just have to determine if it is possible to write $(1 + e^x)^{1/2}e^x$ as $f(g(x))g'(x)$ for some functions $f$ and $g$. Mabe by trail and error you find that indeed if $f(x) = x^{1/2}$ and $g(x) = 1+e^x$, then $f(g(x))g'(x) = (1 + e^x)^{1/2}e^x$. And so with $u = g(x) = 1+e^x$, you get
$$
\int (1 + e^x)^{1/2}e^x\; dx = \int u^{1/2} \; du = \frac{2}{3}u^{3/2} + C = \frac{2}{3}(1+e^x)^{3/2} + C.
$$
---
You ask why you you can't use integration by parts. Integration by parts says that
$$
\int f(x)g'(x)\; dx = f(x)g(x) - \int f'(x)g(x)\; dx.
$$
So you would have to find $f$ and $g$ such that $f(x)g'(x) = e^x(1+e^e)^{1/2}$. You can of course choose $f(x) = (1 + e^x)^{1/2}$ and $g(x) = e^x$, so then you get
$$
(1 + e^x)^{1/2}e^x - \int \frac{1}{2}(1+e^x)^{1/2}e^xe^x\;dx.
$$
This is perfectly fine, but it doesn't do you any good. You wanted to find one complicated integral and now you just have another complicated integral. So you *can* use integration by parts, but, again, it doesn't help you much. It would be a good exercise to try other choices of $f$ and $g$ to convince yourself that this indeed doesn't help much. | $$\int (e^x+1)^{1/2}e^x\ dx=\int (1+\color{green}{e^x})^{1/2}\ d\color{green}{e^x}=\int(1+\color{green}{u})^{1/2}\ d\color{green}{u}=\frac23(1+u)^{3/2}=\frac23(1+e^x)^{3/2}.$$
Equivalenty,
$$\int (e^x+1)^{1/2}e^x\ dx=\int (\color{green}{1+e^x})^{1/2}\ d(\color{green}{1+e^x})=\int \color{green}{u}^{1/2}\ d\color{green}{u}=\frac23u^{3/2}=\frac23(1+e^x)^{3/2}.$$
Note that $dg(x)$ is the same as $g'(x)\ dx$. |
29,390,701 | I am working in codeigniter. My problem is i want to show all rows having same id. But when i perform group\_by it only outputs one row of that group.
below is my model
```
function category_content(){
$this->db->select('*');
$this->db->from('category');
$this->db->group_by('category_id');
$query = $this->db->get();
return $query->result_array();
}
```
Please help. | 2015/04/01 | [
"https://Stackoverflow.com/questions/29390701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717813/"
] | As per the sql properties `Group By` groups all the matching records and will show you only one. It seems you want to sort them by id. Then its better to use `order by` | See the Example hope you will get to know this..
```
tableA
_____
id name marks
-- ---- ---
1 x 25
2 y 27
1 z 30
SELECT * FROM tableA group by id
OUTPUT:
1 x 25
2 y 27
```
in your case you should use WHERE clause.
```
SELECT * FROM tableA WHERE id=1
OUTPUT:
1 x 25
1 z 30
function category_content(){
$this->db->select('*');
$this->db->from('category');
$this->db->where($category_id);
$query = $this->db->get();
return $query->result_array();
}
```
[https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html](http://Group%20By%20:%20MYSQL) |
4,124,091 | I use Visual Studio 2008 Professional with .NET 3.5 SP1 installed. It is not showing Entity Model when I select "New Project". The MSDN links show that it was included with .NET 3.5 SP1.
Why it is not appearing on my VS 2008? | 2010/11/08 | [
"https://Stackoverflow.com/questions/4124091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194328/"
] | You probably need to install *VS2008* SP1, which contains the tooling used to develop against .Net 3.5 SP1. | It won't appear as new project. It will appear as *ADO.NET Entity Data Model* when you add a new item to an existing project:
 |
73,033,294 | I', trying to run this functin only on mobile devices which is less than 768px , it works on this screen width but it also ignore the condition and works on larger screens than 768px, i tried to clear interval but there is something wrong with my code
```js
$(document).ready(function () {
$(window).on("resize", function (e) {
checkScreenSize();
clearInterval(intervalId)
});
checkScreenSize();
function checkScreenSize() {
var newWindowWidth = $(window).width();
if (newWindowWidth < 768) {
const divs = [...document.querySelectorAll(".tagline2")];
divs.i = 0;
intervalId = setInterval(function () {
divs[divs.i++].classList.remove("move");
divs[divs.i = divs.i % divs.length].classList.add("move")
}, 3000);
}
}
});
```
```css
.move {background-color:red}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="infobarContainer">
<div class="tagline tagline2 move">
USP 1
</div>
<div class="tagline tagline2">
USP 2
</div>
<div class="tagline tagline2">
USP 3
</div>
<div class="tagline tagline2">
USP 4
</div>
</div>
``` | 2022/07/19 | [
"https://Stackoverflow.com/questions/73033294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19351845/"
] | If you want to use it later you create it in a macro variable and reference it later with a &variableName
Let's assume:
* data set name is myDataset
* variable name is value
* Single observation/row in the data set
* Macro variable output name is myValue
```
*create fake data;
data myDataset;
date = mdy(7, 18, 2022);
format date ddmmyyn8.;
value = 15;
output;
run;
```
```
data _null_; *_null_ means SAS will not create a data set as output;
set myDataset; *indicate the input data set;
call symputx('myValue', value, 'g'); *create the variable with a global scope;
run;
```
Then to use it later, say filter all people under the age of myValue.
```
data below15;
set sashelp.class;
where age <= &myValue;
run;
```
Here is more references on Macro variables.
<https://stats.oarc.ucla.edu/sas/seminars/sas-macros-introduction/>
Generally speaking though, avoiding macros at the beginning is recommended. You should code without macros as much as possible. There are often other ways of doing things. | SAS does not have any "global variables". All variables live in datasets. If you want to use a value from the first observation of one dataset in a data step that is using some other dataset as its main input then just read it in once at the start of the data step and its value will stay the same for the whole data step.
To change the variable's name from column\_name to last\_dat\_value you can use the RENAME= dataset option.
```
data want;
if _n_=1 then
set RWORK.dataset(keep=column_name rename=(column_name=last_dat_value) obs=1)
;
set have;
days_till_last = last_dat_value - date ;
run;
``` |
4,118,439 | In problem 33 iv Chapter 5 of Spivak's *Calculus*, there is a comment in the solution manual that (in essence) remarks $\lim\_{x \to \infty} \sin x$ **does not exist**.
I wanted to see if I could prove this statement by negating the formal definition of $\lim\_{x \to \infty}f(x)=L \iff \exists L \in \mathbb R \Big [ \forall \epsilon \gt 0 \ \exists N \in \mathbb R \text { s.t. } \forall x \in \mathbb R \big ( x \gt N \rightarrow \lvert f(x) - L \rvert \lt \epsilon \big ) \Big ]$
i.e. I wanted to write a proof that:
>
> $\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$
>
>
>
I'll write what I have so far and highlight the missing piece that I am finding difficult to navigate around. As an "FYI" for those unfamiliar with Spivak's *Calculus*, the subject of Continuous Functions is not found until chapter 6, and I suspect that my issue arises from trig functions being more..."tackle-able"...once continuity is rigorously defined.
---
Relevant Lemma: $\lvert \sin(x) \rvert \leq 1 \quad$ (I do not believe this statement, in and of itself, requires knowledge of continuous functions)
Consider two cases: $\lvert L \rvert \gt 1$ or $\lvert L \rvert \leq 1$.
---
**Case 1**: Note that $\lvert L \rvert \gt 1 \implies \frac{\lvert L \rvert -1}{2}\gt 0$
Let $0 \lt\epsilon \lt \frac{\lvert L \rvert -1}{2}$ . Therefore $-\epsilon \gt \frac{1-\lvert L \rvert}{2}$. From which it follows:
$$ \lvert L \rvert - \epsilon \gt \frac{2 \lvert L \rvert +1 - \lvert L \rvert}{2}=\frac{\lvert L \rvert +1}{2}\gt 1$$
By our lemma, we then have:
$$\lvert L\rvert - \epsilon \gt 1 \geq \lvert \sin(x) \rvert$$.
Rearranging:
$$ \lvert L \rvert \gt 1 + \epsilon \geq \lvert \sin(x) \rvert + \epsilon$$
$$ \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Invoking one of the triangle inequality variants, we finally have:
$$ \lvert \sin(x) - L \rvert = \lvert L - \sin(x) \rvert \geq \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Note that $\forall x \in \mathbb R$, the above statement is true. Therefore, any $N \in \mathbb R$ can be chosen and one can always find an $x \gt N$, for which the desired criteria is met.
---
**Case 2**: $\lvert L \rvert \leq 1$
Consider an $\epsilon \lt \frac{1}{2}$. For example, $\epsilon = \frac{1}{4}$
Here is where I am basically stumped in the absence of knowing anything about continuous functions. My hunch is that because $\lvert L \rvert \leq 1$, I can effectively assert that $\exists c \in \mathbb R \big [ \sin(c) = L \big ]$.
Now, invoking the same triangle inequality variant as before, we know that:
$$ \lvert \sin(c) - \sin(x) \rvert \geq \lvert \sin(c) \rvert - \lvert \sin(x) \rvert $$
So if I can show that: $\exists x \in \mathbb R \big [\lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \big ]$, we are good to go. Once again, I assume that I need some notion of continuous functions in order to prove this.
More generally, in order to apply this argument to any $N \in \mathbb R$, I would like to prove the slightly more refined:
$$ \exists x \in [c - \pi, c + \pi] \text{ s.t. } \Big ( \lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \Big )$$
(noting the $c$ value that produces $\sin(c)=L$ can be replaced by $c+2\pi n$ for any any integer $n$).
If there is a method to circumvent continuous functions, I would greatly appreciate the insight!
Thank you! | 2021/04/27 | [
"https://math.stackexchange.com/questions/4118439",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/544640/"
] | No knowledge of continuity is needed for this result. Suppose towards contradiction that $\lim\_{x \to \infty} \sin(x) = L$. Then let $\epsilon = \frac{1}{4}$ and let $N$ be such that $x > N$ implies $|\sin(x) - L| < \frac{1}{4}.$
Choose integers $k, m > N$. Then clearly $2πk > N$ and $2πm + \frac{π}{2} > N$. But observe that:
\begin{align\*}
|\sin(2πk) - L| &= |0 - L| = L < \frac1{4} \\
|\sin(2πm + \frac{π}{2}) - L| &= |1 - L| < \frac{1}4 \\
\end{align\*}
Which is impossible, since $|1 - L| < \frac{1}{4} \implies L > \frac{3}{4}.$ | Note that since $\sin(x)$ is periodic for every real $N$ there exists a real $x>N$ and $y>N$ such that $\sin(x)=1$ and $\sin(y)=-1$
From here it’s easy to see that this implies if the limit exists then it must be $1$ since if it’s any other value $m$ then you can let $\epsilon$ be less than $|1-m|$ to obtain a contradiction .
But the above argument also works for $-1$ a contradiction hence the limit does not exist . |
4,118,439 | In problem 33 iv Chapter 5 of Spivak's *Calculus*, there is a comment in the solution manual that (in essence) remarks $\lim\_{x \to \infty} \sin x$ **does not exist**.
I wanted to see if I could prove this statement by negating the formal definition of $\lim\_{x \to \infty}f(x)=L \iff \exists L \in \mathbb R \Big [ \forall \epsilon \gt 0 \ \exists N \in \mathbb R \text { s.t. } \forall x \in \mathbb R \big ( x \gt N \rightarrow \lvert f(x) - L \rvert \lt \epsilon \big ) \Big ]$
i.e. I wanted to write a proof that:
>
> $\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$
>
>
>
I'll write what I have so far and highlight the missing piece that I am finding difficult to navigate around. As an "FYI" for those unfamiliar with Spivak's *Calculus*, the subject of Continuous Functions is not found until chapter 6, and I suspect that my issue arises from trig functions being more..."tackle-able"...once continuity is rigorously defined.
---
Relevant Lemma: $\lvert \sin(x) \rvert \leq 1 \quad$ (I do not believe this statement, in and of itself, requires knowledge of continuous functions)
Consider two cases: $\lvert L \rvert \gt 1$ or $\lvert L \rvert \leq 1$.
---
**Case 1**: Note that $\lvert L \rvert \gt 1 \implies \frac{\lvert L \rvert -1}{2}\gt 0$
Let $0 \lt\epsilon \lt \frac{\lvert L \rvert -1}{2}$ . Therefore $-\epsilon \gt \frac{1-\lvert L \rvert}{2}$. From which it follows:
$$ \lvert L \rvert - \epsilon \gt \frac{2 \lvert L \rvert +1 - \lvert L \rvert}{2}=\frac{\lvert L \rvert +1}{2}\gt 1$$
By our lemma, we then have:
$$\lvert L\rvert - \epsilon \gt 1 \geq \lvert \sin(x) \rvert$$.
Rearranging:
$$ \lvert L \rvert \gt 1 + \epsilon \geq \lvert \sin(x) \rvert + \epsilon$$
$$ \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Invoking one of the triangle inequality variants, we finally have:
$$ \lvert \sin(x) - L \rvert = \lvert L - \sin(x) \rvert \geq \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Note that $\forall x \in \mathbb R$, the above statement is true. Therefore, any $N \in \mathbb R$ can be chosen and one can always find an $x \gt N$, for which the desired criteria is met.
---
**Case 2**: $\lvert L \rvert \leq 1$
Consider an $\epsilon \lt \frac{1}{2}$. For example, $\epsilon = \frac{1}{4}$
Here is where I am basically stumped in the absence of knowing anything about continuous functions. My hunch is that because $\lvert L \rvert \leq 1$, I can effectively assert that $\exists c \in \mathbb R \big [ \sin(c) = L \big ]$.
Now, invoking the same triangle inequality variant as before, we know that:
$$ \lvert \sin(c) - \sin(x) \rvert \geq \lvert \sin(c) \rvert - \lvert \sin(x) \rvert $$
So if I can show that: $\exists x \in \mathbb R \big [\lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \big ]$, we are good to go. Once again, I assume that I need some notion of continuous functions in order to prove this.
More generally, in order to apply this argument to any $N \in \mathbb R$, I would like to prove the slightly more refined:
$$ \exists x \in [c - \pi, c + \pi] \text{ s.t. } \Big ( \lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \Big )$$
(noting the $c$ value that produces $\sin(c)=L$ can be replaced by $c+2\pi n$ for any any integer $n$).
If there is a method to circumvent continuous functions, I would greatly appreciate the insight!
Thank you! | 2021/04/27 | [
"https://math.stackexchange.com/questions/4118439",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/544640/"
] | >
> i.e. I wanted to write a proof that:
>
>
> $$\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$$
>
>
>
We can do this using $\varepsilon = \frac{1}{2}$.
**Case 1:** $L > 0$
Here for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
For such $x$ we have
$$\sin x = -1.$$
Since $L > 0$ we have
\begin{align}
|\sin x - L|&= |-1 - L| \\
& = 1 + L \\
& > \frac{1}{2}
\end{align}
**Case 2** $L < 0$
This case is nearly identical to the case for $L > 0$.
For any $N$ we can always find $x > N$ of the form $x = \frac{\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
For such $x$ we have
$$\sin x = 1.$$
Since $L < 0$ we have
\begin{align}
|\sin x - L|&= |1 - L| \\
& = 1 + |L| \\
& > \frac{1}{2}
\end{align}
**Case 3** $L = 0$
This case can be dealt with immediately by re-using either of the $x$ from the previous two cases:
If $x = \frac{\pi}{2} + 2k\pi$, then
\begin{align}
|\sin x - L|&= |1 - 0| \\
& = 1 \\
& > \frac{1}{2}
\end{align}
Of course, this all depends on knowing the behavior of $\sin$: that $\sin$ wavers between $1$ and $-1$ "forever" and so on. Given this behavior, one would expect intuitively that the limit doesn't exist, i.e. $\sin x$ wouldn't "settle" upon some single value for large $x$.
Later in the book Spivak defines the trigonometric functions formally in a way that conforms with the geometric/unit circle versions with which you are probably already familiar. Continuity plays a big part in these later definitions.
Here though, the main thing is just the periodic nature of $\sin$.
Finally, you may be somewhat leery of statements like:
>
> ...for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
>
>
>
This has at its heart the idea that given any real number $N$ we can find a natural number $n$ with $n > N$. *This* fact is employed in a few places early on in the text, but isn't formally proven until Chapter 8 (3rd Ed.) "Least Upper Bounds".
Spivak cops to this "cheating" at the end of that chapter.
(As an aside, an earlier problem in Chapter 5, 5-12 gives a very useful result:
If $f(x) \leq g(x)$ for all $x$ (or even just for all $x$ in a neighborhood of $a$) then $\lim\_{x\to a} f(x) \leq \lim\_{x\to a} g(x)$, provided these limits exist.
This can be shown to hold if we replace $a$ with $\infty$.
This, combined with your lemma that $|\sin x| \leq 1$ can be used to rule out your Case 1, i.e. since $-1 \leq \sin x \leq 1$ we must also have $-1 \leq \lim\_{x \to \infty}\sin x \leq 1$, if that limit exists.) | No knowledge of continuity is needed for this result. Suppose towards contradiction that $\lim\_{x \to \infty} \sin(x) = L$. Then let $\epsilon = \frac{1}{4}$ and let $N$ be such that $x > N$ implies $|\sin(x) - L| < \frac{1}{4}.$
Choose integers $k, m > N$. Then clearly $2πk > N$ and $2πm + \frac{π}{2} > N$. But observe that:
\begin{align\*}
|\sin(2πk) - L| &= |0 - L| = L < \frac1{4} \\
|\sin(2πm + \frac{π}{2}) - L| &= |1 - L| < \frac{1}4 \\
\end{align\*}
Which is impossible, since $|1 - L| < \frac{1}{4} \implies L > \frac{3}{4}.$ |
4,118,439 | In problem 33 iv Chapter 5 of Spivak's *Calculus*, there is a comment in the solution manual that (in essence) remarks $\lim\_{x \to \infty} \sin x$ **does not exist**.
I wanted to see if I could prove this statement by negating the formal definition of $\lim\_{x \to \infty}f(x)=L \iff \exists L \in \mathbb R \Big [ \forall \epsilon \gt 0 \ \exists N \in \mathbb R \text { s.t. } \forall x \in \mathbb R \big ( x \gt N \rightarrow \lvert f(x) - L \rvert \lt \epsilon \big ) \Big ]$
i.e. I wanted to write a proof that:
>
> $\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$
>
>
>
I'll write what I have so far and highlight the missing piece that I am finding difficult to navigate around. As an "FYI" for those unfamiliar with Spivak's *Calculus*, the subject of Continuous Functions is not found until chapter 6, and I suspect that my issue arises from trig functions being more..."tackle-able"...once continuity is rigorously defined.
---
Relevant Lemma: $\lvert \sin(x) \rvert \leq 1 \quad$ (I do not believe this statement, in and of itself, requires knowledge of continuous functions)
Consider two cases: $\lvert L \rvert \gt 1$ or $\lvert L \rvert \leq 1$.
---
**Case 1**: Note that $\lvert L \rvert \gt 1 \implies \frac{\lvert L \rvert -1}{2}\gt 0$
Let $0 \lt\epsilon \lt \frac{\lvert L \rvert -1}{2}$ . Therefore $-\epsilon \gt \frac{1-\lvert L \rvert}{2}$. From which it follows:
$$ \lvert L \rvert - \epsilon \gt \frac{2 \lvert L \rvert +1 - \lvert L \rvert}{2}=\frac{\lvert L \rvert +1}{2}\gt 1$$
By our lemma, we then have:
$$\lvert L\rvert - \epsilon \gt 1 \geq \lvert \sin(x) \rvert$$.
Rearranging:
$$ \lvert L \rvert \gt 1 + \epsilon \geq \lvert \sin(x) \rvert + \epsilon$$
$$ \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Invoking one of the triangle inequality variants, we finally have:
$$ \lvert \sin(x) - L \rvert = \lvert L - \sin(x) \rvert \geq \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$
Note that $\forall x \in \mathbb R$, the above statement is true. Therefore, any $N \in \mathbb R$ can be chosen and one can always find an $x \gt N$, for which the desired criteria is met.
---
**Case 2**: $\lvert L \rvert \leq 1$
Consider an $\epsilon \lt \frac{1}{2}$. For example, $\epsilon = \frac{1}{4}$
Here is where I am basically stumped in the absence of knowing anything about continuous functions. My hunch is that because $\lvert L \rvert \leq 1$, I can effectively assert that $\exists c \in \mathbb R \big [ \sin(c) = L \big ]$.
Now, invoking the same triangle inequality variant as before, we know that:
$$ \lvert \sin(c) - \sin(x) \rvert \geq \lvert \sin(c) \rvert - \lvert \sin(x) \rvert $$
So if I can show that: $\exists x \in \mathbb R \big [\lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \big ]$, we are good to go. Once again, I assume that I need some notion of continuous functions in order to prove this.
More generally, in order to apply this argument to any $N \in \mathbb R$, I would like to prove the slightly more refined:
$$ \exists x \in [c - \pi, c + \pi] \text{ s.t. } \Big ( \lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \Big )$$
(noting the $c$ value that produces $\sin(c)=L$ can be replaced by $c+2\pi n$ for any any integer $n$).
If there is a method to circumvent continuous functions, I would greatly appreciate the insight!
Thank you! | 2021/04/27 | [
"https://math.stackexchange.com/questions/4118439",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/544640/"
] | >
> i.e. I wanted to write a proof that:
>
>
> $$\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$$
>
>
>
We can do this using $\varepsilon = \frac{1}{2}$.
**Case 1:** $L > 0$
Here for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
For such $x$ we have
$$\sin x = -1.$$
Since $L > 0$ we have
\begin{align}
|\sin x - L|&= |-1 - L| \\
& = 1 + L \\
& > \frac{1}{2}
\end{align}
**Case 2** $L < 0$
This case is nearly identical to the case for $L > 0$.
For any $N$ we can always find $x > N$ of the form $x = \frac{\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
For such $x$ we have
$$\sin x = 1.$$
Since $L < 0$ we have
\begin{align}
|\sin x - L|&= |1 - L| \\
& = 1 + |L| \\
& > \frac{1}{2}
\end{align}
**Case 3** $L = 0$
This case can be dealt with immediately by re-using either of the $x$ from the previous two cases:
If $x = \frac{\pi}{2} + 2k\pi$, then
\begin{align}
|\sin x - L|&= |1 - 0| \\
& = 1 \\
& > \frac{1}{2}
\end{align}
Of course, this all depends on knowing the behavior of $\sin$: that $\sin$ wavers between $1$ and $-1$ "forever" and so on. Given this behavior, one would expect intuitively that the limit doesn't exist, i.e. $\sin x$ wouldn't "settle" upon some single value for large $x$.
Later in the book Spivak defines the trigonometric functions formally in a way that conforms with the geometric/unit circle versions with which you are probably already familiar. Continuity plays a big part in these later definitions.
Here though, the main thing is just the periodic nature of $\sin$.
Finally, you may be somewhat leery of statements like:
>
> ...for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$.
>
>
>
This has at its heart the idea that given any real number $N$ we can find a natural number $n$ with $n > N$. *This* fact is employed in a few places early on in the text, but isn't formally proven until Chapter 8 (3rd Ed.) "Least Upper Bounds".
Spivak cops to this "cheating" at the end of that chapter.
(As an aside, an earlier problem in Chapter 5, 5-12 gives a very useful result:
If $f(x) \leq g(x)$ for all $x$ (or even just for all $x$ in a neighborhood of $a$) then $\lim\_{x\to a} f(x) \leq \lim\_{x\to a} g(x)$, provided these limits exist.
This can be shown to hold if we replace $a$ with $\infty$.
This, combined with your lemma that $|\sin x| \leq 1$ can be used to rule out your Case 1, i.e. since $-1 \leq \sin x \leq 1$ we must also have $-1 \leq \lim\_{x \to \infty}\sin x \leq 1$, if that limit exists.) | Note that since $\sin(x)$ is periodic for every real $N$ there exists a real $x>N$ and $y>N$ such that $\sin(x)=1$ and $\sin(y)=-1$
From here it’s easy to see that this implies if the limit exists then it must be $1$ since if it’s any other value $m$ then you can let $\epsilon$ be less than $|1-m|$ to obtain a contradiction .
But the above argument also works for $-1$ a contradiction hence the limit does not exist . |
7,391,333 | I am trying to implement a simple contact manager using the VirtualStringTree component. I have it set up to look like a list-view component with only three columns that will all contain text:

For the data structure, I am using svTree by Linas, which was mentioned in another Stack Overflow question.
I have declared a record like this:
```
type
TMainData = record
Name, Email, Password: string;
end;
```
In the form's OnCreate I have this:
```
procedure TForm1.FormCreate(Sender: TObject);
begin
MyTree := TSVTree<TMainData>.Create(False);
MyTree.VirtualTree := vst1;
end;
```
I am adding the data from TEdits like this:
```
procedure TForm1.BuildStructure;
var
svNode: TSVTreeNode<TMainData>;
Data: TMainData;
begin
MyTree.BeginUpdate;
try
Data.Name := edtname.Text;
Data.Email := edtEmail.Text;
Data.Password := edtPassword.Text;
svNode := MyTree.AddChild(nil, Data);
finally
MyTree.EndUpdate;
end;
Label1.Caption := 'Count: '+IntToStr(MyTree.TotalCount);
end;
```
How can I save this into a stream or a file to be loaded back? I have tried using `MyTree.SaveToFile('C:/Test.dat')` and `MyTree.LoadFromFile('C:/Test.dat')`, but when it's loaded back the tree view contains no data, only a blank row. | 2011/09/12 | [
"https://Stackoverflow.com/questions/7391333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/471837/"
] | You need to set OnLoadNode and OnSaveNode procedures for your TSVTree and implement your logic here. You can look at Project2 in the Demos folder. E.g.:
```
uses
uSvHelpers;
MyTree.OnSaveNode := DoSave;
MyTree.OnLoadNode := DoLoad;
procedure TForm1.DoLoad(Sender: TSVTree<TMainData>; Node: TSVTreeNode<TMainData>; Stream: TStream);
var
obj: TMainData;
begin
//
if Assigned(Node) then
begin
//read from stream
//read in correct order
obj.Name := Stream.AsString;
obj.Email := Stream.AsString;
obj.Password := Stream.AsString;
Node.FValue := obj;
end;
end;
procedure TForm1.DoSave(Sender: TSVTree<TMainData>; Node: TSVTreeNode<TMainData>; Stream: TStream);
begin
if Assigned(Node) then
begin
//read from stream
Stream.WriteString(Node.FValue.Name);
Stream.WriteString(Node.FValue.Email);
Stream.WriteString(Node.FValue.Password);
end;
end;
```
After that you can just call `MyTree.SaveToFile('C:/Test.dat')` or `MyTree.LoadFromFile('C:/Test.dat')`. In my demo and this example i've used another unit (uSvHelpers) which implements TStream helper for more OO stream support. You can of course use your own way to write your data information to stream. | Looks like you need to implement the OnSaveNode and OnLoadNode events:
```
procedure TForm.VTLoadNode(Sender: TBaseVirtualTree;
Node: PVirtualNode; Stream: TStream);
begin
// Load Node Data record from the stream
end;
procedure TForm.VTSaveNode(Sender: TBaseVirtualTree;
Node: PVirtualNode; Stream: TStream);
begin
// Save Node Data record to the stream
end;
``` |
27,443,929 | I'm trying to get a dropdown show the right value when editing using a viewmodel but it only works when i pass the complete model to the view.
When I do it like this and there is already a contact selected it shows that contact in the edit screen.
**Model**
```
public class ClientModel
{
public int ID { get; set; }
public int ContactID { get; set; }
//Other atributes
}
```
**View EditContact**
```
@model Project.Models.ClientModel
@Html.DropDownListFor(model => model.ContactID , (SelectList)ViewBag.ContactID, "select a contact")
```
**Controller**
```
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBagID.Contact = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact");
ClientModel model= db.ClientModel.Find(id);
return View(model);
}
```
But when I do it like this and there is already a contact selected the dropdownlist shows select contact.
**Model**
```
public class ClientModel
{
public int ID { get; set; }
public int ContactID { get; set; }
//Other atributes
}
```
**ViewModel**
```
public class ClientEditContactModel
{
public int ID { get; set; }
public int ContactID { get; set; }
}
```
**View EditContact**
```
@model Project.Models.ClientEditContactModel
@Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactID, "select a contact")
```
**Controller**
```
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBag.ContactID = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact");
ClientModel client= db.ClientModel.Find(id);
ClientEditContactModel model = new ClientEditContactModel();
model.ID = client.ID;
model.ContactID = client.ContactID
return View(model);
}
```
How do i fix this with the viewmodel?
**Edit**
I've made some typo's in my code so I fixed them but because of them i found the answer see below. | 2014/12/12 | [
"https://Stackoverflow.com/questions/27443929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4252392/"
] | I found the answer after some more research here <https://stackoverflow.com/a/11949123/4252392>.
The problem was that ViewBag's name is the same as the model's property.
So i changed the Viewbag's name.
**New Controller**
```
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBag.ContactIDList = new SelectList(Contact.AsEnumerable(), "ID",
"name", "Contact");
ClientModel client= db.ClientModel.Find(id);
ClientEditContactModel model = new ClientEditContactModel();
model.ID = client.ID;
model.ContactID = client.ContactID
return View(model);
}
```
**New View**
```
@model Project.Models.ClientEditContactModel
@Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactIDList,
"select a contact")
``` | If you set selected value in ContactID property from dropdown so you need to set dropdown in view like below:
```
@model Project.Models.ClientEditContactModel
@Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.Contact,
"select a contact")
``` |
3,955,878 | I am currently using apTreeshape to simulate phylogenetic trees using the "Yule-Hardy" Method. What I want to do is randomly generate between 20 and 25 different numbers for three different groupings (small, medium and large trees) and then generate about 40 trees for every random number chosen from within the grouping.
I know how I would do this in Python of Matlab, but in R things seem to behave a bit differently.
My thought was that if I were to generate a vector full of random numbers (one for each size grouping) and then use that to generate a vector which would basically contain all of the repeated values of each random number.
Here is what I have:
```
sm_leaves<-c(sample(3:50,25,replace=F));
s_leafy<-numeric();
for (i in 1:length(sm_leaves)) {
for (j in 1:10) {
s_leafy[j+i-1]=sm_leaves[i];
}
}
```
This is giving me output like:
```
> s_leafy
[1] 5 38 6 22 29 20 19 46 9 18 39 50 34 11 43 7 8 32 10 42 14 37
[23] 23 13 28 28 28 28 28 28 28 28 28 28
```
But What I want is something more like:
```
> s_leafy
[1] 5 5 5 5 5 5 5 5 5 5 38 38 38 38 38 38 38 38 38 ... 28 28 28 28 28 28 28 28 28 28
```
My reason for doing this is merely so that I can append this vector to a data frame along with all of the randomly generated trees - I need 2000 of them, so doing this by hand ain't quite practical.
All I have really been able to deduce from my previous attempts to solve this problem is that generally speaking while loops should be used instead of for loops, and many people have talked about using expand.grid, but I don't think that the latter is particularly useful in this case.
Thanks for reading, I hope my problem isn't too trivial (although I wouldn't be surprised if it were). | 2010/10/18 | [
"https://Stackoverflow.com/questions/3955878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478864/"
] | Apologies if I don't quite understand the question, but what about:
```
sm_leaves <- sample(3:50, 25, replace=FALSE)
s_leafy <- rep(sm_leaves, each=10)
``` | You want `rep()` with the `each=10` option:
```
> set.seed(42)
> sm_leaves <- sample(3:50,25,replace=F)
> s_leafy <- rep(sm_leaves, each=3) ## here rep=3 to generate small sample
> s_leafy
[1] 46 46 46 47 47 47 16 16 16 40 40 40 31 31 31 25 25
[18] 25 33 33 33 8 8 8 29 29 29 30 30 30 20 20 20 42
[35] 42 42 36 36 36 11 11 11 18 18 18 34 34 34 35 35 35
[52] 6 6 6 17 17 17 19 19 19 28 28 28 44 44 44 41 41
[69] 41 26 26 26 4 4 4
>
``` |
3,955,878 | I am currently using apTreeshape to simulate phylogenetic trees using the "Yule-Hardy" Method. What I want to do is randomly generate between 20 and 25 different numbers for three different groupings (small, medium and large trees) and then generate about 40 trees for every random number chosen from within the grouping.
I know how I would do this in Python of Matlab, but in R things seem to behave a bit differently.
My thought was that if I were to generate a vector full of random numbers (one for each size grouping) and then use that to generate a vector which would basically contain all of the repeated values of each random number.
Here is what I have:
```
sm_leaves<-c(sample(3:50,25,replace=F));
s_leafy<-numeric();
for (i in 1:length(sm_leaves)) {
for (j in 1:10) {
s_leafy[j+i-1]=sm_leaves[i];
}
}
```
This is giving me output like:
```
> s_leafy
[1] 5 38 6 22 29 20 19 46 9 18 39 50 34 11 43 7 8 32 10 42 14 37
[23] 23 13 28 28 28 28 28 28 28 28 28 28
```
But What I want is something more like:
```
> s_leafy
[1] 5 5 5 5 5 5 5 5 5 5 38 38 38 38 38 38 38 38 38 ... 28 28 28 28 28 28 28 28 28 28
```
My reason for doing this is merely so that I can append this vector to a data frame along with all of the randomly generated trees - I need 2000 of them, so doing this by hand ain't quite practical.
All I have really been able to deduce from my previous attempts to solve this problem is that generally speaking while loops should be used instead of for loops, and many people have talked about using expand.grid, but I don't think that the latter is particularly useful in this case.
Thanks for reading, I hope my problem isn't too trivial (although I wouldn't be surprised if it were). | 2010/10/18 | [
"https://Stackoverflow.com/questions/3955878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478864/"
] | Using 'rep' is clearly the answer for how to do this quickly in R, but why doesn't your code work? A little investigation reveals why.
First, take out the randomness and give yourself a simple, reproducible example. Set sm\_leaves to c(3,4,5) and see what happens. You get:
3 4 5 5 5 5 5 5 5 5 5 5
which still looks wrong. You expected ten 3s, ten 4s, ten 5s right? Hmmm. Add a print statement to your loop to see where the values are being stuck:
```
> for (i in 1:length(sm_leaves)) {
for (j in 1:10) {
print(j+i-1)
s_leafy[j+i-1]=sm_leaves[i];
}
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
...etc....
```
Oops. Your vector index is wrong. j+i-1 is jumping back after every inner loop and overwriting the earlier values. You want:
```
s_leafy[j + (i - 1)*10]=sm_leaves[i];
```
So maybe this is just a simple case of you missing the \*10 in the expression!
Note however that a lot of simple vector manipulation is best done using R's functions such as rep, and seq, and "[", as explained in the other answers here. | Apologies if I don't quite understand the question, but what about:
```
sm_leaves <- sample(3:50, 25, replace=FALSE)
s_leafy <- rep(sm_leaves, each=10)
``` |
3,955,878 | I am currently using apTreeshape to simulate phylogenetic trees using the "Yule-Hardy" Method. What I want to do is randomly generate between 20 and 25 different numbers for three different groupings (small, medium and large trees) and then generate about 40 trees for every random number chosen from within the grouping.
I know how I would do this in Python of Matlab, but in R things seem to behave a bit differently.
My thought was that if I were to generate a vector full of random numbers (one for each size grouping) and then use that to generate a vector which would basically contain all of the repeated values of each random number.
Here is what I have:
```
sm_leaves<-c(sample(3:50,25,replace=F));
s_leafy<-numeric();
for (i in 1:length(sm_leaves)) {
for (j in 1:10) {
s_leafy[j+i-1]=sm_leaves[i];
}
}
```
This is giving me output like:
```
> s_leafy
[1] 5 38 6 22 29 20 19 46 9 18 39 50 34 11 43 7 8 32 10 42 14 37
[23] 23 13 28 28 28 28 28 28 28 28 28 28
```
But What I want is something more like:
```
> s_leafy
[1] 5 5 5 5 5 5 5 5 5 5 38 38 38 38 38 38 38 38 38 ... 28 28 28 28 28 28 28 28 28 28
```
My reason for doing this is merely so that I can append this vector to a data frame along with all of the randomly generated trees - I need 2000 of them, so doing this by hand ain't quite practical.
All I have really been able to deduce from my previous attempts to solve this problem is that generally speaking while loops should be used instead of for loops, and many people have talked about using expand.grid, but I don't think that the latter is particularly useful in this case.
Thanks for reading, I hope my problem isn't too trivial (although I wouldn't be surprised if it were). | 2010/10/18 | [
"https://Stackoverflow.com/questions/3955878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478864/"
] | Using 'rep' is clearly the answer for how to do this quickly in R, but why doesn't your code work? A little investigation reveals why.
First, take out the randomness and give yourself a simple, reproducible example. Set sm\_leaves to c(3,4,5) and see what happens. You get:
3 4 5 5 5 5 5 5 5 5 5 5
which still looks wrong. You expected ten 3s, ten 4s, ten 5s right? Hmmm. Add a print statement to your loop to see where the values are being stuck:
```
> for (i in 1:length(sm_leaves)) {
for (j in 1:10) {
print(j+i-1)
s_leafy[j+i-1]=sm_leaves[i];
}
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
...etc....
```
Oops. Your vector index is wrong. j+i-1 is jumping back after every inner loop and overwriting the earlier values. You want:
```
s_leafy[j + (i - 1)*10]=sm_leaves[i];
```
So maybe this is just a simple case of you missing the \*10 in the expression!
Note however that a lot of simple vector manipulation is best done using R's functions such as rep, and seq, and "[", as explained in the other answers here. | You want `rep()` with the `each=10` option:
```
> set.seed(42)
> sm_leaves <- sample(3:50,25,replace=F)
> s_leafy <- rep(sm_leaves, each=3) ## here rep=3 to generate small sample
> s_leafy
[1] 46 46 46 47 47 47 16 16 16 40 40 40 31 31 31 25 25
[18] 25 33 33 33 8 8 8 29 29 29 30 30 30 20 20 20 42
[35] 42 42 36 36 36 11 11 11 18 18 18 34 34 34 35 35 35
[52] 6 6 6 17 17 17 19 19 19 28 28 28 44 44 44 41 41
[69] 41 26 26 26 4 4 4
>
``` |
180,737 | Please, help me to put a proper word collocation into a sentence.
I need to describe in an office announcement that a new printer is set for satisfy any employee (printing) need.
I found the phrase *"to support needs"*, but I am not sure about it.
The context is here:
>
> Dear Colleagues,
>
>
> We would like to inform you that the new printer is now available on the 9th floor of the 3rd tower. It was set to simplify the access to the printer and support needs of the growing number of employees of the recently opened floors of the third tower.
>
>
>
Any help would be appreciated! | 2018/09/25 | [
"https://ell.stackexchange.com/questions/180737",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/81713/"
] | It doesn't end with '**s**' because it's the (bare) **infinitive**, which is used without '**to**' after verbs like **hear**, bid, let, make, see, need, dare, etc.
<https://www.englishgrammar.org/bare-infinitive-2/> | Sound in this sentence is a noun, so you are talking about the 'sound' of his/her voice, not the 'sounds' that he/she is making.
'Do' and 'go' are both verbs, so they do not follow the same rule. |
64,443,026 | In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is `InputHTMLAttributes`:
```js
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;
onChange?: ChangeEventHandler<T>;
}
```
I want to define a specific type for only an input of type `number` so that TypeScript complains if I use a `checked` or `disabled` prop on it:
```html
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
```
So is there already a type definition for that coming from React?
I know that I can just define it like the following but I would prefer to use an official source:
```js
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}
``` | 2020/10/20 | [
"https://Stackoverflow.com/questions/64443026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583669/"
] | Multiply, then reset negative values:
```
# transpose and multiply per row
res <- t(m) * v
res <- t(res)
# then reset negatives to original value
res[m < 0] <- m[ m < 0 ]
res
# a b c
# [1,] -1 -1 -1
# [2,] 4 6 -9
# [3,] 6 6 -3
# [4,] 8 -4 -2
``` | Here is another base R option using `msk` as the mask
```
> m*t((msk <- t(m)>0)*v + !msk)
a b c
[1,] -1 -1 -1
[2,] 4 6 -9
[3,] 6 6 -3
[4,] 8 -4 -2
``` |
64,443,026 | In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is `InputHTMLAttributes`:
```js
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;
onChange?: ChangeEventHandler<T>;
}
```
I want to define a specific type for only an input of type `number` so that TypeScript complains if I use a `checked` or `disabled` prop on it:
```html
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
```
So is there already a type definition for that coming from React?
I know that I can just define it like the following but I would prefer to use an official source:
```js
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}
``` | 2020/10/20 | [
"https://Stackoverflow.com/questions/64443026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583669/"
] | You can use the condition `m>0` to subset the result:
```
i <- m>0
#i <- which(m>0) #Maybe faster Alternative
m[i] <- (m %*% diag(v))[i]
#m[i] <- (m * v[col((m))])[i] #Maybe faster Alternative
m
# a b c
#[1,] -1 -1 -1
#[2,] 4 6 -9
#[3,] 6 6 -3
#[4,] 8 -4 -2
```
Or another maybe fast version:
```
i <- +(m>0)
m * (v[col(m)]*i + 1 - i)
``` | Here is another base R option using `msk` as the mask
```
> m*t((msk <- t(m)>0)*v + !msk)
a b c
[1,] -1 -1 -1
[2,] 4 6 -9
[3,] 6 6 -3
[4,] 8 -4 -2
``` |
64,443,026 | In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is `InputHTMLAttributes`:
```js
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;
onChange?: ChangeEventHandler<T>;
}
```
I want to define a specific type for only an input of type `number` so that TypeScript complains if I use a `checked` or `disabled` prop on it:
```html
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
```
So is there already a type definition for that coming from React?
I know that I can just define it like the following but I would prefer to use an official source:
```js
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}
``` | 2020/10/20 | [
"https://Stackoverflow.com/questions/64443026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583669/"
] | ```
to_upd <- which(m>0)
m[to_upd] <- (m * v[col(m)])[to_upd]
m
# a b c
# [1,] -1 -1 -1
# [2,] 4 6 -9
# [3,] 6 6 -3
# [4,] 8 -4 -2
```
Data
```
v <- c(2,3,-3)
m <- cbind(
a = c(-1,2,3,4),
b = c(-1,2,2,-4),
c = c(-1,3,1,-2)
)
``` | Here is another base R option using `msk` as the mask
```
> m*t((msk <- t(m)>0)*v + !msk)
a b c
[1,] -1 -1 -1
[2,] 4 6 -9
[3,] 6 6 -3
[4,] 8 -4 -2
``` |
64,443,026 | In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is `InputHTMLAttributes`:
```js
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;
onChange?: ChangeEventHandler<T>;
}
```
I want to define a specific type for only an input of type `number` so that TypeScript complains if I use a `checked` or `disabled` prop on it:
```html
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
```
So is there already a type definition for that coming from React?
I know that I can just define it like the following but I would prefer to use an official source:
```js
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}
``` | 2020/10/20 | [
"https://Stackoverflow.com/questions/64443026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583669/"
] | You can do like this:
```r
m * c(1, v)[col(m) * (m > 0) + 1L]
#R> a b c
#R> [1,] -1 -1 -1
#R> [2,] 4 6 -9
#R> [3,] 6 6 -3
#R> [4,] 8 -4 -2
```
>
> My dataset is large, so I'm looking for an elegant solution
>
>
>
If by elegant you mean fast, then this seems to be an as fast or faster solution compared with the other options:
```r
# simulate a larger data set
set.seed(1)
n <- 10000
p <- 50
m <- matrix(rnorm(n * p), n)
v <- rnorm(p)
bench::mark(
sindri_baldur = {
to_upd <- which(m>0)
res <- m
res[to_upd] <- (res * v[col(res)])[to_upd]
res
},
Ben = {
res <- m
res * c(1, v)[col(res) * (res > 0) + 1L]
},
GKi = {
i <- m > 0
res <- m
res[i] <- (res %*% diag(v))[i]
res
},
zx8754 = {
res <- t(m) * v
res <- t(res)
res[m < 0] <- m[ m < 0 ]
res
}, min_time = 2)
#R> # A tibble: 4 x 13
#R> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
#R> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm>
#R> 1 sindri_baldur 6.34ms 9.3ms 119. 16.22MB 1.02 235 2 1.97s
#R> 2 Ben 5.01ms 5.22ms 190. 9.54MB 0.503 378 1 1.99s
#R> 3 GKi 17.82ms 18.28ms 53.8 17.19MB 0.555 97 1 1.8s
#R> 4 zx8754 9.03ms 9.26ms 107. 19.07MB 1.53 210 3 1.96s
``` | Here is another base R option using `msk` as the mask
```
> m*t((msk <- t(m)>0)*v + !msk)
a b c
[1,] -1 -1 -1
[2,] 4 6 -9
[3,] 6 6 -3
[4,] 8 -4 -2
``` |
68,819 | [Cosmic rays](https://en.wikipedia.org/wiki/Cosmic_ray) are energetic particles coming from space that hit the Earth's atmosphere and produce a lot of [secondary radiation](https://en.wikipedia.org/wiki/Air_shower_(physics)) (some of which we see in visible light as aurorae). Would it make sense for an organism floating in the upper atmosphere, or even on the brink of space, to try and make this energy work for them, as plants do using the photons from sunlight to split water? Or are cosmic rays too destructive, or too unwieldy, or too sparse for such use? The question is not confined to Earth, of course, or to organisms similar to those living on today's Earth. I'm trying to decide if a microbial biosphere could live off cosmic radiation and its subproducts.
P.S.: [This post](https://worldbuilding.stackexchange.com/questions/36534/no-sunlight-just-high-energy-radiation) touches on some of the same points as my question, though I'm thinking more about a rogue planet far from any star-like energy source (i. e. no pulsars or black holes nearby). | 2017/01/21 | [
"https://worldbuilding.stackexchange.com/questions/68819",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/31844/"
] | I would say that yes, it's borderline possible.
The organism should be very resistant to ionizing radiation; a Universe that allows [*Deinococcus radiodurans*](https://en.wikipedia.org/wiki/Deinococcus_radiodurans) to exist would have little trouble in producing this new critter, even limiting ourselves to DNA.
The organism would of course need to consume ordinary matter to replicate; it would therefore find it way more convenient to (also) extract what energy it can from that matter. Actually it's likely that the capability of absorbing cosmic radiation would evolve from the former; the organism acquires matter and this interacts with cosmic radiation, supplying harvestable energy. Once this kind of matter is more and more incorporated into the new generations of the organism, it will "optimize" itself to directly take advantage of the radiation.
An organism could not begin directly using cosmic radiation, since to do that it would need chemicals and structures that would be already pretty complex. It would need to start from simple chemical reactions, and evolve to first defend against, then make use of the radiation. The most obvious evolution pressure line would be if the defense takes the form of some radiation-hardy chemical, which is transformed on impact generating much higher-energy compounds that would be initially disposed of. Afterwards, any mutation allowing to extract energy from such compounds would have an enormous evolutionary value.
This is not unlike what already happened to [radiotrophic fungi](https://en.wikipedia.org/wiki/Radiotrophic_fungus), which produce a special kind of melanin that is capable of harvesting energy from gamma radiations. It would be more difficult (!) for our hypothetic organism, in that cosmic rays are much more penetrating and energetic than gamma rays and therefore require proportionally more massive interception.
And, of course, the organism would need to live somewhere with *a lot* of cosmic rays.
One possibility would be some sort of low-temperature outer space slug capable of accreting a "black ice" carapace. It would migrate to the safe center of cometary nuclei to spawn, then come out when the carapace is thick enough to both defend the young slug and supply it with energy. The slug would need to have a very low metabolic rate, and be based on a totally different organic chemistry than Earth organisms.
---
There's something along these lines in ["Camelot 30K"](https://en.wikipedia.org/wiki/Camelot_30K) by physicist Robert L. Forward, where a (macroscopic) lifeform is presented that harvests atomic nuclei transmuted by the impact of cosmic rays on distant comets.
>
> *"The initial energy source for the kerac civilization comes from the background cosmic radiation, which creates long-lived excited molecules and free radicals in the ice over long periods of time"*. He drew an arrow leading to another box that he drew in the rotund shape of an iceworm. *"Out on the farms, the iceworms and young heullers tunnel through the untouched ice around the periphery of Camalor. They extract free radicals frozen into the pristine ice and use them as a source of energy to grow and continue tunneling. Those long-lived free radicals are the first level energy source of the kerack food chain, since the iceworms and heullers are harvested as meat. While the iceworms are doing that, they also extract from the dirty ice all the unstable radioisotopes that the dirt and ice contain."*
>
>
>
(While different organisms are named - *iceworms*, *heullers*, *keracks* - it is posited in the book that they are actually all alternate phenotypes of a *single* organism, the kerack hive drone, not unlike what happens with bees). | It can't exist and this is why
------------------------------
This organism would have to be unlike any that lives on Earth. First of all, if the organism was in our upper atmosphere it would be too protected from the cosmic rays for sustainable life. If it has DNA, it would have to be very protected in order to prevent defects and damage. We're talking some kind of biological space suit as it were. All life that we know of has some kind DNA so this is pretty much a given.
Another factor is the distance between organism and producer of the cosmic rays. Obviously the further, the more sparse and unreliable it would be as an energy source, too close and it might get incinerated. Just like Earth, I suggest some kind of Goldilocks Zone where the conditions are 'just right'.
All this being said, I would assume the organism also needs some kind of respiratory system, and a way of excreting unwanted gases, because there isn't any thing that can survive from nothing but charged particles.
To conclude, I do not believe this is possible because the organism needs to be able to absorb harmful cosmic radiation with out being harmed. It also needs to be outside of a planet’s magnetosphere whilst still being able to diffuse with gases. |
68,819 | [Cosmic rays](https://en.wikipedia.org/wiki/Cosmic_ray) are energetic particles coming from space that hit the Earth's atmosphere and produce a lot of [secondary radiation](https://en.wikipedia.org/wiki/Air_shower_(physics)) (some of which we see in visible light as aurorae). Would it make sense for an organism floating in the upper atmosphere, or even on the brink of space, to try and make this energy work for them, as plants do using the photons from sunlight to split water? Or are cosmic rays too destructive, or too unwieldy, or too sparse for such use? The question is not confined to Earth, of course, or to organisms similar to those living on today's Earth. I'm trying to decide if a microbial biosphere could live off cosmic radiation and its subproducts.
P.S.: [This post](https://worldbuilding.stackexchange.com/questions/36534/no-sunlight-just-high-energy-radiation) touches on some of the same points as my question, though I'm thinking more about a rogue planet far from any star-like energy source (i. e. no pulsars or black holes nearby). | 2017/01/21 | [
"https://worldbuilding.stackexchange.com/questions/68819",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/31844/"
] | I would say that yes, it's borderline possible.
The organism should be very resistant to ionizing radiation; a Universe that allows [*Deinococcus radiodurans*](https://en.wikipedia.org/wiki/Deinococcus_radiodurans) to exist would have little trouble in producing this new critter, even limiting ourselves to DNA.
The organism would of course need to consume ordinary matter to replicate; it would therefore find it way more convenient to (also) extract what energy it can from that matter. Actually it's likely that the capability of absorbing cosmic radiation would evolve from the former; the organism acquires matter and this interacts with cosmic radiation, supplying harvestable energy. Once this kind of matter is more and more incorporated into the new generations of the organism, it will "optimize" itself to directly take advantage of the radiation.
An organism could not begin directly using cosmic radiation, since to do that it would need chemicals and structures that would be already pretty complex. It would need to start from simple chemical reactions, and evolve to first defend against, then make use of the radiation. The most obvious evolution pressure line would be if the defense takes the form of some radiation-hardy chemical, which is transformed on impact generating much higher-energy compounds that would be initially disposed of. Afterwards, any mutation allowing to extract energy from such compounds would have an enormous evolutionary value.
This is not unlike what already happened to [radiotrophic fungi](https://en.wikipedia.org/wiki/Radiotrophic_fungus), which produce a special kind of melanin that is capable of harvesting energy from gamma radiations. It would be more difficult (!) for our hypothetic organism, in that cosmic rays are much more penetrating and energetic than gamma rays and therefore require proportionally more massive interception.
And, of course, the organism would need to live somewhere with *a lot* of cosmic rays.
One possibility would be some sort of low-temperature outer space slug capable of accreting a "black ice" carapace. It would migrate to the safe center of cometary nuclei to spawn, then come out when the carapace is thick enough to both defend the young slug and supply it with energy. The slug would need to have a very low metabolic rate, and be based on a totally different organic chemistry than Earth organisms.
---
There's something along these lines in ["Camelot 30K"](https://en.wikipedia.org/wiki/Camelot_30K) by physicist Robert L. Forward, where a (macroscopic) lifeform is presented that harvests atomic nuclei transmuted by the impact of cosmic rays on distant comets.
>
> *"The initial energy source for the kerac civilization comes from the background cosmic radiation, which creates long-lived excited molecules and free radicals in the ice over long periods of time"*. He drew an arrow leading to another box that he drew in the rotund shape of an iceworm. *"Out on the farms, the iceworms and young heullers tunnel through the untouched ice around the periphery of Camalor. They extract free radicals frozen into the pristine ice and use them as a source of energy to grow and continue tunneling. Those long-lived free radicals are the first level energy source of the kerack food chain, since the iceworms and heullers are harvested as meat. While the iceworms are doing that, they also extract from the dirty ice all the unstable radioisotopes that the dirt and ice contain."*
>
>
>
(While different organisms are named - *iceworms*, *heullers*, *keracks* - it is posited in the book that they are actually all alternate phenotypes of a *single* organism, the kerack hive drone, not unlike what happens with bees). | Cosmic rays might *first* affect some non-living substance, which then provides energy and/or nurishment to the life.
That might indeed be a critical factor, like fixing nitrogen for the base of the food chain.
These cosmic rays can cause chemical reactions or nuclear reactions, such as 14C on our planet. So it could be a complex cascade of reactions, bringing energy down into the biosphere. |
60,078,041 | I am trying to create a regular expression to separate each word from `.` (dot) in JavaScript.
```
function myFunction() {
var url = "in.k1.k2.k3.k4.com"
var result
var match
if (match = url.match(/^[^\.]+\.(.+\..+)$/)) {
console.log(match);
}
}
```
Actual result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
```
Expected result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
match[2] : k2.k3.k4.com
match[3] : k3.k4.com
match[4] : k4.com
```
Please help me to create perfect regular expression. | 2020/02/05 | [
"https://Stackoverflow.com/questions/60078041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12337410/"
] | In order to store more than one JSON record, use an array, as when loading you can just load JSON types (an an array is the ideal JSON type you're looking for for that use case).
In that case, to read all scores:
```py
scores = []
with open ("score.json") as json_data:
scores = json.load(json_data)
```
But most important, to write them to a file:
```py
scores.append(score)
json_dump = json.dumps(scores)
f = open("score.json","w")
f.write(json_dump)
f.close()
```
**Update**
The last code can also be written using `json.dump`:
```py
scores.append(score)
f = open("score.json","w")
json.dump(scores, f)
f.write(json_dump)
f.close()
``` | The way your code is written, it will append score dictionaries instead of adding an object in an array of scores.
If you check the output file score.json it will look like {...}{...}{...} whereas it should be like [{...},{...},{...}] |
60,078,041 | I am trying to create a regular expression to separate each word from `.` (dot) in JavaScript.
```
function myFunction() {
var url = "in.k1.k2.k3.k4.com"
var result
var match
if (match = url.match(/^[^\.]+\.(.+\..+)$/)) {
console.log(match);
}
}
```
Actual result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
```
Expected result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
match[2] : k2.k3.k4.com
match[3] : k3.k4.com
match[4] : k4.com
```
Please help me to create perfect regular expression. | 2020/02/05 | [
"https://Stackoverflow.com/questions/60078041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12337410/"
] | In order to store more than one JSON record, use an array, as when loading you can just load JSON types (an an array is the ideal JSON type you're looking for for that use case).
In that case, to read all scores:
```py
scores = []
with open ("score.json") as json_data:
scores = json.load(json_data)
```
But most important, to write them to a file:
```py
scores.append(score)
json_dump = json.dumps(scores)
f = open("score.json","w")
f.write(json_dump)
f.close()
```
**Update**
The last code can also be written using `json.dump`:
```py
scores.append(score)
f = open("score.json","w")
json.dump(scores, f)
f.write(json_dump)
f.close()
``` | You can read the file line by line, every line will contain a valid JSON object:
```
with open('score.json') as fp:
for line in fp:
data = json.loads(line)
# do something with data
```
Or if you need everything in one object:
```
with open('score.json') as fp:
data = []
for line in fp:
data.append(json.loads(line))
``` |
60,078,041 | I am trying to create a regular expression to separate each word from `.` (dot) in JavaScript.
```
function myFunction() {
var url = "in.k1.k2.k3.k4.com"
var result
var match
if (match = url.match(/^[^\.]+\.(.+\..+)$/)) {
console.log(match);
}
}
```
Actual result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
```
Expected result is:
```
match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
match[2] : k2.k3.k4.com
match[3] : k3.k4.com
match[4] : k4.com
```
Please help me to create perfect regular expression. | 2020/02/05 | [
"https://Stackoverflow.com/questions/60078041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12337410/"
] | The way your code is written, it will append score dictionaries instead of adding an object in an array of scores.
If you check the output file score.json it will look like {...}{...}{...} whereas it should be like [{...},{...},{...}] | You can read the file line by line, every line will contain a valid JSON object:
```
with open('score.json') as fp:
for line in fp:
data = json.loads(line)
# do something with data
```
Or if you need everything in one object:
```
with open('score.json') as fp:
data = []
for line in fp:
data.append(json.loads(line))
``` |
50,598,509 | I want to change CSV file content:
```
itemId,url,name,type
1|urlA|nameA|typeA
2|urlB|nameB|typeB
3|urlC,urlD|nameC|typeC
4|urlE|nameE|typeE
```
into an array:
```
[itemId,url,name,type]
[1,urlA,nameA,typeA]
[2,urlB,nameB,typeB]
[**3**,**urlC**,nameC,typeC]
[**3**,**urlD**,nameC,typeC]
[4,urlE,nameE,typeE]
```
Could anybody teach me how to do it?
Finally, I'm going to DL url files(.jpg) | 2018/05/30 | [
"https://Stackoverflow.com/questions/50598509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5448792/"
] | The header row has a different separator than the data. That's a problem. You need to change the header row to use `|` instead of `,`. Then:
```
require 'csv'
require 'pp'
array = Array.new
CSV.foreach("test.csv", col_sep: '|', headers: true) do |row|
if row['url'][/,/]
row['url'].split(',').each do |url|
row['url'] = url
array.push row.to_h.values
end
else
array.push row.to_h.values
end
end
pp array
=> [["1", "urlA", "nameA", "typeA"],
["2", "urlB", "nameB", "typeB"],
["3", "urlC", "nameC", "typeC"],
["3", "urlD", "nameC", "typeC"],
["4", "urlE", "nameE", "typeE"]]
``` | You'll need to test the fifth column to see how the line should be parsed. If you see a fifth element (row[4]) output the line twice replacing the url column
```
array = Array.new
CSV.foreach("test.csv") do |row|
if row[4]
array << [row[0..1], row[3..4]].flatten
array << [[row[0]], row[2..4]].flatten
else
array << row
end
end
p array
```
In your example you had asterisks but I'm assuming that was just to emphasise the lines for which you want special handling. If you do want asterisks, you can modify the two array shovel commands appropriately. |
142,696 | I have not given this too much thought until recently, when a bit of a back and forth happened with a client. So, when I start a new document in InDesign, **for CMYK print**, how to I know how to setup the color settings ?
Many times I will just not look at this and go with whatever is set by default, but apparently this may affect things.
Is this just a case of choosing between the "Europe General Purpose" vs the "North America General Purpose" presets, or is there more to this ?
Are the "Coated FOGRA39"/"US Web Coated (SWOP)" the most widely used standards that will generally work for printers in the EU/US ?
What about web documents in RGB ? Like, when you design a presentation that will not go to a CMYK printer, what's the proper colour space to use for that ?
[](https://i.stack.imgur.com/W9GZ7.jpg)
[](https://i.stack.imgur.com/cHb5b.jpg) | 2020/10/29 | [
"https://graphicdesign.stackexchange.com/questions/142696",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/62949/"
] | Why bother about color profiles?
================================
First of all you need to accept that *different printers follow different standards*. The same CMYK numbers will look differently when printed according to different standards. It's not possible to make a PDF which will be perfect under all circumstances. Unless I absolutely have to, I wouldn't export a PDF for print before knowing where the document will be printed, on which kind of paper and which ICC profile the print house recommends for that paper.
To use the wrong profile can affect the colors on the final print, but even if there is little difference between the profile you choose and the recommended one, there is also a responsibility issue. If you receive a print where you think the colors are a little bit off and the print house discovers that you didn't use the recommended profile, they might park the complaint right there. Always best to keep your path clean.
Setting up your document
========================
Setting up *Working Spaces* in the *Color Settings* affects *new* documents, but you can always change the settings for an existing document later by using *Edit > Assign Profiles*. You can also choose a different profile when exporting a PDF. So you are not confined by what the settings where when you created your document.
The main reason for caring about which profile to use for your InDesign document from the beginning is that it affects the *preview*.
In a print document, when you turn on *View > Overprint Preview* the graphics and images are displayed *as they would look if they were printed according to the Document CMYK*.
RGB swatches
------------
Although all swatches in a print document will be CMYK by default, it's also possible to make RGB swatches. They are assumed to have the RGB profile chosen as *Document RGB* and with *Overprint Preview* turned on they are displayed as if they were converted from that to the CMYK profile chosen as *Document CMYK*.
RGB images with an embedded profile
-----------------------------------
If you are a little in doubt about color profiles and don't know exactly what you are doing and why, I would always recommend to only place RGB images with an embedded color profile. With *Overprint Preview* turned on they are displayed as if they were converted from their embedded RGB profile to the CMYK profile chosen as *Document CMYK*.
For example an RGB image looking like this:
[](https://i.stack.imgur.com/r2UTA.png)
Will look like this with *Document CMYK* set to *Coated FOGRA39*:
[](https://i.stack.imgur.com/ghLFm.png)
But with *Document CMYK* set to *PSO Uncoated*, it will look more faded because the gamut is smaller:
[](https://i.stack.imgur.com/kxZyD.png)
Untagged RGB images
-------------------
RGB images without an embedded profile are a common cause of a shift in colors from screen to print. They are displayed in Adobe's applications as if they had the profile chosen as *Working RGB* in Photoshop or *Document RGB* in InDesign. So if your Photoshop for example has *Adobe RGB* as *Working RGB* and your InDesign document has *sRGB* as *Document RGB*, the untagged images will be displayed differently in those two applications.
Here is how an untagged image (which is is in reality an sRGB image) is displayed when InDesign assumes *sRGB*:
[](https://i.stack.imgur.com/HEr6w.png)
And here is how it looks if InDesign assumes *Adobe RGB*:
[](https://i.stack.imgur.com/IQHXG.png)
Untagged RGB images should be opened in Photoshop and have a profile assigned. 99% of the time it's *sRGB*, but if it doesn't look right you can try *Adobe RGB*. It's a guess.
CMYK swatches
-------------
You probably make your swatches as CMYK swatches like most of us do. This is fine, but be aware that *a CMYK color is not an absolute color*. You are "hard coding" the percentages and the color will appear differently when printed according to different standards.
A mistake I often experience is people creating a document without thinking about the CMYK profile and thereby unconsciously choosing *U.S. Web Coated (SWOP) v2* which is standard in Adobe's applications. Then they carefully fine-tune their CMYK swatches until they look as they want on screen. When they export a PDF they suddenly remember that they need to choose the correct color profile. They convert with *Preserve Numbers* to keep the black swatch at 100% black and thereby assign another color profile to the document. All the CMYK values are unchanged, but the intent of the document changes and when they see the document in Acrobat they notice that the colors have shifted.
The colors they see when designing in *U.S. Web Coated (SWOP) v2* might look like this:
[](https://i.stack.imgur.com/znHfk.png)
But after exporting and assigning *Uncoated FOGRA29* the colors look different:
[](https://i.stack.imgur.com/2UNa6.png)
CMYK images with an embedded profile
------------------------------------
Depending on how your *Color Management Policies* is set up, CMYK images with an embedded profile will either be *Preserved*, *Ignored* or *Converted*. You can see a detailed description of each in the *Color Settings* dialogue. I wouldn't recommend for you to place CMYK images unless you know what you are doing and why.
Untagged CMYK images
--------------------
Has the same problem as untagged RGB images. You don't know which profile it was converted to. InDesign just displays the image as if it was printed according to *Document CMYK*. If that profile isn't the same as the image was originally converted to, there will be a shift in colors. Avoid this issue.
Common standards
================
If you are forced to guess which profile to use, here is a list of commonly used profiles.
Europe
------
### Coated paper
* Coated FOGRA39
* ISO Coated v2
* ISO Coated v2 300%
* etc.
### Uncoated paper
* Uncoated FOGRA29
* ISO Uncoated
* PSO Uncoated
* etc.
North America
-------------
*(Americans, help me out here!)*
A way to make a general PDF?
============================
I'm not sure I would recommend it, but if you really want to make documents which could be used on any printer, you could make a mix of RGB and CMYK. Keep the black text as 100% CMYK black and all neutral objects and images in percentages of black. All other objects and images could then be in RGB. This would enable a print house to convert your PDFs to any profile they wish without too much hassle. | I'm not sure what kind of answer you expect here. Sure there are differences. For CMYK settings, the best idea is always to discuss this with the printing service. Often they offer custom profiles that are calibrated to their machines.
For presentations in RGB you usually don't have much control on what device your design will be displayed. in theory AdobeRGB is better than sRGB, but only if the display can really handle it. In general sRGB is fine.
Just don't use CMYK images, when you want to output RGB. |
142,696 | I have not given this too much thought until recently, when a bit of a back and forth happened with a client. So, when I start a new document in InDesign, **for CMYK print**, how to I know how to setup the color settings ?
Many times I will just not look at this and go with whatever is set by default, but apparently this may affect things.
Is this just a case of choosing between the "Europe General Purpose" vs the "North America General Purpose" presets, or is there more to this ?
Are the "Coated FOGRA39"/"US Web Coated (SWOP)" the most widely used standards that will generally work for printers in the EU/US ?
What about web documents in RGB ? Like, when you design a presentation that will not go to a CMYK printer, what's the proper colour space to use for that ?
[](https://i.stack.imgur.com/W9GZ7.jpg)
[](https://i.stack.imgur.com/cHb5b.jpg) | 2020/10/29 | [
"https://graphicdesign.stackexchange.com/questions/142696",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/62949/"
] | Why bother about color profiles?
================================
First of all you need to accept that *different printers follow different standards*. The same CMYK numbers will look differently when printed according to different standards. It's not possible to make a PDF which will be perfect under all circumstances. Unless I absolutely have to, I wouldn't export a PDF for print before knowing where the document will be printed, on which kind of paper and which ICC profile the print house recommends for that paper.
To use the wrong profile can affect the colors on the final print, but even if there is little difference between the profile you choose and the recommended one, there is also a responsibility issue. If you receive a print where you think the colors are a little bit off and the print house discovers that you didn't use the recommended profile, they might park the complaint right there. Always best to keep your path clean.
Setting up your document
========================
Setting up *Working Spaces* in the *Color Settings* affects *new* documents, but you can always change the settings for an existing document later by using *Edit > Assign Profiles*. You can also choose a different profile when exporting a PDF. So you are not confined by what the settings where when you created your document.
The main reason for caring about which profile to use for your InDesign document from the beginning is that it affects the *preview*.
In a print document, when you turn on *View > Overprint Preview* the graphics and images are displayed *as they would look if they were printed according to the Document CMYK*.
RGB swatches
------------
Although all swatches in a print document will be CMYK by default, it's also possible to make RGB swatches. They are assumed to have the RGB profile chosen as *Document RGB* and with *Overprint Preview* turned on they are displayed as if they were converted from that to the CMYK profile chosen as *Document CMYK*.
RGB images with an embedded profile
-----------------------------------
If you are a little in doubt about color profiles and don't know exactly what you are doing and why, I would always recommend to only place RGB images with an embedded color profile. With *Overprint Preview* turned on they are displayed as if they were converted from their embedded RGB profile to the CMYK profile chosen as *Document CMYK*.
For example an RGB image looking like this:
[](https://i.stack.imgur.com/r2UTA.png)
Will look like this with *Document CMYK* set to *Coated FOGRA39*:
[](https://i.stack.imgur.com/ghLFm.png)
But with *Document CMYK* set to *PSO Uncoated*, it will look more faded because the gamut is smaller:
[](https://i.stack.imgur.com/kxZyD.png)
Untagged RGB images
-------------------
RGB images without an embedded profile are a common cause of a shift in colors from screen to print. They are displayed in Adobe's applications as if they had the profile chosen as *Working RGB* in Photoshop or *Document RGB* in InDesign. So if your Photoshop for example has *Adobe RGB* as *Working RGB* and your InDesign document has *sRGB* as *Document RGB*, the untagged images will be displayed differently in those two applications.
Here is how an untagged image (which is is in reality an sRGB image) is displayed when InDesign assumes *sRGB*:
[](https://i.stack.imgur.com/HEr6w.png)
And here is how it looks if InDesign assumes *Adobe RGB*:
[](https://i.stack.imgur.com/IQHXG.png)
Untagged RGB images should be opened in Photoshop and have a profile assigned. 99% of the time it's *sRGB*, but if it doesn't look right you can try *Adobe RGB*. It's a guess.
CMYK swatches
-------------
You probably make your swatches as CMYK swatches like most of us do. This is fine, but be aware that *a CMYK color is not an absolute color*. You are "hard coding" the percentages and the color will appear differently when printed according to different standards.
A mistake I often experience is people creating a document without thinking about the CMYK profile and thereby unconsciously choosing *U.S. Web Coated (SWOP) v2* which is standard in Adobe's applications. Then they carefully fine-tune their CMYK swatches until they look as they want on screen. When they export a PDF they suddenly remember that they need to choose the correct color profile. They convert with *Preserve Numbers* to keep the black swatch at 100% black and thereby assign another color profile to the document. All the CMYK values are unchanged, but the intent of the document changes and when they see the document in Acrobat they notice that the colors have shifted.
The colors they see when designing in *U.S. Web Coated (SWOP) v2* might look like this:
[](https://i.stack.imgur.com/znHfk.png)
But after exporting and assigning *Uncoated FOGRA29* the colors look different:
[](https://i.stack.imgur.com/2UNa6.png)
CMYK images with an embedded profile
------------------------------------
Depending on how your *Color Management Policies* is set up, CMYK images with an embedded profile will either be *Preserved*, *Ignored* or *Converted*. You can see a detailed description of each in the *Color Settings* dialogue. I wouldn't recommend for you to place CMYK images unless you know what you are doing and why.
Untagged CMYK images
--------------------
Has the same problem as untagged RGB images. You don't know which profile it was converted to. InDesign just displays the image as if it was printed according to *Document CMYK*. If that profile isn't the same as the image was originally converted to, there will be a shift in colors. Avoid this issue.
Common standards
================
If you are forced to guess which profile to use, here is a list of commonly used profiles.
Europe
------
### Coated paper
* Coated FOGRA39
* ISO Coated v2
* ISO Coated v2 300%
* etc.
### Uncoated paper
* Uncoated FOGRA29
* ISO Uncoated
* PSO Uncoated
* etc.
North America
-------------
*(Americans, help me out here!)*
A way to make a general PDF?
============================
I'm not sure I would recommend it, but if you really want to make documents which could be used on any printer, you could make a mix of RGB and CMYK. Keep the black text as 100% CMYK black and all neutral objects and images in percentages of black. All other objects and images could then be in RGB. This would enable a print house to convert your PDFs to any profile they wish without too much hassle. | In theory it shouldnt matter\* what your working space is. Its just a indication that you designed the colors with the assumption that the numeric values match this color definition. Its like stating what language you intend to use, a factual statement. Its then the publish cycles job to get it as close as possible to what you designed. If your monitor is calibrated you can then ask the computer to simulate what it would look like on a real printer or in another standard.
You should always design to some standard never to a particular printers calibration unless you never want to repeat your print or your working for the printer fixing colors. Instead, you should simulate that particular printer by setting printers profile as a preview target.
Im intentionally going to ignore how to deliver the file to the printer though. It depends on the printerhouse.
The second section on policies is more important. Unless you are allready in the stage of sending things to print or your preparing to a unusual target like say a laser. Then you want both RGB and CMYK policies to be set to "preserve embedded profiles". Because you want to preserve artwork as the previous designer stated it. Unless your setup is highly unusual and you know what your doing, you dont want to set the preserve numbers option, ever for anything.
While your at it at least check missing profiles to ask.
Now then the next section deals with what do we do when we can not convert your color. It is a bit under apreciated part of the color management system. You have it set to relative colorimetric. This is a somewhat safe bet, though it has a tendency to make people dissapointed with preview and output results. This is partly psycological on you having seen the alernative.
Now i'm not doing much archival work. So me personally i never use relative colorimetric because its the "meh" option. I tend to use absolute colorimetric when i feel i know the border constraints well, perceptual when appropriate and when im feeling bold or i need saturated i use display. The japanese may be on to something ;) But you probably shouldn follow my route.
What standard to use? ISO is ok in europe... Dunno about USA
\* Well it does affect your gamut |
55,064,957 | With my current code, I'm trying to clear the corresponding cells (columns K:N) when the column (C:J) is blank. It's the reference of Rng. I think it's an `If Then` statement but not sure how to fit it within the code... I understand this is long but any help would be fantastic!
For example, if C30:J30 is empty it clears K30:N30. Is it a `If Then` statement with `ClearContents`? Or if C15:J15 is blank then clear K15:N15, etc.
I'm looking for help on clearing cells that are on the same row as the "Active" criteria. But, only after it is copied from "Future Project Hopper" to "CPD-Carryover,Complete&Active". Trying to make sure it's not confusing when I copy/clear C to J and am left with some data in columns K to N. I'm making this for other individuals to use to easily move Active projects from one sheet to another.
```
Const cCrit As Variant = "D" ' Criteria Column Letter/Number
Const cCols As String = "C:J" ' Source/Target Data Columns
Const cFRsrc As Long = 15 ' Source First Row
Dim ws1 As Worksheet ' Source Workbook
Dim ws2 As Worksheet ' Target Workbook
Dim rng As Range ' Filter Range, Copy Range
Dim lRow As Long ' Last Row Number
Dim FRtgt As Long ' Target First Row
Dim Answer As VbMsgBoxResult ' Message Box
Dim Error1 As VbMsgBoxResult ' Message Box for Errors
' Create references to worksheets.
With ThisWorkbook
Set ws1 = .Worksheets("Future Project Hopper")
Set ws2 = .Worksheets("CPD-Carryover,Complete&Active")
End With
Answer = MsgBox("Do you want to run the Macro?", vbYesNo, "Run Macro")
If Answer <> vbYes Then Exit Sub
' In Source Worksheet
With ws1
' Clear any filters.
.AutoFilterMode = False
' Calculate Last Row.
lRow = .Cells(.Rows.Count, cCrit).End(xlUp).row
' Calculate Filter Column Range.
Set rng = .Cells(cFRsrc, cCrit).Resize(lRow - cFRsrc + 1)
' Make an offset for the filter to start a row before (above) and
' end a row after (below).
With rng.Offset(-1).Resize(lRow - cFRsrc + 3)
' Filter data in Criteria Column.
.AutoFilter Field:=1, Criteria1:="Active"
End With
' Create a reference to the Copy Range.
Set rng = .Columns(cCols).Resize(rng.Rows.Count).Offset(cFRsrc - 1) _
.SpecialCells(xlCellTypeVisible)
' Clear remaining filters.
.AutoFilterMode = False
End With
' Calculate Target First Row.
FRtgt = ws2.Cells(ws2.Rows.Count, cCrit).End(xlUp).row + 1
' Copy Range and paste to Target Worksheet and clear contents of future project hopper
rng.Copy
ws2.Columns(cCols).Resize(1).Offset(FRtgt - 1).PasteSpecial xlPasteValues
rng.Rows.ClearContents
``` | 2019/03/08 | [
"https://Stackoverflow.com/questions/55064957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10964535/"
] | That's because `www.amazon.de` *is* a relative link. To link a different domain (host), you need to begin the [authority component](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax) with double slashes: `//www.amazon.de`, or with the scheme included `https://www.amazon.de`. | You have to add the protocol ('https://') to the link:
```
document.getElementById('linkname').setAttribute("href", "https://www.amazon.de");
``` |
55,064,957 | With my current code, I'm trying to clear the corresponding cells (columns K:N) when the column (C:J) is blank. It's the reference of Rng. I think it's an `If Then` statement but not sure how to fit it within the code... I understand this is long but any help would be fantastic!
For example, if C30:J30 is empty it clears K30:N30. Is it a `If Then` statement with `ClearContents`? Or if C15:J15 is blank then clear K15:N15, etc.
I'm looking for help on clearing cells that are on the same row as the "Active" criteria. But, only after it is copied from "Future Project Hopper" to "CPD-Carryover,Complete&Active". Trying to make sure it's not confusing when I copy/clear C to J and am left with some data in columns K to N. I'm making this for other individuals to use to easily move Active projects from one sheet to another.
```
Const cCrit As Variant = "D" ' Criteria Column Letter/Number
Const cCols As String = "C:J" ' Source/Target Data Columns
Const cFRsrc As Long = 15 ' Source First Row
Dim ws1 As Worksheet ' Source Workbook
Dim ws2 As Worksheet ' Target Workbook
Dim rng As Range ' Filter Range, Copy Range
Dim lRow As Long ' Last Row Number
Dim FRtgt As Long ' Target First Row
Dim Answer As VbMsgBoxResult ' Message Box
Dim Error1 As VbMsgBoxResult ' Message Box for Errors
' Create references to worksheets.
With ThisWorkbook
Set ws1 = .Worksheets("Future Project Hopper")
Set ws2 = .Worksheets("CPD-Carryover,Complete&Active")
End With
Answer = MsgBox("Do you want to run the Macro?", vbYesNo, "Run Macro")
If Answer <> vbYes Then Exit Sub
' In Source Worksheet
With ws1
' Clear any filters.
.AutoFilterMode = False
' Calculate Last Row.
lRow = .Cells(.Rows.Count, cCrit).End(xlUp).row
' Calculate Filter Column Range.
Set rng = .Cells(cFRsrc, cCrit).Resize(lRow - cFRsrc + 1)
' Make an offset for the filter to start a row before (above) and
' end a row after (below).
With rng.Offset(-1).Resize(lRow - cFRsrc + 3)
' Filter data in Criteria Column.
.AutoFilter Field:=1, Criteria1:="Active"
End With
' Create a reference to the Copy Range.
Set rng = .Columns(cCols).Resize(rng.Rows.Count).Offset(cFRsrc - 1) _
.SpecialCells(xlCellTypeVisible)
' Clear remaining filters.
.AutoFilterMode = False
End With
' Calculate Target First Row.
FRtgt = ws2.Cells(ws2.Rows.Count, cCrit).End(xlUp).row + 1
' Copy Range and paste to Target Worksheet and clear contents of future project hopper
rng.Copy
ws2.Columns(cCols).Resize(1).Offset(FRtgt - 1).PasteSpecial xlPasteValues
rng.Rows.ClearContents
``` | 2019/03/08 | [
"https://Stackoverflow.com/questions/55064957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10964535/"
] | You have to add the protocol ('https://') to the link:
```
document.getElementById('linkname').setAttribute("href", "https://www.amazon.de");
``` | It seems you are missing 'http://' or 'https://' |
55,064,957 | With my current code, I'm trying to clear the corresponding cells (columns K:N) when the column (C:J) is blank. It's the reference of Rng. I think it's an `If Then` statement but not sure how to fit it within the code... I understand this is long but any help would be fantastic!
For example, if C30:J30 is empty it clears K30:N30. Is it a `If Then` statement with `ClearContents`? Or if C15:J15 is blank then clear K15:N15, etc.
I'm looking for help on clearing cells that are on the same row as the "Active" criteria. But, only after it is copied from "Future Project Hopper" to "CPD-Carryover,Complete&Active". Trying to make sure it's not confusing when I copy/clear C to J and am left with some data in columns K to N. I'm making this for other individuals to use to easily move Active projects from one sheet to another.
```
Const cCrit As Variant = "D" ' Criteria Column Letter/Number
Const cCols As String = "C:J" ' Source/Target Data Columns
Const cFRsrc As Long = 15 ' Source First Row
Dim ws1 As Worksheet ' Source Workbook
Dim ws2 As Worksheet ' Target Workbook
Dim rng As Range ' Filter Range, Copy Range
Dim lRow As Long ' Last Row Number
Dim FRtgt As Long ' Target First Row
Dim Answer As VbMsgBoxResult ' Message Box
Dim Error1 As VbMsgBoxResult ' Message Box for Errors
' Create references to worksheets.
With ThisWorkbook
Set ws1 = .Worksheets("Future Project Hopper")
Set ws2 = .Worksheets("CPD-Carryover,Complete&Active")
End With
Answer = MsgBox("Do you want to run the Macro?", vbYesNo, "Run Macro")
If Answer <> vbYes Then Exit Sub
' In Source Worksheet
With ws1
' Clear any filters.
.AutoFilterMode = False
' Calculate Last Row.
lRow = .Cells(.Rows.Count, cCrit).End(xlUp).row
' Calculate Filter Column Range.
Set rng = .Cells(cFRsrc, cCrit).Resize(lRow - cFRsrc + 1)
' Make an offset for the filter to start a row before (above) and
' end a row after (below).
With rng.Offset(-1).Resize(lRow - cFRsrc + 3)
' Filter data in Criteria Column.
.AutoFilter Field:=1, Criteria1:="Active"
End With
' Create a reference to the Copy Range.
Set rng = .Columns(cCols).Resize(rng.Rows.Count).Offset(cFRsrc - 1) _
.SpecialCells(xlCellTypeVisible)
' Clear remaining filters.
.AutoFilterMode = False
End With
' Calculate Target First Row.
FRtgt = ws2.Cells(ws2.Rows.Count, cCrit).End(xlUp).row + 1
' Copy Range and paste to Target Worksheet and clear contents of future project hopper
rng.Copy
ws2.Columns(cCols).Resize(1).Offset(FRtgt - 1).PasteSpecial xlPasteValues
rng.Rows.ClearContents
``` | 2019/03/08 | [
"https://Stackoverflow.com/questions/55064957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10964535/"
] | That's because `www.amazon.de` *is* a relative link. To link a different domain (host), you need to begin the [authority component](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax) with double slashes: `//www.amazon.de`, or with the scheme included `https://www.amazon.de`. | It seems you are missing 'http://' or 'https://' |
3,701,329 | If $\dfrac{z-\alpha}{z+\alpha},(\alpha \in R)$ is a purely imaginary number and $|z|=2$, then find value of $\alpha$.
Now I took $\dfrac{z-\alpha}{z+\alpha}=t$ and as t is purely imaginary, and use the fact that $t+ \bar{t}=0$ and obtained the answer $\alpha = \pm2$.
But I was wondering that if there is any way to think about the answer more directly using geometry of complex numbers given that $z$ lies on a circle centered at origin having radius $2$. | 2020/06/01 | [
"https://math.stackexchange.com/questions/3701329",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/290994/"
] | Consider the open cover $\{X\}$. This is a finite open cover of every subset of $X$. So your modified notion would apply to every set.
---
That said, there is a version of this notion which is nontrivial: what if we bound the sizes of the open sets involved? (Note that this is a fundamentally *metric*, as opposed to *topological*, idea.) Specifically, consider the following property:
>
> For each $\epsilon>0$ there is a finite cover of $X$ consisting only of open sets with diameter $<\epsilon$.
>
>
>
Here the diameter of an open set $U$ is the supremum of the distances between elements of that set:$$diam(U)=\sup\{d(a,b): a,b\in U\}.$$
This is no longer trivial - e.g. $\mathbb{R}$ with the usual metric does *not* have this property. But this is still very different from compactness. | If you do that, then **every** subset of $E$ of $X$ has that property. Just take the open cover $\{X\}$ of $E$. It has a finite subcover (itself). |
39,884,860 | boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code?
```
public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){
//page = 0 //Actual is 0, Expected increment by 1.
}
```
Any help should be appreciable.
After implementing **Alan** answers having the following issues,
1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity).
<http://localhost:8180/api/v1/books/?page=3&size=2>
**Response**
```
{
"content": [
{
"id": "57da9eadbee83fb037a66029",
.
.
.
}{
.
.
.
}
],
"last": false,
"totalElements": 5,
"totalPages": 3,
"size": 2,
"number": 2, //strange always getting 1 less than page number.
"sort": null,
"first": true,
"numberOfElements": 2
}
```
2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index. | 2016/10/05 | [
"https://Stackoverflow.com/questions/39884860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656056/"
] | Spring Boot will be using Spring Data under the covers.
The Spring Data class you need to configure is the following:
org.springframework.data.web.PageableHandlerMethodArgumentResolver
and in particular the following method:
<http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/web/PageableHandlerMethodArgumentResolver.html#setOneIndexedParameters-boolean->
This will allow you to use you current UI paging as is i.e. with first page = 1.
In a Boot application I think the config may look something like:
```
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setOneIndexedParameters(true);
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
}
``` | To get better result, you need to extend RepositoryRestMvcConfiguration, like below
```
@Configuration
public class RespositoryConfiguration extends RepositoryRestMvcConfiguration {
@Override
@Bean
public HateoasPageableHandlerMethodArgumentResolver pageableResolver() {
HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver();
resolver.setOneIndexedParameters(true);
return resolver;
}
}
```
Then you shall get all the links and pagination information correct except 'number', which is one less.
See the result for page=1,
```
"_links": {
"first": {
"href": "http://localhost:8080/user/user?page=1&size=5"
},
"self": {
"href": "http://localhost:8080/user/user"
},
"next": {
"href": "http://localhost:8080/user/user?page=2&size=5"
},
"last": {
"href": "http://localhost:8080/user/user?page=2&size=5"
}
},
"page": {
"size": 5,
"totalElements": 6,
"totalPages": 2,
"number": 0
}
``` |
39,884,860 | boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code?
```
public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){
//page = 0 //Actual is 0, Expected increment by 1.
}
```
Any help should be appreciable.
After implementing **Alan** answers having the following issues,
1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity).
<http://localhost:8180/api/v1/books/?page=3&size=2>
**Response**
```
{
"content": [
{
"id": "57da9eadbee83fb037a66029",
.
.
.
}{
.
.
.
}
],
"last": false,
"totalElements": 5,
"totalPages": 3,
"size": 2,
"number": 2, //strange always getting 1 less than page number.
"sort": null,
"first": true,
"numberOfElements": 2
}
```
2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index. | 2016/10/05 | [
"https://Stackoverflow.com/questions/39884860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656056/"
] | If you are using Spring Boot 2.X you could switch from `WebMvcConfigurerAdapter` to application properties. There is a set of properties to configure pageable:
```
# DATA WEB (SpringDataWebProperties)
spring.data.web.pageable.default-page-size=20 # Default page size.
spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted.
spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes.
spring.data.web.pageable.page-parameter=page # Page index parameter name.
spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters.
spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties.
spring.data.web.pageable.size-parameter=size # Page size parameter name.
spring.data.web.sort.sort-parameter=sort # Sort parameter name.
```
But please remember that even if you change the `one-indexed-parameter` the page response (`PageImpl` class) will return results with zero-based page number. It could be a little misleading. | Spring Boot will be using Spring Data under the covers.
The Spring Data class you need to configure is the following:
org.springframework.data.web.PageableHandlerMethodArgumentResolver
and in particular the following method:
<http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/web/PageableHandlerMethodArgumentResolver.html#setOneIndexedParameters-boolean->
This will allow you to use you current UI paging as is i.e. with first page = 1.
In a Boot application I think the config may look something like:
```
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setOneIndexedParameters(true);
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
}
``` |
39,884,860 | boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code?
```
public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){
//page = 0 //Actual is 0, Expected increment by 1.
}
```
Any help should be appreciable.
After implementing **Alan** answers having the following issues,
1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity).
<http://localhost:8180/api/v1/books/?page=3&size=2>
**Response**
```
{
"content": [
{
"id": "57da9eadbee83fb037a66029",
.
.
.
}{
.
.
.
}
],
"last": false,
"totalElements": 5,
"totalPages": 3,
"size": 2,
"number": 2, //strange always getting 1 less than page number.
"sort": null,
"first": true,
"numberOfElements": 2
}
```
2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index. | 2016/10/05 | [
"https://Stackoverflow.com/questions/39884860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656056/"
] | Spring added this future as well. Just make oneIndexed parameter equals to true in your configuration file and pagination will start from page 1.By default its false and pagination starts from 0.
```
spring.data.web.pageable.one-indexed-parameters=true
``` | Spring Boot will be using Spring Data under the covers.
The Spring Data class you need to configure is the following:
org.springframework.data.web.PageableHandlerMethodArgumentResolver
and in particular the following method:
<http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/web/PageableHandlerMethodArgumentResolver.html#setOneIndexedParameters-boolean->
This will allow you to use you current UI paging as is i.e. with first page = 1.
In a Boot application I think the config may look something like:
```
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
resolver.setOneIndexedParameters(true);
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
}
``` |
39,884,860 | boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code?
```
public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){
//page = 0 //Actual is 0, Expected increment by 1.
}
```
Any help should be appreciable.
After implementing **Alan** answers having the following issues,
1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity).
<http://localhost:8180/api/v1/books/?page=3&size=2>
**Response**
```
{
"content": [
{
"id": "57da9eadbee83fb037a66029",
.
.
.
}{
.
.
.
}
],
"last": false,
"totalElements": 5,
"totalPages": 3,
"size": 2,
"number": 2, //strange always getting 1 less than page number.
"sort": null,
"first": true,
"numberOfElements": 2
}
```
2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index. | 2016/10/05 | [
"https://Stackoverflow.com/questions/39884860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656056/"
] | If you are using Spring Boot 2.X you could switch from `WebMvcConfigurerAdapter` to application properties. There is a set of properties to configure pageable:
```
# DATA WEB (SpringDataWebProperties)
spring.data.web.pageable.default-page-size=20 # Default page size.
spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted.
spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes.
spring.data.web.pageable.page-parameter=page # Page index parameter name.
spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters.
spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties.
spring.data.web.pageable.size-parameter=size # Page size parameter name.
spring.data.web.sort.sort-parameter=sort # Sort parameter name.
```
But please remember that even if you change the `one-indexed-parameter` the page response (`PageImpl` class) will return results with zero-based page number. It could be a little misleading. | To get better result, you need to extend RepositoryRestMvcConfiguration, like below
```
@Configuration
public class RespositoryConfiguration extends RepositoryRestMvcConfiguration {
@Override
@Bean
public HateoasPageableHandlerMethodArgumentResolver pageableResolver() {
HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver();
resolver.setOneIndexedParameters(true);
return resolver;
}
}
```
Then you shall get all the links and pagination information correct except 'number', which is one less.
See the result for page=1,
```
"_links": {
"first": {
"href": "http://localhost:8080/user/user?page=1&size=5"
},
"self": {
"href": "http://localhost:8080/user/user"
},
"next": {
"href": "http://localhost:8080/user/user?page=2&size=5"
},
"last": {
"href": "http://localhost:8080/user/user?page=2&size=5"
}
},
"page": {
"size": 5,
"totalElements": 6,
"totalPages": 2,
"number": 0
}
``` |
39,884,860 | boot(1.4.0) "Pageable" for pagination.It works fine without any issue.But by default the page value starts from "0" but in the front-end the page value starts from "1". So is there any standard approach to increment value instead of manually increment the page number inside the code?
```
public Page<Device> find(DeviceFindCommand deviceFindCommand, Pageable pageable){
//page = 0 //Actual is 0, Expected increment by 1.
}
```
Any help should be appreciable.
After implementing **Alan** answers having the following issues,
1) Still i am able to access zero page which returns the first page(I don't know this is issue or not but i want to get a better clarity).
<http://localhost:8180/api/v1/books/?page=3&size=2>
**Response**
```
{
"content": [
{
"id": "57da9eadbee83fb037a66029",
.
.
.
}{
.
.
.
}
],
"last": false,
"totalElements": 5,
"totalPages": 3,
"size": 2,
"number": 2, //strange always getting 1 less than page number.
"sort": null,
"first": true,
"numberOfElements": 2
}
```
2) **"number": 2,** in the response always getting one less than the page number.It should return the current page index. | 2016/10/05 | [
"https://Stackoverflow.com/questions/39884860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656056/"
] | Spring added this future as well. Just make oneIndexed parameter equals to true in your configuration file and pagination will start from page 1.By default its false and pagination starts from 0.
```
spring.data.web.pageable.one-indexed-parameters=true
``` | To get better result, you need to extend RepositoryRestMvcConfiguration, like below
```
@Configuration
public class RespositoryConfiguration extends RepositoryRestMvcConfiguration {
@Override
@Bean
public HateoasPageableHandlerMethodArgumentResolver pageableResolver() {
HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver();
resolver.setOneIndexedParameters(true);
return resolver;
}
}
```
Then you shall get all the links and pagination information correct except 'number', which is one less.
See the result for page=1,
```
"_links": {
"first": {
"href": "http://localhost:8080/user/user?page=1&size=5"
},
"self": {
"href": "http://localhost:8080/user/user"
},
"next": {
"href": "http://localhost:8080/user/user?page=2&size=5"
},
"last": {
"href": "http://localhost:8080/user/user?page=2&size=5"
}
},
"page": {
"size": 5,
"totalElements": 6,
"totalPages": 2,
"number": 0
}
``` |
66,991,986 | I have one pandas dataframe and one geopandas dataframe. In the Pandas dataframe, I have a column *Points* that contains `shapely.geometry` `Point` objects. The *geometry* column in the geopandas frame has `Polygon` objects. What I would like to do is take a `Point` in the Pandas frame and test to see if it is `within` **any** of the `Polygon` objects in the geopandas frame.
In a new column in the pandas frame, I would like the following. If the `Point` is within a given `Polygon` (i.e. `within` call returns `True`), I would like the new column's value at the `Point`'s row to be the value of a different column in the `Polygon`'s row in the geopandas frame.
I have a working solution to this problem, but it is not vectorized. Is it possible to vectorize it?
Example:
```py
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point, Polygon
# Create random frame, geometries are supposed to be mutually exclusive
gdf = gpd.GeoDataFrame({'A': [1, 2], 'geometry': [Polygon([(10, 5), (5, 6)]), Polygon([(1,2), (2, 5))]})
# Create random pandas
df = pd.DataFrame({'Foo': ['bar', 'Bar'], 'Points': [Point(4, 5), Point(1, 2)]})
# My non-vectorized solution
df['new'] = ''
for i in df.index:
for j in gdf.index:
if df.at[i, 'Points'].within(gdf.at[j, 'geometry']):
df.at[i, 'new'] = gdf.at[j, 'A']
```
This works fine, so that `df['new']` will contain whatever is in column `gdf['A']` when the point is within the polygon. I am hoping that there may be a way for me to vectorize this operation. | 2021/04/07 | [
"https://Stackoverflow.com/questions/66991986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3934100/"
] | You can calculate the Euclidean distance between all the points of the `Points` and `Polygon`. And, wherever the distance is equal to 0, this would give you an intersection point. My approach is below. Note that, I leave the part of getting all the points and the polygon points from your data frames to you. Probably, a function like `pandas.Series.toList` should provide that.
```
import numpy as np
from scipy.spatial.distance import cdist
polygon = [[10,5],[5,6],[1,2],[2,5]]
points = [[4,5],[1,2]]
# return distances between all the items of the two arrays
distances = cdist(polygon,points)
print(distances)
```
```
[[6. 9.48683298]
[1.41421356 5.65685425]
[4.24264069 0. ]
[2. 3.16227766]]
```
All we have to do now, is to get the index of 0s in the array. As you can see, our intersection point is at the 3rd row and the 2nd column, which is the 3rd item of the polygon or the 2nd item of the points.
```
for i,dist in enumerate(distances.flatten()):
if dist==0:
intersect_index = np.unravel_index(i,shape=distances.shape)
intersect_point = polygon[intersect_index[0]]
print(intersect_point)
```
```
[1,2]
```
This should give you the vectorized form you are looking for. | I found a solution that works for my purposes. Not the most elegant, but still much faster than looping.
```py
def within_vectorized(array, point):
# Create array of False and True values
_array = np.array([point.within(p) for p in array])
# When the first element of np.where tuple is not empty
if np.where(_array)[0].size != 0:
return np.where(_array)[0][0]
else:
return -1
# Create dummy value row geopandas frame
# This will have an empty Polygon object in the geometry column and NaN's everywhere else
dummy_values = np.empty((1, gdf.shape[1]))
dummy_values[:] = np.nan
dummy_values = dummy_values.tolist()[0]
dummy_values[-1] = Polygon()
gdf.loc[-1] = dummy_values
# Use loc where index is retrieved by calling vectorized function
df['A'] = gdf.loc[df['Point'].apply(lambda x: within_vectorized(gdf['geometry'], x)), 'A'].to_list()
``` |
59,370,781 | I built a excel macro using the "Microsoft Outlook 15.0 Object Library" reference, but when I send the file to other people they get this error: "***Can’t find project or library***".
This file will be used by a lot of people, so I have to add it from VBA Code.
I'm using this code that runs when you open the excel file, which is returning the following error: "***Error in loading DLL***"
```
Private Sub Workbook_Open()
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office15\MSOUTL.OLB\"
End Sub
```
Do you have any idea why this is happening?
Thanks | 2019/12/17 | [
"https://Stackoverflow.com/questions/59370781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7920914/"
] | If you still want to keep the early binding you could use the GUID in order to add the libray, i.e.
```
Sub AddOL_Ref()
Application.VBE.ActiveVBProject.REFERENCES. _
AddFromGuid "{00062FFF-0000-0000-C000-000000000046}", 1, 0
End Sub
```
Advantage of using the GUID is that it is constant and does not change with the version of the program.
[Here](https://www.excelcise.org/add-or-remove-object-library-reference-via-vba/) one finds an extened discussion on dis/advantages of early resp. late binding. | You will have to remove the references & use late binding
or you can also try this. Send your code to one of the user having 2010MS.
**Goto VBA > Tools > References**
Check for any missing references. You may have ***Microsoft Outlook 15.0 Object Library*** showing as missing. Un-check this, browse down and select ***Microsoft Outlook 14.0 Object Library***. |
4,926,383 | I am tring to display all my products within their category, so something like:
Category Name1
Product Name1, Product Name2 ...
Category Name2
Product Name3, Product Name4 ...
I am using oscommerce, So the database structure is not my choice. The database tables I need to use are
products\_to\_categories: holds the products\_id and categories\_id
products\_description:holds products\_id and products\_name (other info in this table are not important)
category\_description: holds the categories\_id and categories\_name
I have tried everything and i only can get to echo the products (all together) and categories all together, but I can't get them in a way that all the products within a category sit under the specified name
As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products
I really hope you can help
thanks | 2011/02/07 | [
"https://Stackoverflow.com/questions/4926383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420941/"
] | I dont understand fully how you want to display. I hope you like to display like this
```
Category Name1
Product Name1
Product Name2
Category Name2
Product Name3
Product Name4
```
Easiest way i think, get distinct list of category in an array.
with cat id and cat name
Loop that array and print products for each Category.
If category list is huge storing it in array and looping will be a bad idea. | You'll likely need a `LEFT JOIN` in your SQL, to merge the three tables together, and order the query by `category_name, product_name`.
Something like:
```
SELECT p.product_id, p.product_name, c.category_name FROM `products_description` p
LEFT JOIN `products_to_categories` linker ON linker.product_id=p.product_id
LEFT JOIN `category_description` c ON linker.category_id=c.category_id
ORDER BY c.category_name, p.product_name
```
Then your PHP to output the list would be something like:
```
$data = array(); // Data from query above
$cur_category = '';
foreach($data as $product) {
if ($product['category_name'] != $cur_category) {
// Category changed; display it
echo $product['category_name'].": ";
$cur_category = $product['category_name'];
}
echo $product['product_name'].", ";
}
``` |
4,926,383 | I am tring to display all my products within their category, so something like:
Category Name1
Product Name1, Product Name2 ...
Category Name2
Product Name3, Product Name4 ...
I am using oscommerce, So the database structure is not my choice. The database tables I need to use are
products\_to\_categories: holds the products\_id and categories\_id
products\_description:holds products\_id and products\_name (other info in this table are not important)
category\_description: holds the categories\_id and categories\_name
I have tried everything and i only can get to echo the products (all together) and categories all together, but I can't get them in a way that all the products within a category sit under the specified name
As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products
I really hope you can help
thanks | 2011/02/07 | [
"https://Stackoverflow.com/questions/4926383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420941/"
] | There are two ways of approaching this, and the idea behind is was already given as an answer here, by Zod.
The first way is using category\_description to get **all** categories (whether it's full of products or not), the second way is to only extract categories that are used (i.e., not getting a complete list of categories). I'll go through the first way; getting all categories.
Run through category\_description, and get the IDs and category names into an Array.
Now, run through that array with `foreach` and grab all product\_ids from products\_to\_categories. (`SELECT products_id FROM products_to_categories WHERE categories_id=[CATEGORY ID GOES HERE]`).
Now that you have your product IDs that are associated with the concurrent category, you can run through the products\_description and get their name. Essentially, your code should look like:
```
foreach ($categories as $category) {
...display category name and run code to get product ids...
foreach ($products as $product) {
...get product name from products_description...
...display product name...
}
}
``` | You'll likely need a `LEFT JOIN` in your SQL, to merge the three tables together, and order the query by `category_name, product_name`.
Something like:
```
SELECT p.product_id, p.product_name, c.category_name FROM `products_description` p
LEFT JOIN `products_to_categories` linker ON linker.product_id=p.product_id
LEFT JOIN `category_description` c ON linker.category_id=c.category_id
ORDER BY c.category_name, p.product_name
```
Then your PHP to output the list would be something like:
```
$data = array(); // Data from query above
$cur_category = '';
foreach($data as $product) {
if ($product['category_name'] != $cur_category) {
// Category changed; display it
echo $product['category_name'].": ";
$cur_category = $product['category_name'];
}
echo $product['product_name'].", ";
}
``` |
4,926,383 | I am tring to display all my products within their category, so something like:
Category Name1
Product Name1, Product Name2 ...
Category Name2
Product Name3, Product Name4 ...
I am using oscommerce, So the database structure is not my choice. The database tables I need to use are
products\_to\_categories: holds the products\_id and categories\_id
products\_description:holds products\_id and products\_name (other info in this table are not important)
category\_description: holds the categories\_id and categories\_name
I have tried everything and i only can get to echo the products (all together) and categories all together, but I can't get them in a way that all the products within a category sit under the specified name
As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products
I really hope you can help
thanks | 2011/02/07 | [
"https://Stackoverflow.com/questions/4926383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420941/"
] | There are two ways of approaching this, and the idea behind is was already given as an answer here, by Zod.
The first way is using category\_description to get **all** categories (whether it's full of products or not), the second way is to only extract categories that are used (i.e., not getting a complete list of categories). I'll go through the first way; getting all categories.
Run through category\_description, and get the IDs and category names into an Array.
Now, run through that array with `foreach` and grab all product\_ids from products\_to\_categories. (`SELECT products_id FROM products_to_categories WHERE categories_id=[CATEGORY ID GOES HERE]`).
Now that you have your product IDs that are associated with the concurrent category, you can run through the products\_description and get their name. Essentially, your code should look like:
```
foreach ($categories as $category) {
...display category name and run code to get product ids...
foreach ($products as $product) {
...get product name from products_description...
...display product name...
}
}
``` | I dont understand fully how you want to display. I hope you like to display like this
```
Category Name1
Product Name1
Product Name2
Category Name2
Product Name3
Product Name4
```
Easiest way i think, get distinct list of category in an array.
with cat id and cat name
Loop that array and print products for each Category.
If category list is huge storing it in array and looping will be a bad idea. |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | In CSS3, you can use the `::selection` declaration.
```
::selection { background: #00FF00; }
``` | There are many ways, but the easiest all use CSS. Read up on CSS background-color and CSS3 hover. |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | You can use `::selection` CSS to achieve this.
Eg:
```css
::selection {
background:#fff;
color:red;
}
``` | In CSS3, you can use the `::selection` declaration.
```
::selection { background: #00FF00; }
``` |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | In CSS3, you can use the `::selection` declaration.
```
::selection { background: #00FF00; }
``` | ```css
html,body{
background-color: #fff;
}
h1,p{
color: #000;
}
::selection{
background-color: #000;
color: #fff;
}
```
```html
<html>
<head>
<title> Trial </title>
</head>
<body>
<h1> This is the trial header</h1>
<p> This is the trial paragraph </p>
</body>
</html>
``` |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | In CSS3, you can use the `::selection` declaration.
```
::selection { background: #00FF00; }
``` | It can be done with the`::selection` CSS pseudo-element.
for example:
```
p::selection {
background:red;
}
``` |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | You can use `::selection` CSS to achieve this.
Eg:
```css
::selection {
background:#fff;
color:red;
}
``` | There are many ways, but the easiest all use CSS. Read up on CSS background-color and CSS3 hover. |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | You can use `::selection` CSS to achieve this.
Eg:
```css
::selection {
background:#fff;
color:red;
}
``` | ```css
html,body{
background-color: #fff;
}
h1,p{
color: #000;
}
::selection{
background-color: #000;
color: #fff;
}
```
```html
<html>
<head>
<title> Trial </title>
</head>
<body>
<h1> This is the trial header</h1>
<p> This is the trial paragraph </p>
</body>
</html>
``` |
5,747,820 | How can I change the background color from selected text? Like selecting this question but instead of a blue background and white text, a white background and red, blue, white etc. text.
Thanks, VVW | 2011/04/21 | [
"https://Stackoverflow.com/questions/5747820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665168/"
] | You can use `::selection` CSS to achieve this.
Eg:
```css
::selection {
background:#fff;
color:red;
}
``` | It can be done with the`::selection` CSS pseudo-element.
for example:
```
p::selection {
background:red;
}
``` |
1,066,784 | I am really stuck with this problem, and I cannot come out with a solution.
I know that to prove a relation is an equivalence relation we have to prove that it's reflexive, symmetric and transitive, but in this case I don't know how, maybe because I don't much experience (but this exercise should be easy)
This is the relation:
$S=\{(x,y) \in \mathbb{R}\times \mathbb{R}|x - y \in \mathbb{Q} \}$ | 2014/12/13 | [
"https://math.stackexchange.com/questions/1066784",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | This is Proposition 9.2 on p. 212 of *Elements of Algebraic Coding Theory* by L. R. Vermani.
>
> **Definiton 9.2**
>
>
> We have shown that linear $[n, 1, n]$, $[n, n- 1, 2]$ and $[n, n, 1]$ codes exist
> over any finite field $F$ and these are MDS codes. These are called trivial MDS
> codes.
>
>
> **Proposition 9.2**
>
>
> The only binary MDS codes are the trivial codes.
>
>
> ***Proof***
>
>
> Let $C$ be a binary $[n, k, d]$ MDS code. If $k = 1$, then $C$ is a trivial MDS code and
> so we may suppose that $k > 1$. Let $G$ be a generator matrix of $C$ with the first
> $k$ columns of $G$ forming the identity matrix. If $n > k + 1$, then $C$ has a column,
> say $j$th, of weight less than $k$ and greater than $1$. Suppose that the $i$th entry
> of this column is $0$. Then the first $k$ columns of $G$ except the $i$th together
> with the $j$th column are linearly dependent. This proves that $C$ cannot be an
> MDS code. Hence
>
>
> $$k \le n \le k + 1$$
>
>
> and $C$ is a trivial MDS code.
>
>
> | The only binary codes that are MDS are the trivial (n, n, 1) universe codes, the (n, n − 1, 2) single-parity-check (SPC) codes, and the (n, 1, n) repetition codes.
<http://web.stanford.edu/class/ee392d/Chap8.pdf> |
1,066,784 | I am really stuck with this problem, and I cannot come out with a solution.
I know that to prove a relation is an equivalence relation we have to prove that it's reflexive, symmetric and transitive, but in this case I don't know how, maybe because I don't much experience (but this exercise should be easy)
This is the relation:
$S=\{(x,y) \in \mathbb{R}\times \mathbb{R}|x - y \in \mathbb{Q} \}$ | 2014/12/13 | [
"https://math.stackexchange.com/questions/1066784",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Let $G$ be the generator matrix of the code in standard form $[I\_k|A]$ where $A$ is a $k \times (n - k)$ matrix. Since the minimum weight of the code is $d = n - k + 1$, all entries of $A$ are non-zero, and hence $A$ is the all one matrix. If $A$ has only one row, then $k = 1$ and the parameters of the code are $[n, 1, n]$. So, say that $A$ has at least two rows. The sum of first two rows is a vector of weight $2$ which is a codeword. Therefore, $d = n - k + 1 \leq 2$, which shows that $n = k$ or $n = k + 1$. For both cases we have a trivial code, of parameters $[n, n, 1]$ and $[n, n-1, 2]$, respectively. | The only binary codes that are MDS are the trivial (n, n, 1) universe codes, the (n, n − 1, 2) single-parity-check (SPC) codes, and the (n, 1, n) repetition codes.
<http://web.stanford.edu/class/ee392d/Chap8.pdf> |
373,043 | when I open up the terminal and write the command
```
cd Desktop
```
also I have tried
```
cd /Desktop
```
a message appears that no file or directory was found what I suppose to do? I have logged in as a root but still have the same problem any help? | 2013/11/08 | [
"https://askubuntu.com/questions/373043",
"https://askubuntu.com",
"https://askubuntu.com/users/212740/"
] | To enter your user's Desktop directory, run `cd ~/Desktop` (the `~` is expanded into your user's home directory). If your Desktop directory doesn't exist, you can create it via `mkdir ~/Desktop`. | Run this command in terminal,it will help you.
```
cd ~/Desktop
gcc yourfilename.c
``` |
373,043 | when I open up the terminal and write the command
```
cd Desktop
```
also I have tried
```
cd /Desktop
```
a message appears that no file or directory was found what I suppose to do? I have logged in as a root but still have the same problem any help? | 2013/11/08 | [
"https://askubuntu.com/questions/373043",
"https://askubuntu.com",
"https://askubuntu.com/users/212740/"
] | To enter your user's Desktop directory, run `cd ~/Desktop` (the `~` is expanded into your user's home directory). If your Desktop directory doesn't exist, you can create it via `mkdir ~/Desktop`. | `cd Desktop/` Goes to the Desktop directory if you are in your home directory.
`cd -` Goes back to previous directory.
`cd /` Take you to the root directory.
`cd ~/Desktop` Will take you to your Desktop Directory no matter where you are. |
373,043 | when I open up the terminal and write the command
```
cd Desktop
```
also I have tried
```
cd /Desktop
```
a message appears that no file or directory was found what I suppose to do? I have logged in as a root but still have the same problem any help? | 2013/11/08 | [
"https://askubuntu.com/questions/373043",
"https://askubuntu.com",
"https://askubuntu.com/users/212740/"
] | `cd Desktop/` Goes to the Desktop directory if you are in your home directory.
`cd -` Goes back to previous directory.
`cd /` Take you to the root directory.
`cd ~/Desktop` Will take you to your Desktop Directory no matter where you are. | Run this command in terminal,it will help you.
```
cd ~/Desktop
gcc yourfilename.c
``` |
49,693,393 | I can't find out if the below is possible. I want to run an update statement in one database from another database. I know that I can save a query and run that from the master database but I thought the below would be possible
```
UPDATE tblOne
INNER JOIN tblTwo
ON tblOne.[TID] = tblTwo.TID
SET tblTwo.PC = [tblOne].[PC]
from tblOne in 'C:\DB.mdb' ;
```
Any help would be greatly appreciated | 2018/04/06 | [
"https://Stackoverflow.com/questions/49693393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342483/"
] | Per the [MSDN Documentation](https://msdn.microsoft.com/en-us/library/bb177907(v=office.12).aspx), the `IN` clause is only compatible when used in conjunction with the `SELECT` statement (i.e. Select queries), `INSERT INTO` statement (i.e. Append queries), or `SELECT INTO` statement (i.e. Make Table queries) - it cannot be used as part of an `UPDATE` statement.
I would suggest that you import `tblOne` as a linked table in the database in which you intend to execute your `UPDATE` query - this will also result in improved performance over the use of the `IN` clause.
To link the table, select **Access Database** from the **Import** panel of the **External Data** ribbon tab, and then select the **Link** option from the wizard:
[](https://i.stack.imgur.com/SNg1a.png)
After the table has been linked, your `UPDATE` statement will become simply:
```
UPDATE
tblOne INNER JOIN tblTwo ON tblOne.TID = tblTwo.TID
SET
tblTwo.PC = tblOne.PC
``` | I think you just need to reverse what you’ve written because the table you’re updating needs to be the main table.
Try:
```
UPDATE tblTwo
INNER JOIN tblOne ON tblOne.[TID] = tblTwo.TID
SET tblTwo.PC = [tblOne].[PC] ;
```
Please note without a where clause you will be updating all rows. |
10,838,386 | I have this tables
`ADDS` (1)
```none
+----+--------------+--------------+
| id | name of add | Date |
+----+--------------+--------------+
| 1 | Add01 | March 01 |
| 2 | Add02 | March 02 |
| 3 | Add03 | March 03 |
| 4 | Add04 | March 04 |
+----+--------------+--------------+
```
`TYPE OF ADDS` (2)
```none
+----+----------+
| id | Add id |
+----+----------+
| 21 | 1 | NOTE: Add id of table (2) = id of table (1)
| 22 | 2 |
| 23 | 3 |
| 24 | 4 |
+----+----------+
```
`NAMES OF TYPES` (3)
```none
+----+-----------+--------------+
| id | Type id | Name |
+----+-----------+--------------+
| 31 | 21 | Text add |
| 32 | 22 | Banner | NOTE: Type id of table (3) = id of table (2)
| 33 | 23 | Video add |
| 34 | 24 | Other |
+----+-----------+--------------+
```
I need a report like this:
```none
+--------+-----------+--------------+
| Add id | Add name | Type of add |
+--------+-----------+--------------+
| 1 | Add01 | Text add |
| 2 | Add02 | Banner |
| 3 | Add03 | Video add |
| 4 | Add04 | Other |
+--------+-----------+--------------+
```
(`Add id` from table (1), `Add name` from table (1), `Type of add` from table (3))
So far I can do a `SELECT query LEFT JOIN table 1 and 2` but I don't know how to return the value `Name of type` from table 3. How can I do it? | 2012/05/31 | [
"https://Stackoverflow.com/questions/10838386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428981/"
] | Today is the 31st next month only has 30 days so it would be 7/12 in 1 month from today
```
assuming that today is May 31 2012
date('m Y') == 05 2012
date('m Y', strtotime('+1 month')) == 07 2012 because june has 30 days
date('m Y', strtotime('+2 month')) == 07 2012
date('m Y', strtotime('+3 month')) == 08 2012
date('m Y', strtotime('+4 month')) == 10 2012
```
I would take today's date and find the first day of the month then add a month to that if you are doing something that needs to get each month | It is working as intended. In a nutshell, it is because what is "one month" from May 31? June 30? August 1?
My suggestion is that if you need sequential months, calculate the offset from the start of the current month, not the current day. Or compose the date that you're looking for manually using the month, day, and year parts broken up. |
10,838,386 | I have this tables
`ADDS` (1)
```none
+----+--------------+--------------+
| id | name of add | Date |
+----+--------------+--------------+
| 1 | Add01 | March 01 |
| 2 | Add02 | March 02 |
| 3 | Add03 | March 03 |
| 4 | Add04 | March 04 |
+----+--------------+--------------+
```
`TYPE OF ADDS` (2)
```none
+----+----------+
| id | Add id |
+----+----------+
| 21 | 1 | NOTE: Add id of table (2) = id of table (1)
| 22 | 2 |
| 23 | 3 |
| 24 | 4 |
+----+----------+
```
`NAMES OF TYPES` (3)
```none
+----+-----------+--------------+
| id | Type id | Name |
+----+-----------+--------------+
| 31 | 21 | Text add |
| 32 | 22 | Banner | NOTE: Type id of table (3) = id of table (2)
| 33 | 23 | Video add |
| 34 | 24 | Other |
+----+-----------+--------------+
```
I need a report like this:
```none
+--------+-----------+--------------+
| Add id | Add name | Type of add |
+--------+-----------+--------------+
| 1 | Add01 | Text add |
| 2 | Add02 | Banner |
| 3 | Add03 | Video add |
| 4 | Add04 | Other |
+--------+-----------+--------------+
```
(`Add id` from table (1), `Add name` from table (1), `Type of add` from table (3))
So far I can do a `SELECT query LEFT JOIN table 1 and 2` but I don't know how to return the value `Name of type` from table 3. How can I do it? | 2012/05/31 | [
"https://Stackoverflow.com/questions/10838386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428981/"
] | As others have said, it is because today is the 31st and +1 month equals June-31 which changes to Jul-1. If you include the day in the date string, you can see exactly this.
```
<?php
$sP1 = date('m-d-Y');
$sP2 = date('m-d-Y', strtotime('+01 month'));
$sP3 = date('m-d-Y', strtotime('+02 month'));
$sP4 = date('m-d-Y', strtotime('+03 month'));
echo $sP1."\n";
echo $sP2."\n";
echo $sP3."\n";
echo $sP4."\n";
/* Outputs:
05-31-2012
07-01-2012
07-31-2012
08-31-2012
*/
?>
```
strtotime though can take the start date as part of the string so as King suggested, calculate the +N months from the first. So a string like `May-1-2012 +01 month` such as:
```
<?php
$sP1 = date('m Y');
$sP2 = date('m Y', strtotime(date('M-1-Y').' +01 month'));
$sP3 = date('m Y', strtotime(date('M-1-Y').' +02 month'));
$sP4 = date('m Y', strtotime(date('M-1-Y').' +03 month'));
echo $sP1."\n";
echo $sP2."\n";
echo $sP3."\n";
echo $sP4."\n";
/* Outputs:
05 2012
06 2012
07 2012
08 2012
*/
?>
```
<http://codepad.org/auYLHvDI> | It is working as intended. In a nutshell, it is because what is "one month" from May 31? June 30? August 1?
My suggestion is that if you need sequential months, calculate the offset from the start of the current month, not the current day. Or compose the date that you're looking for manually using the month, day, and year parts broken up. |
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
] | It's a hold over from C++ and C before that. In the C context, one of its meanings was for variables that keep their value between invocations. I presume that's where 'static' comes from - it doesn't reset the value (as opposed to a const where the value cannot change) | >
> Definition of STATIC 1 : exerting
> force by reason of weight alone
> without motion 2 : of or relating to
> bodies at rest or forces in
> equilibrium 3 : showing little change
> 4 a :
> characterized by a lack of movement,
> animation, or progression b :
> producing an effect of repose or
> quiescence 5 a :
> standing or fixed in one place :
> stationary b of water : stored in a
> tank but not under pressure
>
>
>
just apply the definition to a variable... |
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
] | It's a hold over from C++ and C before that. In the C context, one of its meanings was for variables that keep their value between invocations. I presume that's where 'static' comes from - it doesn't reset the value (as opposed to a const where the value cannot change) | In Head First Java, there is a nice explanation of static. Static means stable not changing thats obvious from meaning and its quite obvious that it does not change.
Static mean sharing in Java. There is a nice picture where two child sharing one ice cream and showed static variable analogy. For more info please read Head First Java. |
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
] | It's a hold over from C++ and C before that. In the C context, one of its meanings was for variables that keep their value between invocations. I presume that's where 'static' comes from - it doesn't reset the value (as opposed to a const where the value cannot change) | I suppose the best way to think of it is that "static" means unchanging, and it is the *location* of the variable that is unchanging when when you switch between the different instances of a class. The main thing is to eradicate any thought from your mind that the *value* of a static variable is unchanging: it may even be changed by another instance of the same class. |
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
] | In Head First Java, there is a nice explanation of static. Static means stable not changing thats obvious from meaning and its quite obvious that it does not change.
Static mean sharing in Java. There is a nice picture where two child sharing one ice cream and showed static variable analogy. For more info please read Head First Java. | >
> Definition of STATIC 1 : exerting
> force by reason of weight alone
> without motion 2 : of or relating to
> bodies at rest or forces in
> equilibrium 3 : showing little change
> 4 a :
> characterized by a lack of movement,
> animation, or progression b :
> producing an effect of repose or
> quiescence 5 a :
> standing or fixed in one place :
> stationary b of water : stored in a
> tank but not under pressure
>
>
>
just apply the definition to a variable... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.