qid
int64 1
74.7M
| question
stringlengths 17
39.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
41.1k
| response_k
stringlengths 2
47.9k
|
---|---|---|---|---|---|
24,012,430 | I can only get correct output for decimal less than five. the output for five is 110 when it should be 101. the output for six is 101 and the output for ten is 1100.
```
//while loop divides each digit
while (decimal > 0)
{
//divides and digit becomes the remainder
int digit = decimal % 2;
//makes the digit into a string builder so it can be reversed
binaryresult.append(digit);
decimal = decimal / 2;
display.setText(binaryresult.reverse());
}
``` | 2014/06/03 | [
"https://Stackoverflow.com/questions/24012430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657245/"
] | Usee the below code it may work for you
```
import java.util.Scanner;
public class decToBinary{
public String decToBin(int n) {
StringBuilder result = new StringBuilder();
int i = 0;
int b[] = new int[10];
while (n != 0) {
i++;
b[i] = n % 2;
n = n / 2;
}
for (int j = i; j > 0; j--) {
result.append(b[j]);
}
return result.toString();
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal no :");
int n=sc.nextInt();
System.out.println("binary numbers is :");
decToBinary dtb = new decToBinary();
System.out.println(dtb.decToBin(n));
}
}
``` | try this code , i hope this is what u r looking for:
```
public class DecimalToBinary {
public static void main(String[] args)
{
int decimal=11;
StringBuffer binaryValue=new StringBuffer();
while(decimal>0 ){
int rem=decimal%2;
decimal=decimal/2;
System.out.println("Remainder:"+rem);
binaryValue.append(rem);
}
System.out.println("binary is:"+binaryValue.reverse());
}
}
``` |
38,521,514 | I have two xml variables:
```
@main xml = '<root></root>'
@insert xml = '<rows><row>SomeRow</row></rows>'
```
And I would like to insert child nodes of @insert rows, so that I have a resultant XML that looks like this:
```
<root>
<row>SomeRow</row>
</root>
```
I am well aware of inserting xml from sql variables (using sql:variable("@insert")) but this inserts the whole XML including the root element. What I want is to only insert the child nodes of the root element in the @insert variable.
Thanks a bunch. | 2016/07/22 | [
"https://Stackoverflow.com/questions/38521514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5336001/"
] | One way is to change data in variable you need to insert into another xml:
```
DECLARE @main xml = '<root></root>',
@insert xml = '<rows><row>SomeRow</row></rows>'
SELECT @insert = @insert.query('/rows/row')
SET @main.modify('
insert sql:variable("@insert")
into (/root)[1] ')
SELECT @main
```
Output:
```
<root>
<row>SomeRow</row>
</root>
``` | Okay, in the spirit of closing this, I have a workaround which is technically a one-liner that can be used to do what I want. It has proven to work well for me and avoids creating an intermediate variable. But also only works in mainly single-level XMLs.
```
-- The same variables, I added '<tag>' to demonstrate the insert
DECLARE @main xml = '<root><tag>Some data Here</tag></root>'
DECLARE @insert xml = '<rows><row>SomeRow</row></rows>'
-- One-liner that inserts '@insert' into @main
SET @main = (
SELECT @main.query('/root/*'), @insert.query('/rows/*')
FOR XML RAW(''),ROOT('root'), ELEMENTS, TYPE
)
SELECT @main
```
Output:
```
<root>
<tag>Some data Here</tag>
<row>SomeRow</row>
</root>
``` |
45,785,435 | I'm trying to make a new application that will help people hear music together.
One problem I noticed is that the people need to get the YouTube code of each song or video they want to hear.
I kind of fixed this problem by using MySQL database with names and codes of songs, then all what the user need to do is to find the YouTube video and click on share with my application, it sends the link and the name of the video to the database and then users can search there for the song they want to play. However, I want to get rid of that, too.
Is there some way to search for a video on YouTube with the API?
I found this link to open source code on Google Developers <https://developers.google.com/youtube/v3/docs/search/list#examples>
But it just doesn't work. | 2017/08/20 | [
"https://Stackoverflow.com/questions/45785435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5791998/"
] | You can use this:
```
https://www.googleapis.com/youtube/v3/search?part=snippet&q=eminem&type=video&key=<key>
```
Change the parameters to get what you actually need, but you need an API key from <https://console.developers.google.com/> to make this work. | ```
https://www.googleapis.com/youtube/v3/search?key={your_key_here}&channelId={channel_id_here}&part=snippet,id&order=date&maxResults=20
```
you can use above url for searching videos. |
467,675 | I have the following problem:
>
> Assume that $f:\Bbb R^n\to\Bbb R$ satisfies $$|f(x)-f(y)|\le M\cdot|x-y|$$for some $M\in \Bbb R$ and $f(0)=0$. Suppose that all the directional derivatives vanish at the origin. Prove that $f$ is differentiable at 0.
>
>
>
The following was what I tried:
In order to show that $f$ is differentiable at $0$, we need to find a linear map $A$ such that $$\lim\_{h\to0}{{|f(h)-f(0)-A\cdot h|}\over{|h|}}=0.$$
Since all the directional derivatives vanish at 0, which says $A=0$ (Is this right???).
$0\le{{|f(h)-f(0)|}\over{|h|}}\le M|h|/|h|=M$, which I cannot get the desired result. Any help, please. | 2013/08/14 | [
"https://math.stackexchange.com/questions/467675",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/40071/"
] | The given assumptions indeed imply that $f$ is differentiable at $0$ and that $df(0)=0$.
*Proof.* We have to prove that
$$\lim\_{x\to 0}{|f(x)|\over|x|}=0\ .$$
Assume that this is not the case. Then there exists an $\epsilon>0$ and a sequence $(x\_k)\_{k\geq0}$ with $\lim\_{k\to\infty} x\_k=0$ such that
$$|f(x\_k)|>\epsilon |x\_k|\qquad\forall k\geq0\ .$$
The unit sphere $S^{n-1}$ is compact. After passing to a subsequence we can therefore assume that there is an $u\in S^{n-1}$ with
$${x\_k\over|x\_k|}\to u\qquad(k\to\infty)\ .$$
It follows that there is a $k\_0$ such that
$$\left|{x\_k\over|x\_k|}-u\right|<{\epsilon\over 2M}\qquad(k>k\_0)\ ,$$
or
$$\biggl|x\_k-|x\_k|u\biggr|<{\epsilon|x\_k|\over 2M}\qquad(k\to\infty)\ .$$
The Lipschitz condition then implies that
$$\biggl|f\bigl(|x\_k|u\bigr)\biggr|\geq|f(x\_k)|-M\biggl|x\_k-|x\_k|u\biggr|>\epsilon|x\_k|-{\epsilon|x\_k|\over 2}={\epsilon|x\_k|\over2}\qquad(k>k\_0)\ .$$
It follows that
$${\bigl|f\bigl(|x\_k|u\bigr)\bigr|\over|x\_k|}\geq{\epsilon\over2}$$
for all $k>k\_0$, which contradicts the assumption $D\_uf(0)=0$. | As you found out, the Lipschitz condition applied here is useless. The essence of the problem lies in the difference between the directional derivative definition and this stronger full differentiation definition.
**Edit:** In consideration of the contradiction proof from Christian Blatter, and a few attempts, it appears what I had before probably won't work. Anyway, for a direct proof suggestion, use an $\epsilon$-$\delta$ proof, and apply the definition of directional derivative to **many** different directions. Then for a given direction $h$, you can compare to the result to the nearest one for which you have applied the definition. Probably in essence will be the same as Christian's proof. |
10,272,481 | I need to get a random number that is between
```
0 - 80
```
and
```
120 - 200
```
I can do
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
But then I need to choose between `n1` and `n2`. Cannot do
```
$n3 = rand($n1, $n2)
```
as this may give me a number between `80 - 120` which I need to avoid.
How to solve this? | 2012/04/22 | [
"https://Stackoverflow.com/questions/10272481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445142/"
] | Since both ranges have different sizes (even if only by 1 number), to ensure good random spread, you need to do this:
```
$random = rand( 0, 200 - 39 );
if ($random>=120-39) $random+=39;
```
Fastest method. :)
The way this works is by pretending it's a single range, and if it ends up picking a number above the first range, we increase it to fit within the second range. This ensures perfect spread. | Since both ranges have the same size you can simply use `rand(0, 1)` to determine which range to use.
```
$n = rand(0, 1) ? rand(0, 80) : rand(120, 200);
``` |
10,272,481 | I need to get a random number that is between
```
0 - 80
```
and
```
120 - 200
```
I can do
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
But then I need to choose between `n1` and `n2`. Cannot do
```
$n3 = rand($n1, $n2)
```
as this may give me a number between `80 - 120` which I need to avoid.
How to solve this? | 2012/04/22 | [
"https://Stackoverflow.com/questions/10272481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445142/"
] | Since both ranges have the same size you can simply use `rand(0, 1)` to determine which range to use.
```
$n = rand(0, 1) ? rand(0, 80) : rand(120, 200);
``` | PHP has a new function for this as well called range. Very easy to use, and can be located in the PHP Manual.
It allows you to input a minimum/maximum number to grab a range from.
```
<?php
echo range(0, 1000);
?
```
Technically though, you could also enter your own two numbers to serve as the number range. |
10,272,481 | I need to get a random number that is between
```
0 - 80
```
and
```
120 - 200
```
I can do
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
But then I need to choose between `n1` and `n2`. Cannot do
```
$n3 = rand($n1, $n2)
```
as this may give me a number between `80 - 120` which I need to avoid.
How to solve this? | 2012/04/22 | [
"https://Stackoverflow.com/questions/10272481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445142/"
] | Since both ranges have the same size you can simply use `rand(0, 1)` to determine which range to use.
```
$n = rand(0, 1) ? rand(0, 80) : rand(120, 200);
``` | get two random numbers **$n1** and **$n2**
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
define new array called **$n3**
```
$n3=array();
```
add **$n1** and **$n2** into array **$n3** use array\_push() function
```
array_push($n3,$n1,$n2);
```
use array\_rand() function to find random index **$find\_index** from array **$n3**.
```
$find_index=array_rand($n3,1);
```
show the result
```
echo $n3[$find_index];
``` |
10,272,481 | I need to get a random number that is between
```
0 - 80
```
and
```
120 - 200
```
I can do
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
But then I need to choose between `n1` and `n2`. Cannot do
```
$n3 = rand($n1, $n2)
```
as this may give me a number between `80 - 120` which I need to avoid.
How to solve this? | 2012/04/22 | [
"https://Stackoverflow.com/questions/10272481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445142/"
] | Since both ranges have different sizes (even if only by 1 number), to ensure good random spread, you need to do this:
```
$random = rand( 0, 200 - 39 );
if ($random>=120-39) $random+=39;
```
Fastest method. :)
The way this works is by pretending it's a single range, and if it ends up picking a number above the first range, we increase it to fit within the second range. This ensures perfect spread. | PHP has a new function for this as well called range. Very easy to use, and can be located in the PHP Manual.
It allows you to input a minimum/maximum number to grab a range from.
```
<?php
echo range(0, 1000);
?
```
Technically though, you could also enter your own two numbers to serve as the number range. |
10,272,481 | I need to get a random number that is between
```
0 - 80
```
and
```
120 - 200
```
I can do
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
But then I need to choose between `n1` and `n2`. Cannot do
```
$n3 = rand($n1, $n2)
```
as this may give me a number between `80 - 120` which I need to avoid.
How to solve this? | 2012/04/22 | [
"https://Stackoverflow.com/questions/10272481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445142/"
] | Since both ranges have different sizes (even if only by 1 number), to ensure good random spread, you need to do this:
```
$random = rand( 0, 200 - 39 );
if ($random>=120-39) $random+=39;
```
Fastest method. :)
The way this works is by pretending it's a single range, and if it ends up picking a number above the first range, we increase it to fit within the second range. This ensures perfect spread. | get two random numbers **$n1** and **$n2**
```
$n1 = rand(0, 80);
$n2 = rand(120, 200);
```
define new array called **$n3**
```
$n3=array();
```
add **$n1** and **$n2** into array **$n3** use array\_push() function
```
array_push($n3,$n1,$n2);
```
use array\_rand() function to find random index **$find\_index** from array **$n3**.
```
$find_index=array_rand($n3,1);
```
show the result
```
echo $n3[$find_index];
``` |
72,413,719 | I'm wondering if there is something inefficient in this code I've made, or if there is a faster way to find prime numbers.
```
#include <stdio.h>
int main(void)
{
int count;
for(int i=3; i<1000; i+=2){//search number in range of 3~999
count=0;//init count
for(int j=3; j*j<=i; j+=2){
if(count==1){//if i has aliquot already, break the loop
break;
}
if(i%j==0){
count=1;//if i has aliquot, change count to 1
}
}
if(count==0){
printf("%d ", i);//if there are no aliquot, print i
}
}
return 0;
}
``` | 2022/05/28 | [
"https://Stackoverflow.com/questions/72413719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19157836/"
] | Seems that you are using [trial division](https://en.wikipedia.org/wiki/Trial_division), which takes *O*(√*n*) time to determine the primality of a single number, thus inefficient for finding all prime numbers in a range. To find all prime numbers in a range efficiently, consider using the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) (with time complexity *O*(*n*log*n*loglog*n*)) or [Euler's sieve](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Euler%27s_sieve) (with time complexity *O*(*n*)). Here are simple implementations for these two algorithms.
Implementation for the sieve of Eratosthenes
--------------------------------------------
```cpp
bool isPrime[N];
void eratosthenes(int n) {
for (int i = 2; i <= n; ++i) {
isPrime[i] = true;
}
isPrime[1] = false;
for (int i = 2; i * i <= n; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
```
Implementation for Euler's sieve
--------------------------------
```cpp
bool isPrime[N];
std::vector<int> primes;
void euler(int n) {
for (int i = 2; i <= n; ++i) {
isPrime[i] = true;
}
isPrime[1] = false;
for (int i = 2; i <= n; ++i) {
if (isPrime[i]) primes.push_back(i);
for (size_t j = 0; j < primes.size() && i * primes[j] <= n; ++j) {
isPrime[i * primes[j]] = false;
if (i % primes[j] == 0) break;
}
}
}
``` | Eratosthenes Sieve is cool, but deprecated ? Why not use my Prime class ? it has an incrementation method, does not not use division.
Prime class describes a number through its congruences to lower primes. Incrementing a prime is to increase all congruences, a new congruence is created if the integer is prime (all congruences -modulos\_- differ from 0).
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
class Prime {
public :
Prime () : n_ (2), modulos_ (std::vector<std::pair<int, int> > ())
{
if (!modulos_.capacity ()) modulos_.reserve (100000000);
std::pair<int, int> p (2, 0);
modulos_.push_back (p);
}
~Prime () {}
Prime (const Prime& i) : n_ (i.n_), modulos_ (i.modulos_)
{}
bool operator == (const Prime& n) const {
return (n_ == n.n_);
}
bool operator != (const Prime& n) const {
return !operator == (n);
}
Prime& operator = (const Prime& i) {
n_ = i.n_,
modulos_ = i.modulos_;
return *this;
}
void write (std::ostream& os) const {
os << n_;
}
void operator ++ () {
int prime (1);
do {
++n_;
prime = 1;
std::for_each (modulos_.begin (), modulos_.end (), [&prime] (std::pair<int, int>& p) {
++p.second;
if (p.first == p.second) {
p.second = 0;
prime = 0;
}
});
}
while (!prime);
std::pair<int, int> p (n_, 0);
modulos_.push_back (p);
}
bool operator < (const int& s) const {
return n_ < s;
}
private :
int n_;
std::vector<std::pair<int, int> > modulos_;
};
```
Usage :
```
int main (int, char**) {
Prime p;
do {
p.write (std::cout);
std::cout << std::endl;
++p;
}
while (p < 20);
}
```
Results :
2
3
5
7
11
13
17
19 |
72,413,719 | I'm wondering if there is something inefficient in this code I've made, or if there is a faster way to find prime numbers.
```
#include <stdio.h>
int main(void)
{
int count;
for(int i=3; i<1000; i+=2){//search number in range of 3~999
count=0;//init count
for(int j=3; j*j<=i; j+=2){
if(count==1){//if i has aliquot already, break the loop
break;
}
if(i%j==0){
count=1;//if i has aliquot, change count to 1
}
}
if(count==0){
printf("%d ", i);//if there are no aliquot, print i
}
}
return 0;
}
``` | 2022/05/28 | [
"https://Stackoverflow.com/questions/72413719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19157836/"
] | Seems that you are using [trial division](https://en.wikipedia.org/wiki/Trial_division), which takes *O*(√*n*) time to determine the primality of a single number, thus inefficient for finding all prime numbers in a range. To find all prime numbers in a range efficiently, consider using the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) (with time complexity *O*(*n*log*n*loglog*n*)) or [Euler's sieve](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Euler%27s_sieve) (with time complexity *O*(*n*)). Here are simple implementations for these two algorithms.
Implementation for the sieve of Eratosthenes
--------------------------------------------
```cpp
bool isPrime[N];
void eratosthenes(int n) {
for (int i = 2; i <= n; ++i) {
isPrime[i] = true;
}
isPrime[1] = false;
for (int i = 2; i * i <= n; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
```
Implementation for Euler's sieve
--------------------------------
```cpp
bool isPrime[N];
std::vector<int> primes;
void euler(int n) {
for (int i = 2; i <= n; ++i) {
isPrime[i] = true;
}
isPrime[1] = false;
for (int i = 2; i <= n; ++i) {
if (isPrime[i]) primes.push_back(i);
for (size_t j = 0; j < primes.size() && i * primes[j] <= n; ++j) {
isPrime[i * primes[j]] = false;
if (i % primes[j] == 0) break;
}
}
}
``` | For the primes up to 1000, an efficient method is
```
cout << "2 3 5 7 11 13 17 19 23
29 31 37 41 43 47 53 59 61 67
71 73 79 83 89 97 101 103 107 109
113 127 131 137 139 149 151 157 163 167
173 179 181 191 193 197 199 211 223 227
229 233 239 241 251 257 263 269 271 277
281 283 293 307 311 313 317 331 337 347
349 353 359 367 373 379 383 389 397 401
409 419 421 431 433 439 443 449 457 461
463 467 479 487 491 499 503 509 521 523
541 547 557 563 569 571 577 587 593 599
601 607 613 617 619 631 641 643 647 653
659 661 673 677 683 691 701 709 719 727
733 739 743 751 757 761 769 773 787 797
809 811 821 823 827 829 839 853 857 859
863 877 881 883 887 907 911 919 929 937
941 947 953 967 971 977 983 991 997" << endl;
``` |
180,007 | **Background**
I'm a Data Scientist and am being asked to come up with a set of metrics/KPIs to assess my annual performance, and things like bonuses (and in the worst case being fired) depend on that. And of course I want them to align to my personal Data Scientist growth goals as well. My position entails:
* working on machine learning projects from the start to end (getting data access, exploration, modelling, results, presentation, helping in productionising etc)
* Analysing certain topics to give suggestions to the management
* A part of which could be to educate stakeholders on using new tools to analyze on their own
What I've observed is that the job of a Data Scientist is rather complicated when it comes to measuring success, and things like performance appraisals metrics are then harder to design.
**My Intuition:**
On one hand, things like number of machine learning models deployed seem like a direct measurable metric, but on the other hand all models are not equal. Some may need a lot of time while others might be ready relatively quicker. The same goes for number of topics analysed/explored, as in exploration the required effort could vary a lot more than in modelling.
The only thing I can clearly put is the cumulative business value of the machine learning models developed, or of the business decision made from an exploration/analysis. This, however, puts the responsibility on the stakeholders a lot, putting an overhead work (to devise this value) needed to approach our team, and the stakeholders might hesitate approaching us. On the other hand, I believe that the stakeholders should be clear about the value of every topic they're working on, and the ones they requested other teams to work on.
Apart from business value, I also think about including something to assess the quality of every modelling project or analysis, something like a quality score, so as to drive me to improve the quality of my approach, to present better etc. But I'm not sure if quantifying the overall quality of such things could be practical and indicative consistently of what it was meant to be.
**Question:**
What could (generally) be good performance evaluation metrics for such a Data Scientist?
OR
What should the technical approach be to devise such metrics? | 2021/11/16 | [
"https://workplace.stackexchange.com/questions/180007",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/110828/"
] | Any metric can (and will) be gamed. You are **asked** to make up the rules for that game however, so you can just make metrics that you know you will be able to perform best on, and get your bonuses.
But if you want to create honest metrics, do not look at numbers too much. Number of models deployed? Sure, you'll just create 10 regression models and combine them into one ensemble model and boom!, lots of models. Number of projects? Not up to you, but just finish every project quickly without writing proper code and documentation, done.
So instead, look at actual competencies/skills and assess based on that. You want to measure improvement in those competencies. Schaun Wheeler [suggests](https://elu.nl/a-framework-for-evaluating-data-scientist-competency/) a few skills/competencies:
[![ELU suggestions](https://i.stack.imgur.com/ZMZTl.png)](https://i.stack.imgur.com/ZMZTl.png)
This of course needs to be tailored to your individual responsibilities, together with your manager. The possible skill levels here are:
* Unconscious Incompentence
* Conscious Incompentence
* Conscious Competence
* Unconscious Competence
Which is based on [this model](https://en.wikipedia.org/wiki/Four_stages_of_competence) of Four Stages of Competence. These are not hard numeric values, but can be used to assess where your competence is right now and what you should work on. You can use whatever competence rating system you want of course.
Evaluate yourself now on these skills, and look at 6 months from now whether you've improved on any of these. Add new ones if you want to develop yourself further in a specific direction. Set a goal with your manager, e.g. "Bonus if skills X, Y and Z from Unconscious Incompetence to Conscious Competence".
You can still game this, but this way it is at least incentivized to become better at your job instead of better at deploying some number of models to make a cutoff. This does make it hard to actually evaluate your performance, since it is less absolute, but if you have a good relationship with your manager and you want to improve, it can certainly work. | It's always a good idea to stay simple when you write metrics when there are no clear indicators.
You need to understand your role as a Data Scientist, in the context of your job, and how it relates to the goals and outputs of the wider organization. The company's KPI sets out what is important for them, so you should be drawing from them.
You should be looking for a mix of lead indicators and lag indicators. A lead indicator gives on how your future performance will be and a lag indicator on how your past performance has been.
Good lead indicators could be:
* evidence that your skills are staying current and that you're undertaking any necessary training
* evidence that you are engaged across the business and are actively looking for and identifying new opportunities for data improvement
Good lag indicators could be:
* surveys from colleagues on projects you have been involved in
* individual performance against project timeframes and objectives
* % of total data sources you have reviewed, cleaned, and optimized
* % of total data sources where data accuracy has been checked
* % of known missing data sources that have been identified and connected
* if it's possible a metric on what value you've added to the organization through new processes, models, algorithms, or insights. |
180,007 | **Background**
I'm a Data Scientist and am being asked to come up with a set of metrics/KPIs to assess my annual performance, and things like bonuses (and in the worst case being fired) depend on that. And of course I want them to align to my personal Data Scientist growth goals as well. My position entails:
* working on machine learning projects from the start to end (getting data access, exploration, modelling, results, presentation, helping in productionising etc)
* Analysing certain topics to give suggestions to the management
* A part of which could be to educate stakeholders on using new tools to analyze on their own
What I've observed is that the job of a Data Scientist is rather complicated when it comes to measuring success, and things like performance appraisals metrics are then harder to design.
**My Intuition:**
On one hand, things like number of machine learning models deployed seem like a direct measurable metric, but on the other hand all models are not equal. Some may need a lot of time while others might be ready relatively quicker. The same goes for number of topics analysed/explored, as in exploration the required effort could vary a lot more than in modelling.
The only thing I can clearly put is the cumulative business value of the machine learning models developed, or of the business decision made from an exploration/analysis. This, however, puts the responsibility on the stakeholders a lot, putting an overhead work (to devise this value) needed to approach our team, and the stakeholders might hesitate approaching us. On the other hand, I believe that the stakeholders should be clear about the value of every topic they're working on, and the ones they requested other teams to work on.
Apart from business value, I also think about including something to assess the quality of every modelling project or analysis, something like a quality score, so as to drive me to improve the quality of my approach, to present better etc. But I'm not sure if quantifying the overall quality of such things could be practical and indicative consistently of what it was meant to be.
**Question:**
What could (generally) be good performance evaluation metrics for such a Data Scientist?
OR
What should the technical approach be to devise such metrics? | 2021/11/16 | [
"https://workplace.stackexchange.com/questions/180007",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/110828/"
] | Any metric can (and will) be gamed. You are **asked** to make up the rules for that game however, so you can just make metrics that you know you will be able to perform best on, and get your bonuses.
But if you want to create honest metrics, do not look at numbers too much. Number of models deployed? Sure, you'll just create 10 regression models and combine them into one ensemble model and boom!, lots of models. Number of projects? Not up to you, but just finish every project quickly without writing proper code and documentation, done.
So instead, look at actual competencies/skills and assess based on that. You want to measure improvement in those competencies. Schaun Wheeler [suggests](https://elu.nl/a-framework-for-evaluating-data-scientist-competency/) a few skills/competencies:
[![ELU suggestions](https://i.stack.imgur.com/ZMZTl.png)](https://i.stack.imgur.com/ZMZTl.png)
This of course needs to be tailored to your individual responsibilities, together with your manager. The possible skill levels here are:
* Unconscious Incompentence
* Conscious Incompentence
* Conscious Competence
* Unconscious Competence
Which is based on [this model](https://en.wikipedia.org/wiki/Four_stages_of_competence) of Four Stages of Competence. These are not hard numeric values, but can be used to assess where your competence is right now and what you should work on. You can use whatever competence rating system you want of course.
Evaluate yourself now on these skills, and look at 6 months from now whether you've improved on any of these. Add new ones if you want to develop yourself further in a specific direction. Set a goal with your manager, e.g. "Bonus if skills X, Y and Z from Unconscious Incompetence to Conscious Competence".
You can still game this, but this way it is at least incentivized to become better at your job instead of better at deploying some number of models to make a cutoff. This does make it hard to actually evaluate your performance, since it is less absolute, but if you have a good relationship with your manager and you want to improve, it can certainly work. | I'm assuming that a Data Scientist is not a Data Engineer (DE), and not an Analyst, but lives in the intersection of those fields. My criteria would be:
Business problems solved, short-term (i.e., one-offs)
Business problems solved, long-term:
* People in business units understood the solution.
* Data pipelines set up as needed (possibly with DE supporting).
* People in the business set up to understand, implement and manage the solution.
Business managers saying that you have saved them time/money/problems, and/or improved time/money/problems.
Training people to better solve problems (DE, Analysts, business unit people).
Demonstrating the you have gained the business knowledge to participate at a higher and better level. |
210,624 | The gas giant in question is about 3 times the mass of jupiter with a density of 3.58 grams per cubic centimeter. It formed naturally beyond the system's forstline and then migrated into the habitable zone at about 2 to 2.26 AUs from it's parent F-star 1.31 times more massive than the sun, acquiring a couple of additional satellites around the end of the migration on rather distant orbits (10 to 20 planetary radii).
First of all, can a gas giant with that mass and density have rings? How thick could they be?
Would it still retain the rings after migration?
How much would the rings be impacted by the increased solar energy? How thinner would they get if they lost most of the ice? | 2021/08/21 | [
"https://worldbuilding.stackexchange.com/questions/210624",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/88403/"
] | You've got a big problem here: Land erodes. The only reason we have continents is plate tectonics--otherwise the continents would have eroded into the oceans long ago and we would have a 100% water world.
You are after 40% land--every bit of that 40% must be volcanoes (or recently deceased volcanoes that haven't eroded away yet.) That's not going to be a good place if it's even survivable at all.
And there are no chains--with no plate tectonics nothing moves over the heat pipes. Your **only** terrain type is volcano. (Yes, you can have the sorts of terrain that are on the slopes of a volcano.) You won't have anything resembling continents, land-based evolution won't be able to spread other than by species that develop means of very long range ocean travel. | There is a quite long and insightful BBC article on this topic:
<http://www.bbc.com/earth/story/20170111-the-unexpected-ingredient-necessary-for-life/>
So the atmosphere, climate and geographics would certainly differ from our world and it would be unlikely a planet like that would produce the same very specific atmosphere composition and conditions that made life like ours possible. It's for good reason we didn't find extraterrestrial life yet- life like it exists on earth just needs that 1 in a billion exact combination of different factors, so I think it might be possible but veeeery improbable for it to occur on a planet lacking something influential as tectonics.
However it doesn't seem impossible for some sort of species to develop on a completely different environmental operating system, maybe breathing something entirely different than oxygen or not breathing at all. Wether that is possible we didn't have the chance to find out yet, so I assume that is up to creativity. |
25,105,456 | I'm trying to add in a new element to a JsValue, but I'm not sure how to go about it.
```
val rJson = Json.parse(response)
val imgId = //stuff to get the id :Long
rJson.apply("imgId", imgId)
Json.stringify(rJson)
```
Should I be converting to a JSONObject or is there some method that can be applied directly to the JsValue to insert a new element to the JSON?
Edit:
`response` is coming from another server, but I do have control over it. So, if I need to add an empty `"imgId"` element to the JSON Object, that's fine. | 2014/08/03 | [
"https://Stackoverflow.com/questions/25105456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842932/"
] | You can do this as a `JsObject`, which extends `JsValue` and has a `+` method:
```
val rJson: JsValue = Json.parse(response)
val imgId = ...
val returnJson: JsObject = rJson.as[JsObject] + ("imgId" -> Json.toJson(imgId))
Json.stringify(returnJson)
``` | I use the following helper in a project I'm working on:
```
/** Insert a new value at the given path */
def insert(path: JsPath, value: JsValue) =
__.json.update(path.json.put(value))
```
, which can be used as a JSON transformer as such:
```
val rJson = Json.parse(response)
val imgId = //stuff to get the id :Long
Json.stringify(rJson.transform(insert(__ \ 'imgId, imgId)))
```
You could definitely just use the body of that `insert` method, but I personally find the transformer API to be really counterintuitive.
The nice thing about this is that any number of transforms can be composed using `andThen`. We typically use this to convert API responses to the format of our models so that we can use `Reads` deserializers to instantiate model instances. We use this `insert` helper to mock parts of the API response that don't yet exist, so that we can build models we need ahead of the API.
Even though the API is convoluted, I highly, highly recommend investing some time in reading the [Play framework docs on JSON handling](http://www.playframework.com/documentation/2.3.x/ScalaJson), all 5 pages. They're not the world's greatest docs, but they actually are pretty thorough. |
26,765,311 | I want to make a Greasemonkey script that, while you are in URL\_1, the script parses the whole HTML web page of URL\_2 in the background in order to extract a text element from it.
To be specific, I want to download the whole page's HTML code (a *Rotten Tomatoes* page) in the background and store it in a variable and then use `getElementsByClassName[0]` in order to extract the text I want from the element with class name "critic\_consensus".
I've found this in MDN: [HTML in XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest) so, I ended up in this unfortunately non-working code:
```
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0].innerHTML);
}
xhr.open("GET", "http://www.rottentomatoes.com/m/godfather/",true);
xhr.responseType = "document";
xhr.send();
```
It shows this error message when I run it in Firefox Scratchpad:
>
> Cross-Origin Request Blocked: The Same Origin Policy disallows reading
> the remote resource at <http://www.rottentomatoes.com/m/godfather/>.
> This can be fixed by moving the resource to the same domain or
> enabling CORS.
>
>
>
PS. The reason why I don't use the Rotten Tomatoes API is that [they've removed the critics consensus from it](http://developer.rottentomatoes.com/forum/read/184496). | 2014/11/05 | [
"https://Stackoverflow.com/questions/26765311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3231411/"
] | The problem is: XMLHttpRequest cannot load <http://www.rottentomatoes.com/m/godfather/>. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Because you are not the owner of the resource you can not set up this header.
What you can do is set up a proxy on heroku which will proxy all requests to rottentomatoes web site
Here is a small node.js proxy <https://gist.github.com/igorbarinov/a970cdaf5fc9451f8d34>
```
var https = require('https'),
http = require('http'),
util = require('util'),
path = require('path'),
fs = require('fs'),
colors = require('colors'),
url = require('url'),
httpProxy = require('http-proxy'),
dotenv = require('dotenv');
dotenv.load();
var proxy = httpProxy.createProxyServer({});
var host = "www.rottentomatoes.com";
var port = Number(process.env.PORT || 5000);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var server = require('http').createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
var path = url.parse(req.url, true).path;
req.headers.host = host;
res.setHeader("Access-Control-Allow-Origin", "*");
proxy.web(req, res, {
target: "http://"+host+path,
});
}).listen(port);
proxy.on('proxyRes', function (res) {
console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));
});
util.puts('Proxying to '+ host +'. Server'.blue + ' started '.green.bold + 'on port '.blue + port);
```
I modified <https://github.com/massive/firebase-proxy/> code for this
I published proxy on <http://peaceful-cove-8072.herokuapp.com/> and on <http://peaceful-cove-8072.herokuapp.com/m/godfather> you can test it
Here is a gist to test <http://jsfiddle.net/uuw8nryy/>
```
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0]);
}
xhr.open("GET", "http://peaceful-cove-8072.herokuapp.com/m/godfather",true);
xhr.responseType = "document";
xhr.send();
``` | The JavaScript [same origin policy](http://en.wikipedia.org/wiki/Same-origin_policy) prevents you from accessing content that belongs to a different domain.
The above reference also gives you four techniques for relaxing this rule (CORS being one of them). |
26,765,311 | I want to make a Greasemonkey script that, while you are in URL\_1, the script parses the whole HTML web page of URL\_2 in the background in order to extract a text element from it.
To be specific, I want to download the whole page's HTML code (a *Rotten Tomatoes* page) in the background and store it in a variable and then use `getElementsByClassName[0]` in order to extract the text I want from the element with class name "critic\_consensus".
I've found this in MDN: [HTML in XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest) so, I ended up in this unfortunately non-working code:
```
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0].innerHTML);
}
xhr.open("GET", "http://www.rottentomatoes.com/m/godfather/",true);
xhr.responseType = "document";
xhr.send();
```
It shows this error message when I run it in Firefox Scratchpad:
>
> Cross-Origin Request Blocked: The Same Origin Policy disallows reading
> the remote resource at <http://www.rottentomatoes.com/m/godfather/>.
> This can be fixed by moving the resource to the same domain or
> enabling CORS.
>
>
>
PS. The reason why I don't use the Rotten Tomatoes API is that [they've removed the critics consensus from it](http://developer.rottentomatoes.com/forum/read/184496). | 2014/11/05 | [
"https://Stackoverflow.com/questions/26765311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3231411/"
] | For cross-origin requests, where the fetched site has not helpfully set a permissive [CORS policy](http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing), Greasemonkey provides [the `GM_xmlhttpRequest()` function](http://wiki.greasespot.net/GM_xmlhttpRequest). (Most other userscript engines also provide this function.)
`GM_xmlhttpRequest` is expressly designed to allow cross-origin requests.
To get your target information create a `DOMParser` on the result. Do not use jQuery methods as this will cause extraneous images, scripts and objects to load, slowing things down, or crashing the page.
Here's **a complete script** that illustrates the process:
```
// ==UserScript==
// @name _Parse Ajax Response for specific nodes
// @include http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_xmlhttpRequest
// ==/UserScript==
GM_xmlhttpRequest ( {
method: "GET",
url: "http://www.rottentomatoes.com/m/godfather/",
onload: function (response) {
var parser = new DOMParser ();
/* IMPORTANT!
1) For Chrome, see
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension_for_other_browsers
for a work-around.
2) jQuery.parseHTML() and similar are bad because it causes images, etc., to be loaded.
*/
var doc = parser.parseFromString (response.responseText, "text/html");
var criticTxt = doc.getElementsByClassName ("critic_consensus")[0].textContent;
$("body").prepend ('<h1>' + criticTxt + '</h1>');
},
onerror: function (e) {
console.error ('**** error ', e);
},
onabort: function (e) {
console.error ('**** abort ', e);
},
ontimeout: function (e) {
console.error ('**** timeout ', e);
}
} );
``` | The problem is: XMLHttpRequest cannot load <http://www.rottentomatoes.com/m/godfather/>. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Because you are not the owner of the resource you can not set up this header.
What you can do is set up a proxy on heroku which will proxy all requests to rottentomatoes web site
Here is a small node.js proxy <https://gist.github.com/igorbarinov/a970cdaf5fc9451f8d34>
```
var https = require('https'),
http = require('http'),
util = require('util'),
path = require('path'),
fs = require('fs'),
colors = require('colors'),
url = require('url'),
httpProxy = require('http-proxy'),
dotenv = require('dotenv');
dotenv.load();
var proxy = httpProxy.createProxyServer({});
var host = "www.rottentomatoes.com";
var port = Number(process.env.PORT || 5000);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var server = require('http').createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
var path = url.parse(req.url, true).path;
req.headers.host = host;
res.setHeader("Access-Control-Allow-Origin", "*");
proxy.web(req, res, {
target: "http://"+host+path,
});
}).listen(port);
proxy.on('proxyRes', function (res) {
console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));
});
util.puts('Proxying to '+ host +'. Server'.blue + ' started '.green.bold + 'on port '.blue + port);
```
I modified <https://github.com/massive/firebase-proxy/> code for this
I published proxy on <http://peaceful-cove-8072.herokuapp.com/> and on <http://peaceful-cove-8072.herokuapp.com/m/godfather> you can test it
Here is a gist to test <http://jsfiddle.net/uuw8nryy/>
```
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0]);
}
xhr.open("GET", "http://peaceful-cove-8072.herokuapp.com/m/godfather",true);
xhr.responseType = "document";
xhr.send();
``` |
26,765,311 | I want to make a Greasemonkey script that, while you are in URL\_1, the script parses the whole HTML web page of URL\_2 in the background in order to extract a text element from it.
To be specific, I want to download the whole page's HTML code (a *Rotten Tomatoes* page) in the background and store it in a variable and then use `getElementsByClassName[0]` in order to extract the text I want from the element with class name "critic\_consensus".
I've found this in MDN: [HTML in XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest) so, I ended up in this unfortunately non-working code:
```
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0].innerHTML);
}
xhr.open("GET", "http://www.rottentomatoes.com/m/godfather/",true);
xhr.responseType = "document";
xhr.send();
```
It shows this error message when I run it in Firefox Scratchpad:
>
> Cross-Origin Request Blocked: The Same Origin Policy disallows reading
> the remote resource at <http://www.rottentomatoes.com/m/godfather/>.
> This can be fixed by moving the resource to the same domain or
> enabling CORS.
>
>
>
PS. The reason why I don't use the Rotten Tomatoes API is that [they've removed the critics consensus from it](http://developer.rottentomatoes.com/forum/read/184496). | 2014/11/05 | [
"https://Stackoverflow.com/questions/26765311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3231411/"
] | For cross-origin requests, where the fetched site has not helpfully set a permissive [CORS policy](http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing), Greasemonkey provides [the `GM_xmlhttpRequest()` function](http://wiki.greasespot.net/GM_xmlhttpRequest). (Most other userscript engines also provide this function.)
`GM_xmlhttpRequest` is expressly designed to allow cross-origin requests.
To get your target information create a `DOMParser` on the result. Do not use jQuery methods as this will cause extraneous images, scripts and objects to load, slowing things down, or crashing the page.
Here's **a complete script** that illustrates the process:
```
// ==UserScript==
// @name _Parse Ajax Response for specific nodes
// @include http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_xmlhttpRequest
// ==/UserScript==
GM_xmlhttpRequest ( {
method: "GET",
url: "http://www.rottentomatoes.com/m/godfather/",
onload: function (response) {
var parser = new DOMParser ();
/* IMPORTANT!
1) For Chrome, see
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension_for_other_browsers
for a work-around.
2) jQuery.parseHTML() and similar are bad because it causes images, etc., to be loaded.
*/
var doc = parser.parseFromString (response.responseText, "text/html");
var criticTxt = doc.getElementsByClassName ("critic_consensus")[0].textContent;
$("body").prepend ('<h1>' + criticTxt + '</h1>');
},
onerror: function (e) {
console.error ('**** error ', e);
},
onabort: function (e) {
console.error ('**** abort ', e);
},
ontimeout: function (e) {
console.error ('**** timeout ', e);
}
} );
``` | The JavaScript [same origin policy](http://en.wikipedia.org/wiki/Same-origin_policy) prevents you from accessing content that belongs to a different domain.
The above reference also gives you four techniques for relaxing this rule (CORS being one of them). |
39,922 | After finishing Project Euler 24, I decided to make a scrabble type of application using /usr/lib/dict as my dictionary what I cat that into a word file. It does take a few seconds, and the dictionary selection isn't that great.
Is there any way I could make it faster, more effective, and with a better dictionary source?
```
public class Scrabble {
public static ArrayList<String> numbers = new ArrayList<String>();
public static ArrayList<String> numbers2 = new ArrayList<String>() {
};
public static void main(String[] args) {
Scanner dict = null;
try {
dict = new Scanner(new File("words.txt"));
} catch (FileNotFoundException ex) {
}
while (dict.hasNextLine()) {
numbers.add(dict.nextLine());
}
String n = "gojy";//random text here
rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {
if (numbers.contains(listWithoutDuplicates.get(i))) {
System.out.println(listWithoutDuplicates.get(i));
}
}
}
public static void rearrange(
String q, String w) {
if (w.length() <= 1) {
String k = q + w;
numbers2.add(k);//full word
numbers2.add(q);//smaller combination to get words with less letters. doesn't work too well
} else {
for (int i = 0; i < w.length(); i++) {
String c = w.substring(0, i)
+ w.substring(i + 1);
rearrange(q
+ w.charAt(i), c);
}
}
}
}
``` | 2014/01/23 | [
"https://codereview.stackexchange.com/questions/39922",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/35472/"
] | If what you are trying to do is store a huge list of valid words in such a way that you can test whether a given string is a valid word, a Trie works well. See [this](https://stackoverflow.com/questions/2225540/trie-implementation) Stack Overflow question.
Load the wordlist into the Trie when your server starts, and use the same Trie for all games (assuming this is a client server game). It's trickier than the linked thread if you need to include more than the standard 26 letters of the alphabet, but I've done a Unicode Trie for a chat filter before and I could help if you need that.
I don't understand what you are trying to do with the rearrange method. Can you explain? | @Teresa has already provided some good hints on how to improve the performance by using a better data structure so I'll concentrate on general things:
1. Your code has a bug such as that it will crash with a `NullPointerException` if the file cannot be found.
* You initialize `dict` to `null`
* You catch the `FileNotFoundException` when trying to create `dict`
* If the exception got caught the `dict` will still be `null` and it will throw when you try to access it.So the whole `try-catch` around the `Scanner` instantiation is pretty much useless as it will crash anyway. Even worse: Instead of getting a `FileNotFoundException` which pretty much tells you what is wrong you get a fairly meaningless `NullPointerException`.
2. You have two static arrays `numbers` and `numbers2`. These names are useless as they do in no way give you any idea whatsoever what they are being used for. The name of a variable, method, class, parameter, etc. is effectively the advertising sign for its purpose. A good concise name goes a long way of
* Making your code more readable and understandable
* Reducing bugs by misunderstanding the purpose of your own variablesIn this case there is not much code and it's not terribly complicated but you should get into the habit of choosing good names.
3. `dict` is not a good name for the `Scanner` as it doesn't represent a dictionary in itself - it's a reader which reads lines from a file.
4. All your code is in the `main` method. You should get into the habit of building reusable pieces of code - in the case of Java this means creating reusable classes. So I'd suggest your create a dedicated class which holds your lookup structure and provide as well defined interface for adding valid words and looking up a word. Something like this:
```
public class WordLookup
{
public WordLookup()
{
...
}
public void addValidWord(string word)
{
...
}
public bool isValidWord(string word)
{
...
}
}
```
Now `main` can be rewritten as:
```
public static void main(String[] args) {
Scanner reader = new Scanner(new File("words.txt"));
WordLookup lookup = new WordLookup();
while (reader.hasNextLine()) {
lookup.addValidWord(reader.nextLine());
}
String n = "gojy";//random text here
rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {
string currentWord = listWithoutDuplicates.get(i);
if (lookup.isValidWord(currentWord)) {
System.out.println(currentWord);
}
}
}
```
What do you gain from it: You can now fiddle with the implementation of `WordLookup` without having to touch the `main` method.
I came across a saying a while ago, don't remember where, which I quite like:
>
> Train like you fight because you will fight like you train
>
>
>
So train yourself to write well structured encapsulated code even for seemingly simple things because it will form a habit. Even if you don't want to develop software professionally in the long run you will find it more rewarding when you do it right. |
39,922 | After finishing Project Euler 24, I decided to make a scrabble type of application using /usr/lib/dict as my dictionary what I cat that into a word file. It does take a few seconds, and the dictionary selection isn't that great.
Is there any way I could make it faster, more effective, and with a better dictionary source?
```
public class Scrabble {
public static ArrayList<String> numbers = new ArrayList<String>();
public static ArrayList<String> numbers2 = new ArrayList<String>() {
};
public static void main(String[] args) {
Scanner dict = null;
try {
dict = new Scanner(new File("words.txt"));
} catch (FileNotFoundException ex) {
}
while (dict.hasNextLine()) {
numbers.add(dict.nextLine());
}
String n = "gojy";//random text here
rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {
if (numbers.contains(listWithoutDuplicates.get(i))) {
System.out.println(listWithoutDuplicates.get(i));
}
}
}
public static void rearrange(
String q, String w) {
if (w.length() <= 1) {
String k = q + w;
numbers2.add(k);//full word
numbers2.add(q);//smaller combination to get words with less letters. doesn't work too well
} else {
for (int i = 0; i < w.length(); i++) {
String c = w.substring(0, i)
+ w.substring(i + 1);
rearrange(q
+ w.charAt(i), c);
}
}
}
}
``` | 2014/01/23 | [
"https://codereview.stackexchange.com/questions/39922",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/35472/"
] | If what you are trying to do is store a huge list of valid words in such a way that you can test whether a given string is a valid word, a Trie works well. See [this](https://stackoverflow.com/questions/2225540/trie-implementation) Stack Overflow question.
Load the wordlist into the Trie when your server starts, and use the same Trie for all games (assuming this is a client server game). It's trickier than the linked thread if you need to include more than the standard 26 letters of the alphabet, but I've done a Unicode Trie for a chat filter before and I could help if you need that.
I don't understand what you are trying to do with the rearrange method. Can you explain? | I found the code rather hard to follow due to some unconventional naming:
* `numbers` and `numbers2` are actually lists of `String`s, not numbers.
* `dict` is a `Scanner`, not a dictionary.
* `n` is a `String`, not an integer.
---
The `numbers2` assignment has inexplicable trailing braces. That creates an anonymous inner class that extends `ArrayList`, but not overriding or defining any additional members!
---
You swallowed `FileNotFoundException`, which just makes debugging more difficult. In general, if you don't know what to do about an exception, just let it propagate. In this case,
```
public static void main(String[] args) throws FileNotFoundException
```
will take care of it.
---
To iterate through all elements of a list…
```
for (String s : listWithoutDuplicates) {
…
}
``` |
39,922 | After finishing Project Euler 24, I decided to make a scrabble type of application using /usr/lib/dict as my dictionary what I cat that into a word file. It does take a few seconds, and the dictionary selection isn't that great.
Is there any way I could make it faster, more effective, and with a better dictionary source?
```
public class Scrabble {
public static ArrayList<String> numbers = new ArrayList<String>();
public static ArrayList<String> numbers2 = new ArrayList<String>() {
};
public static void main(String[] args) {
Scanner dict = null;
try {
dict = new Scanner(new File("words.txt"));
} catch (FileNotFoundException ex) {
}
while (dict.hasNextLine()) {
numbers.add(dict.nextLine());
}
String n = "gojy";//random text here
rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {
if (numbers.contains(listWithoutDuplicates.get(i))) {
System.out.println(listWithoutDuplicates.get(i));
}
}
}
public static void rearrange(
String q, String w) {
if (w.length() <= 1) {
String k = q + w;
numbers2.add(k);//full word
numbers2.add(q);//smaller combination to get words with less letters. doesn't work too well
} else {
for (int i = 0; i < w.length(); i++) {
String c = w.substring(0, i)
+ w.substring(i + 1);
rearrange(q
+ w.charAt(i), c);
}
}
}
}
``` | 2014/01/23 | [
"https://codereview.stackexchange.com/questions/39922",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/35472/"
] | @Teresa has already provided some good hints on how to improve the performance by using a better data structure so I'll concentrate on general things:
1. Your code has a bug such as that it will crash with a `NullPointerException` if the file cannot be found.
* You initialize `dict` to `null`
* You catch the `FileNotFoundException` when trying to create `dict`
* If the exception got caught the `dict` will still be `null` and it will throw when you try to access it.So the whole `try-catch` around the `Scanner` instantiation is pretty much useless as it will crash anyway. Even worse: Instead of getting a `FileNotFoundException` which pretty much tells you what is wrong you get a fairly meaningless `NullPointerException`.
2. You have two static arrays `numbers` and `numbers2`. These names are useless as they do in no way give you any idea whatsoever what they are being used for. The name of a variable, method, class, parameter, etc. is effectively the advertising sign for its purpose. A good concise name goes a long way of
* Making your code more readable and understandable
* Reducing bugs by misunderstanding the purpose of your own variablesIn this case there is not much code and it's not terribly complicated but you should get into the habit of choosing good names.
3. `dict` is not a good name for the `Scanner` as it doesn't represent a dictionary in itself - it's a reader which reads lines from a file.
4. All your code is in the `main` method. You should get into the habit of building reusable pieces of code - in the case of Java this means creating reusable classes. So I'd suggest your create a dedicated class which holds your lookup structure and provide as well defined interface for adding valid words and looking up a word. Something like this:
```
public class WordLookup
{
public WordLookup()
{
...
}
public void addValidWord(string word)
{
...
}
public bool isValidWord(string word)
{
...
}
}
```
Now `main` can be rewritten as:
```
public static void main(String[] args) {
Scanner reader = new Scanner(new File("words.txt"));
WordLookup lookup = new WordLookup();
while (reader.hasNextLine()) {
lookup.addValidWord(reader.nextLine());
}
String n = "gojy";//random text here
rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {
string currentWord = listWithoutDuplicates.get(i);
if (lookup.isValidWord(currentWord)) {
System.out.println(currentWord);
}
}
}
```
What do you gain from it: You can now fiddle with the implementation of `WordLookup` without having to touch the `main` method.
I came across a saying a while ago, don't remember where, which I quite like:
>
> Train like you fight because you will fight like you train
>
>
>
So train yourself to write well structured encapsulated code even for seemingly simple things because it will form a habit. Even if you don't want to develop software professionally in the long run you will find it more rewarding when you do it right. | I found the code rather hard to follow due to some unconventional naming:
* `numbers` and `numbers2` are actually lists of `String`s, not numbers.
* `dict` is a `Scanner`, not a dictionary.
* `n` is a `String`, not an integer.
---
The `numbers2` assignment has inexplicable trailing braces. That creates an anonymous inner class that extends `ArrayList`, but not overriding or defining any additional members!
---
You swallowed `FileNotFoundException`, which just makes debugging more difficult. In general, if you don't know what to do about an exception, just let it propagate. In this case,
```
public static void main(String[] args) throws FileNotFoundException
```
will take care of it.
---
To iterate through all elements of a list…
```
for (String s : listWithoutDuplicates) {
…
}
``` |
640,294 | I've been trying to make `printf` output some chars, given their ASCII numbers (in hex)... something like this:
```bsh
#!/bin/bash
hexchars () { printf '\x%s' $@ ;}
hexchars 48 65 6c 6c 6f
Expected output:
Hello
```
For some reason that doesn't work though. Any ideas?
**EDIT:**
Based on the answer provided by Isaac (accepted answer), I ended up with this function:
```
chr () { local var ; printf -v var '\\x%x' $@ ; printf "$var" ;}
```
Note, I rewrote his answer a bit in order to improve speed by avoiding the subshell.
```
Result:
~# chr 0x48 0x65 0x6c 0x6c 0x6f
Hello
~# chr 72 101 108 108 111
Hello
~# chr {32..126}
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
```
I guess the inverse of the `chr` function would be a function like...
```
asc () { printf '%d\n' "'$1" ;}
asc A
65
chr 65
A
```
Or, if we want strictly hex variants...
```
chrx () { local var ; printf -v var '\\x%s' $@ ; printf "$var\n" ;}
ascx () { printf '%x\n' "'$1" ;}
chrx 48 65 6c 6c 6f
Hello
ascx A
41
```
Thank you! | 2021/03/21 | [
"https://unix.stackexchange.com/questions/640294",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | Oh, sure, just that it has to be done in two steps. Like a two step tango:
```
$ printf "$(printf '\\x%s' 48 65 6c 6c 6f)"; echo
Hello
```
Or, alternatively:
```
$ test () { printf "$(printf '\\x%s' "$@")"; echo; }
$ test 48 65 6c 6c 6f
Hello
```
Or, to avoid printing on "no arguments":
```
$ test () { [ "$#" -gt 0 ] && printf "$(printf '\\x%s' "$@")"; echo; }
$ test 48 65 6c 6c 6f
Hello
$
```
That is assuming that the arguments are decimal values between 1 and 127 (empty arguments would be counted but will fail on printing). | `\x` needs to be followed by a *literal* hexadecimal value:
```
$ printf '\x48\n'
H
$ c=48
$ printf '\x%s\n' "$c"
bash: printf: missing hex digit for \x
\x48
```
Presumably this is because `printf` will expand any hexadecimal literals in the format string as a separate step before using the resulting string as the format.
What you can do instead:
```bsh
unhexlify() {
for character
do
format="\x${character}"
printf "$format"
done
printf '\n'
}
```
Test:
```
$ unhexlify 48 65 6c 6c 6f
Hello
``` |
640,294 | I've been trying to make `printf` output some chars, given their ASCII numbers (in hex)... something like this:
```bsh
#!/bin/bash
hexchars () { printf '\x%s' $@ ;}
hexchars 48 65 6c 6c 6f
Expected output:
Hello
```
For some reason that doesn't work though. Any ideas?
**EDIT:**
Based on the answer provided by Isaac (accepted answer), I ended up with this function:
```
chr () { local var ; printf -v var '\\x%x' $@ ; printf "$var" ;}
```
Note, I rewrote his answer a bit in order to improve speed by avoiding the subshell.
```
Result:
~# chr 0x48 0x65 0x6c 0x6c 0x6f
Hello
~# chr 72 101 108 108 111
Hello
~# chr {32..126}
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
```
I guess the inverse of the `chr` function would be a function like...
```
asc () { printf '%d\n' "'$1" ;}
asc A
65
chr 65
A
```
Or, if we want strictly hex variants...
```
chrx () { local var ; printf -v var '\\x%s' $@ ; printf "$var\n" ;}
ascx () { printf '%x\n' "'$1" ;}
chrx 48 65 6c 6c 6f
Hello
ascx A
41
```
Thank you! | 2021/03/21 | [
"https://unix.stackexchange.com/questions/640294",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | Oh, sure, just that it has to be done in two steps. Like a two step tango:
```
$ printf "$(printf '\\x%s' 48 65 6c 6c 6f)"; echo
Hello
```
Or, alternatively:
```
$ test () { printf "$(printf '\\x%s' "$@")"; echo; }
$ test 48 65 6c 6c 6f
Hello
```
Or, to avoid printing on "no arguments":
```
$ test () { [ "$#" -gt 0 ] && printf "$(printf '\\x%s' "$@")"; echo; }
$ test 48 65 6c 6c 6f
Hello
$
```
That is assuming that the arguments are decimal values between 1 and 127 (empty arguments would be counted but will fail on printing). | Using **perl** and it's `pack` function we pack two hex digits and print the ASCII representation.
```
charx() {
perl -le 'print pack "(H2)*", @ARGV' -- "$@"
}
```
---
We use the desk calculator **dc** to input base 16 and print out in their ASCII characters using the **a** command.
```
charx() {
dc <<eof
16i
$(echo "$@" | tr a-f A-F)
[SAz0<a]sa
[LAanln1-dsn0<b]sb
[zsnlaxlbxAan]sc
z0<c
eof
}
```
---
Used as:
```
charx 48 65 6c 6c 6f
```
**Result**
```
Hello
``` |
17,532,858 | I have written two Rest based web methods in a service :
```
Response doSomething() ;
Response doSomething2()
```
Now , I want to marshal these responses as two different xml names . So that, the response looks like :
```
**<doSomethingResponse>** for doSomething()
**<doSomething2Response>** for doSomething2()
```
What is the best way to do this. I am using jaxB for marshalling. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17532858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033534/"
] | You could leverage a `JAXBElement` to supply the root element name. In the example below we will use a `JAXBElement` to make the root node of the response `FOO`.
```
@GET
@Produces(MediaType.APPLICATION_XML)
public Response get() {
Customer customer = new Customer();
customer.setFirstName("Jane");
customer.setLastName("Doe");
JAXBElement<Customer> jaxbElement = new JAXBElement(new QName("FOO"), Customer.class, customer);
return Response.ok(jaxbElement).build();
}
``` | You can either use `@WebResult` or `@XmlElement` annotations:
```
@WebResult(name="doSomethingResponse")
//or
//@XmlElement(name="doSomethingResponse")
Response doSomething();
@WebResult(name="doSomething2Response")
//or
//@XmlElement(name="doSomething2Response")
Response doSomething2();
``` |
204,542 | Is there a quick way to discover what Active Directory site the current server you are logged into is? I googled but couldn't find anything. | 2010/11/22 | [
"https://serverfault.com/questions/204542",
"https://serverfault.com",
"https://serverfault.com/users/53216/"
] | Sites are determined by subnet in CIDR notation in the Sites and Services snap-in. You could just take a screenshot of the configuration and by your IP address, determine what site it should be in. Now, if you're looking for a command that shows the CURRENT site try the gpresult command line tool. I'm almost positive that will print it out for you. | From a command prompt, run SET.
You'll get a listing of USERDOMAIN and USERDNSDOMAIN. |
204,542 | Is there a quick way to discover what Active Directory site the current server you are logged into is? I googled but couldn't find anything. | 2010/11/22 | [
"https://serverfault.com/questions/204542",
"https://serverfault.com",
"https://serverfault.com/users/53216/"
] | Sites are determined by subnet in CIDR notation in the Sites and Services snap-in. You could just take a screenshot of the configuration and by your IP address, determine what site it should be in. Now, if you're looking for a command that shows the CURRENT site try the gpresult command line tool. I'm almost positive that will print it out for you. | Run the following in an administrator command prompt:
```
gpresult /R /Scope Computer
```
Example output:
```
C:\Windows\system32>gpresult /R /Scope Computer
Microsoft (R) Windows (R) Operating System Group Policy Result tool v2.0
Copyright (C) Microsoft Corp. 1981-2001
Created On 4/23/2012 at 6:34:45 PM
RSOP data for GB7\- on GB7 : Logging Mode
------------------------------------------
OS Configuration: Standalone Workstation
OS Version: 6.1.7601
Site Name: N/A
Roaming Profile: N/A
Local Profile: C:\Users\-
Connected over a slow link?: No
```
Another option would be to use [Nltest](http://technet.microsoft.com/en-us/library/cc786478%28v=ws.10%29.aspx):
```
Nltest.exe /dsgetsite
```
For more details including all applied Group Policy Objects (GPO) run the following commands:
```
gpresult /V /Scope Computer
gpresult /V /Scope User
``` |
204,542 | Is there a quick way to discover what Active Directory site the current server you are logged into is? I googled but couldn't find anything. | 2010/11/22 | [
"https://serverfault.com/questions/204542",
"https://serverfault.com",
"https://serverfault.com/users/53216/"
] | Run the following in an administrator command prompt:
```
gpresult /R /Scope Computer
```
Example output:
```
C:\Windows\system32>gpresult /R /Scope Computer
Microsoft (R) Windows (R) Operating System Group Policy Result tool v2.0
Copyright (C) Microsoft Corp. 1981-2001
Created On 4/23/2012 at 6:34:45 PM
RSOP data for GB7\- on GB7 : Logging Mode
------------------------------------------
OS Configuration: Standalone Workstation
OS Version: 6.1.7601
Site Name: N/A
Roaming Profile: N/A
Local Profile: C:\Users\-
Connected over a slow link?: No
```
Another option would be to use [Nltest](http://technet.microsoft.com/en-us/library/cc786478%28v=ws.10%29.aspx):
```
Nltest.exe /dsgetsite
```
For more details including all applied Group Policy Objects (GPO) run the following commands:
```
gpresult /V /Scope Computer
gpresult /V /Scope User
``` | From a command prompt, run SET.
You'll get a listing of USERDOMAIN and USERDNSDOMAIN. |
23,650,205 | Can you tell me how can I add a nice fade effect for smoother animation to my function instead of setting visibility hidden / visible at an regular interval.
I am not looking for a plugin or add jQuery UI library.
**My JS** :
```
setBlinkingInterval: function(elem, event) {
if (intervalIdForBlinking != 0)
window.clearInterval(intervalIdForBlinking);
$(elem).show();
intervalIdForBlinking = setInterval(function() {
if (eventsObj.eventIsFinished(event)) {
timer.setClosedStatus(elem, event);
}
else {
if (elem.css('visibility') == 'hidden')
elem.css('visibility', 'visible');
else
elem.css('visibility', 'hidden');
}
}, 500);
}
```
Update 1: HTML markup in order to clarify one answer
```
$('<span/>')
.append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + ' </div>')
.append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
.append('<br/>')
.append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + ' ' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
.appendTo(rightTd);
```
Update 2: So after implementing the solutions based on the provided answers I am having issues when it is displayed on the page.
Case 1: When using my original solution (It works fine)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QHn458)
Case 2: When using fade in/out method (Display issue)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QMn45S)
Case 3: When using toggle method (Display issue)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QEn45M)
Is there any quick fix to solve the display issue?
Update 3: As requested by one user here is the complete HTML up generated by a JS function
drawRaceHead: function(event) {
```
// Returning all race numbers to default values
styling.makeAllRaceNumbersUnselected();
// Make the race number active (including Racing Specials)
styling.makeCurrentEventNumberSelected(event)
// Race info
$("#raceInfo").html('');
$("#raceInfo").append($('<table/>').append($('<tr/>')))
var leftTd = $('<td style="width: 295px"/>')
.appendTo($('#raceInfo')),
rightTd = $('<td/>')
.appendTo($('#raceInfo'));
// If not Racing Specials category
if (event.parentCategoryId != 2863) leftTd.html(raceFullName + ' ' + event.name)
else leftTd.html(event.name);
$('<div id="closing_time" style="display:none"/>')
.appendTo(leftTd)
// Date, time, weather, track
var weatherInfo = '', trackInfo = '';
if (event.markets.length > 0) {
weatherInfo = (event.markets[0].weather == null) ? '-' : event.markets[0].weather;
trackInfo = (event.markets[0].track == null) ? '-' : event.markets[0].track;
}
var isMSIE = /*@cc_on!@*/false;
var ieVersion = (function(reg) { return isMSIE && navigator.userAgent.match(reg) ? RegExp.$1 * 1 : null; })(/MSIE\s([0-9]+[\.0-9]*)/);
if (isMSIE && ieVersion < 11) {
timezone = '';
}
else {
var regExp = /\(([^)]+)\)/, timezone = (regExp.exec(new Date)[1]).split(' ')[0];
timezone = ' (' + timezone + ')';
}
$('<span/>')
.append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + ' </div>')
.append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
.append('<br/>')
.append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + ' ' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
.appendTo(rightTd);
```
}, | 2014/05/14 | [
"https://Stackoverflow.com/questions/23650205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695685/"
] | use this:
```
if (!$(elem).is(':visible')) {
$(elem).fadeIn( "slow");
} else {
$(elem).fadeOut( "slow");
}
```
Or use the toggle function of jquery:
```
$(elem).toggle("slow");
```
For fadeIn function [read here](http://api.jquery.com/fadein/).
For fadeOut function [read here](http://api.jquery.com/fadeOut/).
For toggle function [read here](http://api.jquery.com/toggle/). | Try below jQuery code
```
setBlinkingInterval: function(elem, event) {
if (intervalIdForBlinking != 0)
window.clearInterval(intervalIdForBlinking);
$(elem).show();
intervalIdForBlinking = setInterval(function() {
if (eventsObj.eventIsFinished(event)) {
timer.setClosedStatus(elem, event);
}
else {
if ($(elem).is(':visible'))
$(elem).fadeOut(3000);
else
$(elem).fadeIn(3000);
}
}, 500);
}
```
[FadeIn and fadeOut examples](http://www.mkyong.com/jquery/jquery-fadein-fadeout-and-fadeto-example/)
[fadeIn API Details](http://api.jquery.com/fadein/)
[fadeOut API Details](http://api.jquery.com/fadeout/) |
23,650,205 | Can you tell me how can I add a nice fade effect for smoother animation to my function instead of setting visibility hidden / visible at an regular interval.
I am not looking for a plugin or add jQuery UI library.
**My JS** :
```
setBlinkingInterval: function(elem, event) {
if (intervalIdForBlinking != 0)
window.clearInterval(intervalIdForBlinking);
$(elem).show();
intervalIdForBlinking = setInterval(function() {
if (eventsObj.eventIsFinished(event)) {
timer.setClosedStatus(elem, event);
}
else {
if (elem.css('visibility') == 'hidden')
elem.css('visibility', 'visible');
else
elem.css('visibility', 'hidden');
}
}, 500);
}
```
Update 1: HTML markup in order to clarify one answer
```
$('<span/>')
.append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + ' </div>')
.append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
.append('<br/>')
.append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + ' ' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
.appendTo(rightTd);
```
Update 2: So after implementing the solutions based on the provided answers I am having issues when it is displayed on the page.
Case 1: When using my original solution (It works fine)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QHn458)
Case 2: When using fade in/out method (Display issue)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QMn45S)
Case 3: When using toggle method (Display issue)
Screen recorder link [HERE](http://screencast-o-matic.com/watch/c2h2QEn45M)
Is there any quick fix to solve the display issue?
Update 3: As requested by one user here is the complete HTML up generated by a JS function
drawRaceHead: function(event) {
```
// Returning all race numbers to default values
styling.makeAllRaceNumbersUnselected();
// Make the race number active (including Racing Specials)
styling.makeCurrentEventNumberSelected(event)
// Race info
$("#raceInfo").html('');
$("#raceInfo").append($('<table/>').append($('<tr/>')))
var leftTd = $('<td style="width: 295px"/>')
.appendTo($('#raceInfo')),
rightTd = $('<td/>')
.appendTo($('#raceInfo'));
// If not Racing Specials category
if (event.parentCategoryId != 2863) leftTd.html(raceFullName + ' ' + event.name)
else leftTd.html(event.name);
$('<div id="closing_time" style="display:none"/>')
.appendTo(leftTd)
// Date, time, weather, track
var weatherInfo = '', trackInfo = '';
if (event.markets.length > 0) {
weatherInfo = (event.markets[0].weather == null) ? '-' : event.markets[0].weather;
trackInfo = (event.markets[0].track == null) ? '-' : event.markets[0].track;
}
var isMSIE = /*@cc_on!@*/false;
var ieVersion = (function(reg) { return isMSIE && navigator.userAgent.match(reg) ? RegExp.$1 * 1 : null; })(/MSIE\s([0-9]+[\.0-9]*)/);
if (isMSIE && ieVersion < 11) {
timezone = '';
}
else {
var regExp = /\(([^)]+)\)/, timezone = (regExp.exec(new Date)[1]).split(' ')[0];
timezone = ' (' + timezone + ')';
}
$('<span/>')
.append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + ' </div>')
.append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
.append('<br/>')
.append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + ' ' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
.appendTo(rightTd);
```
}, | 2014/05/14 | [
"https://Stackoverflow.com/questions/23650205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695685/"
] | use this:
```
if (!$(elem).is(':visible')) {
$(elem).fadeIn( "slow");
} else {
$(elem).fadeOut( "slow");
}
```
Or use the toggle function of jquery:
```
$(elem).toggle("slow");
```
For fadeIn function [read here](http://api.jquery.com/fadein/).
For fadeOut function [read here](http://api.jquery.com/fadeOut/).
For toggle function [read here](http://api.jquery.com/toggle/). | They are two methods to do this first is to use Jquery toggle() functionality.
```
elem.toggle("slow");
```
It will automatically toggle to other form.
Or you can use Jquery fadeIn() and fadeOut().
```
if (!$(elem).is(':visible')) {
$(elem).fadeIn( "slow");
} else {
$(elem).fadeOut( "slow");
}
``` |
69,765,218 | I have meet a problem that I want to delete the duplicates or use other signs to replace them except the last time by Python . For example:
Before: `aaaabbbbcccc||ddddddd||eee||fff`
After: `aaaabbbbccccdddddddeee||fff` OR
`aaaabbbbcccc,ddddddd,eee||fff` | 2021/10/29 | [
"https://Stackoverflow.com/questions/69765218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15781190/"
] | There are **many** ways to achieve this. The ground principle is to separate the last item and handle it individually.
Here are a few possibilities that do not require imports:
##### using a list as intermediate
```
s = 'aaaabbbbcccc||ddddddd||eee||fff'
l = s.split('||')
','.join(l[:-1])+'||'+l[-1]
```
##### functional way
```
'||'.join(map(lambda x: ','.join(x.split('||')), s.rsplit('||', 1)))
```
##### limited replacements (require 2 reads of the string)
```
s.replace('||', ',', s.count('||')-1)
```
output: `'aaaabbbbcccc,ddddddd,eee||fff'` | Using regex:
```py
import re
x = "aaaabbbbcccc||ddddddd||eee||fff"
x = re.sub(r"\|\|(?=[^\|]*\|\|)", ",", x)
print(x)
```
Result:
```
aaaabbbbcccc,ddddddd,eee||fff
```
Use empty string to get the first example:
```
x = re.sub(r"\|\|(?=[^\|]*\|\|)", "", x)
>>>
aaaabbbbccccdddddddeee||fff
``` |
15,665,980 | I am running Flash Builder 4.6 and just added Apache flex sdk 4.9.1 (build 1447119) to my mac book pro running Moutain Lion and when i tried to do a quick 'hello world' and add a few elements to the stage using design mode i got following error:
>
> The design mode is disabled as the project uses an incompatible version of the flex sdk
>
>
>
My question is if i go beyond the default sdk that shipped with fb 4.6 do I therefore loose the ability to use design mode and have to do everything in source mode?
Also, if i am using windows the error is quite similar when i mouseover on `Design` tab
>
> Design mode not supported - incompatible SDK version - Apache Flex
>
>
>
Thanks | 2013/03/27 | [
"https://Stackoverflow.com/questions/15665980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306792/"
] | There is a hack you can do to get it working (I've done this myself and it works perfectly so far) that involves editing an XML file in the 4.9.1 SDK to trick Flash Builder into thinking it is using Flex 4.6. You'll need to edit the `'flex-sdk-description.xml'` Version tag and change it from 4.9.1 to 4.6 and that should take care of it. Location of the file is in the SDK folder in 4.9.1 folder, here is the path in Windows 7:
```
C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.6\sdks\4.9.1
``` | I confirm the say by **wakqasahmed**
I changed it at Apache Flex 4.10
```
<?xml version="1.0"?>
<flex-sdk-description>
<name>Apache Flex 4.10.0 FP 11.8 AIR 3.8 en_US</name>
<!--version>4.10.0</version-->
<version>4.6.0</version>
<build>20130801</build>
</flex-sdk-description>
```
And the Design mode is enable again!, Thanks |
15,665,980 | I am running Flash Builder 4.6 and just added Apache flex sdk 4.9.1 (build 1447119) to my mac book pro running Moutain Lion and when i tried to do a quick 'hello world' and add a few elements to the stage using design mode i got following error:
>
> The design mode is disabled as the project uses an incompatible version of the flex sdk
>
>
>
My question is if i go beyond the default sdk that shipped with fb 4.6 do I therefore loose the ability to use design mode and have to do everything in source mode?
Also, if i am using windows the error is quite similar when i mouseover on `Design` tab
>
> Design mode not supported - incompatible SDK version - Apache Flex
>
>
>
Thanks | 2013/03/27 | [
"https://Stackoverflow.com/questions/15665980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306792/"
] | There is a hack you can do to get it working (I've done this myself and it works perfectly so far) that involves editing an XML file in the 4.9.1 SDK to trick Flash Builder into thinking it is using Flex 4.6. You'll need to edit the `'flex-sdk-description.xml'` Version tag and change it from 4.9.1 to 4.6 and that should take care of it. Location of the file is in the SDK folder in 4.9.1 folder, here is the path in Windows 7:
```
C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.6\sdks\4.9.1
``` | I have a better trick which doesn't involve cheating Flash Builder about the Flex SDK you are using. It is about patching a single bit in one compiled class. After that, the designer will open no matter the version of Flex you are using.
You can read a bit more about it in my article at:
[Latest Flex SDK in Adobe Flash Builder 4.6](https://tonigodoy.com/blog/latest-flex-sdk-in-adobe-flash-builder-4-6/)
(I've just dared to open a blog, after almost 40 years in the area!),
However, here you have the solution in a nutshell:
You have to patch the class:
com\adobe\flexbuilder\mxml\editor\**MXMLEditor.class**
which is inside:
eclipse\plugins\com.adobe.flexbuilder.mxml.editor**\_4.6.1.335153\mxml.jar**
With an hexadecimal editor, open the file MXMLEditor.class and change the byte:
`3D (61 dec.) at address 0x9D04`
to:
`AC (172 dec.)`
After that, you will be able to use the Flash Builder designer with any version of Flex SDK.
But be cautious and take the appropriate precautions first:
* Do a backup of the .jar file before changing anything.
* Check that the version of your mxml.jar is the same as the above.
* Revise your software license and check that it's ok for you to do the patch. |
15,665,980 | I am running Flash Builder 4.6 and just added Apache flex sdk 4.9.1 (build 1447119) to my mac book pro running Moutain Lion and when i tried to do a quick 'hello world' and add a few elements to the stage using design mode i got following error:
>
> The design mode is disabled as the project uses an incompatible version of the flex sdk
>
>
>
My question is if i go beyond the default sdk that shipped with fb 4.6 do I therefore loose the ability to use design mode and have to do everything in source mode?
Also, if i am using windows the error is quite similar when i mouseover on `Design` tab
>
> Design mode not supported - incompatible SDK version - Apache Flex
>
>
>
Thanks | 2013/03/27 | [
"https://Stackoverflow.com/questions/15665980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306792/"
] | I confirm the say by **wakqasahmed**
I changed it at Apache Flex 4.10
```
<?xml version="1.0"?>
<flex-sdk-description>
<name>Apache Flex 4.10.0 FP 11.8 AIR 3.8 en_US</name>
<!--version>4.10.0</version-->
<version>4.6.0</version>
<build>20130801</build>
</flex-sdk-description>
```
And the Design mode is enable again!, Thanks | I have a better trick which doesn't involve cheating Flash Builder about the Flex SDK you are using. It is about patching a single bit in one compiled class. After that, the designer will open no matter the version of Flex you are using.
You can read a bit more about it in my article at:
[Latest Flex SDK in Adobe Flash Builder 4.6](https://tonigodoy.com/blog/latest-flex-sdk-in-adobe-flash-builder-4-6/)
(I've just dared to open a blog, after almost 40 years in the area!),
However, here you have the solution in a nutshell:
You have to patch the class:
com\adobe\flexbuilder\mxml\editor\**MXMLEditor.class**
which is inside:
eclipse\plugins\com.adobe.flexbuilder.mxml.editor**\_4.6.1.335153\mxml.jar**
With an hexadecimal editor, open the file MXMLEditor.class and change the byte:
`3D (61 dec.) at address 0x9D04`
to:
`AC (172 dec.)`
After that, you will be able to use the Flash Builder designer with any version of Flex SDK.
But be cautious and take the appropriate precautions first:
* Do a backup of the .jar file before changing anything.
* Check that the version of your mxml.jar is the same as the above.
* Revise your software license and check that it's ok for you to do the patch. |
256,271 | Being a beginning programmer myself, I have found much of the content (questions and such) to be far past my knowledge, even in languages I know the basics of (such as HTML). My question is, do you think the content is too advanced for people like me? If so, what can be done about it? If not, why do you think so? | 2014/05/26 | [
"https://meta.stackoverflow.com/questions/256271",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/-1/"
] | To quote the help center (emphasis mine)
>
> Stack Overflow is for **professional** and **enthusiast** programmers, people who write code because they love it. We feel the best Stack Overflow questions have a bit of source code in them
>
>
>
Ultimately Stack Overflow is intended for users to have a basic understanding of programming concepts. You don't need to be an expert, but you are expected to understand enough to be able to understand the answers to your question.
Beginners are absolutely welcome, but users are expected to be able to operate on their own. That means they need to be able to do research on their own and to be able to grasp the basics of the concepts they are asking about. No one will hold your hand and no one will treat you differently just because you are a beginner. | Your concern does not make sense; what are you trying to do with the content? There's all kinds of problems and solutions on Stack Overflow, of all "levels".
If you have a programming problem, and you find a question that seems to be about that problem, but you can't understand either the question itself or the answers, then ask a new question, explaining your problem and *exactly* what you don't understand about the other posts.
There's no other concern that I can see. This isn't a course in school, it's not a social club, it's not a book you're reading chapter by chapter, and it's not a place to learn how to program. It's a place you look (or ask) when you have a coding obstacle that you can describe clearly in a few paragraphs. It's a huge archive of independent search results; hunt through it when you have some difficulty, and post a question if you don't find your answer. |
256,271 | Being a beginning programmer myself, I have found much of the content (questions and such) to be far past my knowledge, even in languages I know the basics of (such as HTML). My question is, do you think the content is too advanced for people like me? If so, what can be done about it? If not, why do you think so? | 2014/05/26 | [
"https://meta.stackoverflow.com/questions/256271",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/-1/"
] | Your concern does not make sense; what are you trying to do with the content? There's all kinds of problems and solutions on Stack Overflow, of all "levels".
If you have a programming problem, and you find a question that seems to be about that problem, but you can't understand either the question itself or the answers, then ask a new question, explaining your problem and *exactly* what you don't understand about the other posts.
There's no other concern that I can see. This isn't a course in school, it's not a social club, it's not a book you're reading chapter by chapter, and it's not a place to learn how to program. It's a place you look (or ask) when you have a coding obstacle that you can describe clearly in a few paragraphs. It's a huge archive of independent search results; hunt through it when you have some difficulty, and post a question if you don't find your answer. | Yes, much of it is too advanced for a beginner! -- thanks to the efforts of thousands of developers and hundreds of notable experts.
As an additional benefit, there is also a great deal of information for the beginner.
A more "beginner-oriented" Stack Overflow that can not answer the advanced, specialized and esoteric questions where people get stuck will not keep a large audience and would not continue to grow and be useful as new technologies are developed. |
256,271 | Being a beginning programmer myself, I have found much of the content (questions and such) to be far past my knowledge, even in languages I know the basics of (such as HTML). My question is, do you think the content is too advanced for people like me? If so, what can be done about it? If not, why do you think so? | 2014/05/26 | [
"https://meta.stackoverflow.com/questions/256271",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/-1/"
] | To quote the help center (emphasis mine)
>
> Stack Overflow is for **professional** and **enthusiast** programmers, people who write code because they love it. We feel the best Stack Overflow questions have a bit of source code in them
>
>
>
Ultimately Stack Overflow is intended for users to have a basic understanding of programming concepts. You don't need to be an expert, but you are expected to understand enough to be able to understand the answers to your question.
Beginners are absolutely welcome, but users are expected to be able to operate on their own. That means they need to be able to do research on their own and to be able to grasp the basics of the concepts they are asking about. No one will hold your hand and no one will treat you differently just because you are a beginner. | Yes, much of it is too advanced for a beginner! -- thanks to the efforts of thousands of developers and hundreds of notable experts.
As an additional benefit, there is also a great deal of information for the beginner.
A more "beginner-oriented" Stack Overflow that can not answer the advanced, specialized and esoteric questions where people get stuck will not keep a large audience and would not continue to grow and be useful as new technologies are developed. |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | As above, though if you want to *capture* the matching substring, then you need a capturing, not a non-capturing group, with the quantifier `+` *within* the group:
`^([^,:]+)(?=.*?:)` | You can do this with lookahead:
```
^(?:[^,:])+(?=.*?:)
```
[Regex101 demo](http://regex101.com/r/lT5sK2/1)
`(?:[^,:])+` captures a sequence of characters that aren't commas or colons.
`(?=.*?:)` requires that this match is followed by any any characters and then a colon somewhere. |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | This might work.
```
# (?s)^(?=.*:[ ]).*?(?=[,:][ ])
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
.*? # Consume minimal any chars up until
(?= [,:] [ ] ) # Lookahead, Comma or colon, then whitespace
```
Or, it could be done without the final lookahead.
```
# (?s)^(?=.*:[ ])[^,:]*
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
[^,:]* # Consume non comma nor colon
``` | You can do this with lookahead:
```
^(?:[^,:])+(?=.*?:)
```
[Regex101 demo](http://regex101.com/r/lT5sK2/1)
`(?:[^,:])+` captures a sequence of characters that aren't commas or colons.
`(?=.*?:)` requires that this match is followed by any any characters and then a colon somewhere. |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | As above, though if you want to *capture* the matching substring, then you need a capturing, not a non-capturing group, with the quantifier `+` *within* the group:
`^([^,:]+)(?=.*?:)` | This pattern should capture what you want:
```
^([^\n,:]+)(?=.*:)
```
Example:
**<http://regex101.com/r/vE0eP4/1>**
![^[^\n,:]+(?=.*:)](https://i.stack.imgur.com/cxeH9.png) |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | As above, though if you want to *capture* the matching substring, then you need a capturing, not a non-capturing group, with the quantifier `+` *within* the group:
`^([^,:]+)(?=.*?:)` | You can do this without lookahead:
```
^(.*?)(?:, .*: |: )
```
This assumes the implementation gives leftmost alternations precedence, which most do. |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | This might work.
```
# (?s)^(?=.*:[ ]).*?(?=[,:][ ])
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
.*? # Consume minimal any chars up until
(?= [,:] [ ] ) # Lookahead, Comma or colon, then whitespace
```
Or, it could be done without the final lookahead.
```
# (?s)^(?=.*:[ ])[^,:]*
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
[^,:]* # Consume non comma nor colon
``` | This pattern should capture what you want:
```
^([^\n,:]+)(?=.*:)
```
Example:
**<http://regex101.com/r/vE0eP4/1>**
![^[^\n,:]+(?=.*:)](https://i.stack.imgur.com/cxeH9.png) |
26,578,449 | I would like to use regex to capture everything in a string up to a colon followed by a space, `:` OR a comma followed by a space, `,` but only using the comma as a condition if the colon with a space can be found in the string. In other words, if there is no `:`, I do not want to capture anything. If there is `:` in the string, I want to capture everything up until it OR up until a `,` if the `,` comes before the `:`.
I am trying with
```
/(?:(?!: )[^])*/g
```
and
```
/(?:(?!: )[^])*/g
```
Some example text:
Here I want to capture only `DeBary`:
```
DeBary, OH: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture only `DeBary`:
```
DeBary: Suddenly on Thursday, June 16, 2011 at the age of 78.
```
Here I want to capture nothing:
```
Suddenly on Thursday, June 16, 2011 at the age of 78.
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26578449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183970/"
] | This might work.
```
# (?s)^(?=.*:[ ]).*?(?=[,:][ ])
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
.*? # Consume minimal any chars up until
(?= [,:] [ ] ) # Lookahead, Comma or colon, then whitespace
```
Or, it could be done without the final lookahead.
```
# (?s)^(?=.*:[ ])[^,:]*
(?s) # Dot-all modifier
^ # BOS
(?= .* : [ ] ) # Lookahead for colon then space
[^,:]* # Consume non comma nor colon
``` | You can do this without lookahead:
```
^(.*?)(?:, .*: |: )
```
This assumes the implementation gives leftmost alternations precedence, which most do. |
122,208 | One point in time, I tried oh my zsh but it causes a lot of issues so I'm back at bash. I'm trying to clean up some files and notice there is a oh my zsh folder. The github instructions tell me to run uninstall oh my zsh but I don't see that script in my folder.
Is it safe to remove `.oh-my-zsh` folder? | 2014/03/30 | [
"https://unix.stackexchange.com/questions/122208",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/63943/"
] | `.oh-my-zsh` isn't used by anything but oh-my-zsh. If you use bash, you can just remove it.
The [instructions](https://github.com/robbyrussell/oh-my-zsh) tell you to run the command `uninstall_oh_my_zsh`. This is a function that you can invoke from zsh running oh-my-zsh. If you aren't running oh-my-zsh, you can run `tools/uninstall.sh`, but all it does is:
* remove `~/.oh-my-zsh`, which you were going to do anyway;
* switch your login shell to bash, which you've already done;
* restore your old `~/.zshrc`, which you didn't have if you never used zsh without oh-my-zsh.
You could also use zsh without oh-my-zsh. | Not totally save, because it could cause leftover configuration from oh-my-zsh.
The setup of oh-my-zsh adds some lines to your zsh startup files, like ~/.zshrc
The uninstall program you already looked for would remove these added lines.
The problem caused by the leftover configutation could make zsh show error messages at start, or stop running the shell startup scripts somewhere inbetween.
All that can be confusing to fix without knowing the scripts.
So, for now, I propose to keep the directory until you found and used the uninstall script.
If you end up running in errors at zsh start related to this, please show the error messages.
(Please clarify which folder to remove you talk about exactly) |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | You can use this script.
<http://pellepim.bitbucket.org/jstz/>
Fork or clone repository here.
<https://bitbucket.org/pellepim/jstimezonedetect>
Once you include the script, you can get the list of timezones in - `jstz.olson.timezones` variable.
And following code is used to determine client browser's timezone.
```
var tz = jstz.determine();
tz.name();
```
Enjoy jstz! | You can simply write your own code by using the mapping table here:
<http://www.timeanddate.com/time/zones/>
or, use moment-timezone library:
<http://momentjs.com/timezone/docs/>
See `zone.name; // America/Los_Angeles`
or, this library:
<https://github.com/Canop/tzdetect.js> |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | If you're already using [Moment.js](https://momentjs.com/timezone/docs/) you can guess the timezone name:
```
moment.tz.guess(); // eg. "America/New York"
``` | In javascript , the Date.getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.
```
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
```
Moment'timezone will be a useful tool.
<http://momentjs.com/timezone/>
**Convert Dates Between Timezones**
```
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
``` |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | If you're already using [Moment.js](https://momentjs.com/timezone/docs/) you can guess the timezone name:
```
moment.tz.guess(); // eg. "America/New York"
``` | You can simply write your own code by using the mapping table here:
<http://www.timeanddate.com/time/zones/>
or, use moment-timezone library:
<http://momentjs.com/timezone/docs/>
See `zone.name; // America/Los_Angeles`
or, this library:
<https://github.com/Canop/tzdetect.js> |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | A short possibility for a result in current user's language:
```js
console.log(new Date().toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long' }).substring(4));
``` | If you're already using [Moment.js](https://momentjs.com/timezone/docs/) you can guess the timezone name:
```
moment.tz.guess(); // eg. "America/New York"
``` |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | Most upvoted [answer](https://stackoverflow.com/a/44935836/5877243) is probably the best way to get the timezone, however, `Intl.DateTimeFormat().resolvedOptions().timeZone` returns IANA timezone name by definition, which is in English.
If you want the timezone's name in current user's language, you can parse it from `Date`'s string representation like so:
```js
function getTimezoneName() {
const today = new Date();
const short = today.toLocaleDateString(undefined);
const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });
// Trying to remove date from the string in a locale-agnostic way
const shortIndex = full.indexOf(short);
if (shortIndex >= 0) {
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);
// by this time `trimmed` should be the timezone's name with some punctuation -
// trim it from both sides
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');
} else {
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
return full;
}
}
console.log(getTimezoneName());
```
Tested in Chrome and Firefox.
Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. `GMT+07:00`) instead of a name. But I think it's still readable as a fallback.
P.S. Won't work in IE11, just as the `Intl...` solution. | This gets the timezone code (e.g., `GMT`) in older javascript (I'm using google app script with old engine):
```
function getTimezoneName() {
return new Date().toString().get(/\((.+)\)/);
}
```
I'm just putting this here in case someone needs it. |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | If you're already using [Moment.js](https://momentjs.com/timezone/docs/) you can guess the timezone name:
```
moment.tz.guess(); // eg. "America/New York"
``` | This gets the timezone code (e.g., `GMT`) in older javascript (I'm using google app script with old engine):
```
function getTimezoneName() {
return new Date().toString().get(/\((.+)\)/);
}
```
I'm just putting this here in case someone needs it. |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | Most upvoted [answer](https://stackoverflow.com/a/44935836/5877243) is probably the best way to get the timezone, however, `Intl.DateTimeFormat().resolvedOptions().timeZone` returns IANA timezone name by definition, which is in English.
If you want the timezone's name in current user's language, you can parse it from `Date`'s string representation like so:
```js
function getTimezoneName() {
const today = new Date();
const short = today.toLocaleDateString(undefined);
const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });
// Trying to remove date from the string in a locale-agnostic way
const shortIndex = full.indexOf(short);
if (shortIndex >= 0) {
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);
// by this time `trimmed` should be the timezone's name with some punctuation -
// trim it from both sides
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');
} else {
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
return full;
}
}
console.log(getTimezoneName());
```
Tested in Chrome and Firefox.
Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. `GMT+07:00`) instead of a name. But I think it's still readable as a fallback.
P.S. Won't work in IE11, just as the `Intl...` solution. | To detect something like "America/New York.", you can use the `new LocalZone()` from the [Luxon library](https://moment.github.io/luxon/api-docs/index.html).
```
import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;
``` |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | You can simply write your own code by using the mapping table here:
<http://www.timeanddate.com/time/zones/>
or, use moment-timezone library:
<http://momentjs.com/timezone/docs/>
See `zone.name; // America/Los_Angeles`
or, this library:
<https://github.com/Canop/tzdetect.js> | This gets the timezone code (e.g., `GMT`) in older javascript (I'm using google app script with old engine):
```
function getTimezoneName() {
return new Date().toString().get(/\((.+)\)/);
}
```
I'm just putting this here in case someone needs it. |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | You can simply write your own code by using the mapping table here:
<http://www.timeanddate.com/time/zones/>
or, use moment-timezone library:
<http://momentjs.com/timezone/docs/>
See `zone.name; // America/Los_Angeles`
or, this library:
<https://github.com/Canop/tzdetect.js> | To detect something like "America/New York.", you can use the `new LocalZone()` from the [Luxon library](https://moment.github.io/luxon/api-docs/index.html).
```
import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;
``` |
9,772,955 | I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9772955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284538/"
] | The [Internationalization API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions) supports getting the user timezone, and is [supported](http://caniuse.com/#feat=internationalization) in all current browsers.
```js
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
```
Keep in mind that on some older browser versions that support the Internationalization API, the `timeZone` property is set to `undefined` rather than the user’s timezone string. As best as I can tell, at the time of writing (July 2017) [all current browsers except for IE11](http://kangax.github.io/compat-table/esintl/#test-DateTimeFormat_resolvedOptions().timeZone_defaults_to_the_host_environment) will return the user timezone as a string. | If you're already using [Moment.js](https://momentjs.com/timezone/docs/) you can guess the timezone name:
```
moment.tz.guess(); // eg. "America/New York"
``` |
60,697,531 | <https://plnkr.co/edit/O4BxVsdOZBc4R68p>
```
fetch(target)
.then(response => response.json())
.then(data => {
var prices = data['Time Series (5min)'];
for (prop in prices) {
var stockPrices = prices[prop]['1. open'];
//change to 2. high, etc
console.log(`${prop} : ${stockPrices}`);
stocksData.datasets[0].data.push({x: prop, y: +stockPrices})
//time x axes are preventing render
window.lineChart.update();
}
})
```
I am getting information from the AlphaVantage API and am trying to graph the time as the X axis and the open price as the Y axis. However, the time from the API is in an odd format and doesn't appear to graph. I have looked into Moment.js but that appears to be making times, not formatting them. Can anyone give me any pointers on graphing the time correct? | 2020/03/15 | [
"https://Stackoverflow.com/questions/60697531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12981681/"
] | Instead of using
```
property.Relational().ColumnType = "decimal(18, 6)";
```
you can use
```
property.SetColumnType("decimal(18, 6)");
``` | Although the *answer* is accepted. But this answer didn't work for me. Another approach worked for me. Sharing below, **maybe someone will need it**.
```
property.SetPrecision(18);
property.SetScale(6);
``` |
25,705 | I've got a win 2003 server running a TFS server, and a Win 2008 server acting as a PDC.
A few days ago, I changed my DHCP and DNS server (which used to be the win 2008 server) to a Cisco Router.
Since then, I've not been able to log in on my TFS server, which keeps complaining that my domain doesn't exists.
I've run dcdiag from my local Admin account to debug :
```
dcdiag /v /s:MYPDC /u:MYDOMAIN\Brann /p:*
```
Which returned me this error:
```
* Active Directory LDAP Services Check
The host 95cb8ce0-ecb1-43e3-87aa-e4ce74fe6._msdcs.MYDOMAIN could not be resolved to an
IP address. Check the DNS server, DHCP, server name, etc
......................... MYPDC failed test Connectivity
```
I changed my DHCP server to use MYPDC as the primary DNS server again, and this error stopped appearing
I restarted the server, confident that the issue was solved, but now I'm getting this :
```
Starting test: VerifyReferences
Some objects relating to the DC IDS-SERVER have problems:
[1] Problem: Missing Expected Value
Base Object: CN=MYPDC,OU=Domain Controllers,DC=MYDOMAIN
Base Object Description: "DC Account Object"
Value Object Attribute Name: frsComputerReferenceBL
Value Object Description: "SYSVOL FRS Member Object"
Recommended Action: See Knowledge Base Article: Q312862
......................... IDS-SERVER failed test VerifyReferences
```
I've tried troubleshooting File Replication service as suggested in Q312862, but I'm stuck at the beginning :
```
C:\Documents and Settings\Administrator>ntfrsutl ds TFS
ERROR - Cannot bind w/authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot bind w/o authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot RPC to computer, TFS; 000006d9 (1753)
C:\Documents and Settings\Administrator>ntfrsutl ds MYPDC
ERROR - Cannot RPC to computer, MYPDC; 000006d2 (1746)
```
Any ideas on what to try next?
Btw, other Vista computers on this domain can login just fine. | 2009/06/15 | [
"https://serverfault.com/questions/25705",
"https://serverfault.com",
"https://serverfault.com/users/1725/"
] | >
> I changed my DHCP and DNS server
>
>
>
Just a thought ...
Did you move all of your service records (SRV) when you switched to the new DNS server? Active Directory *really* needs those records to operate. Without the SRV records you have no way of telling clients where your LDAP and Kerberos servers are (which is your PDC/GC).
Oh ... and was your TFS using DHCP? | An obvious test perhaps, but if you fire up a command prompt on the 2003 server and type nslookup does it display something like:
```
c:\temp>nslookup
Default Server: mypdc.mydomain.local
Address: 192.168.1.1
```
and if you now type:
```
mypdc.mydomain.local
```
does it correctly resolve the PDC name?
JR
Edit: It looks as if DNS is OK or at least your 2k3 server is correctly using mypdc as the DNS server. Presumably you're logging into the 2k3 server as a local account if the domain account doesn't work. When you're logged in, if you open a command prompt and type:
```
net use \\mypdc\ipc$ /user:mydomain\administrator
```
(obviously replace "mydomain" by your domain name) and then feed in the domain administrator password, does this work?
Also is there anything relevant in the Security log on mypdc? |
25,705 | I've got a win 2003 server running a TFS server, and a Win 2008 server acting as a PDC.
A few days ago, I changed my DHCP and DNS server (which used to be the win 2008 server) to a Cisco Router.
Since then, I've not been able to log in on my TFS server, which keeps complaining that my domain doesn't exists.
I've run dcdiag from my local Admin account to debug :
```
dcdiag /v /s:MYPDC /u:MYDOMAIN\Brann /p:*
```
Which returned me this error:
```
* Active Directory LDAP Services Check
The host 95cb8ce0-ecb1-43e3-87aa-e4ce74fe6._msdcs.MYDOMAIN could not be resolved to an
IP address. Check the DNS server, DHCP, server name, etc
......................... MYPDC failed test Connectivity
```
I changed my DHCP server to use MYPDC as the primary DNS server again, and this error stopped appearing
I restarted the server, confident that the issue was solved, but now I'm getting this :
```
Starting test: VerifyReferences
Some objects relating to the DC IDS-SERVER have problems:
[1] Problem: Missing Expected Value
Base Object: CN=MYPDC,OU=Domain Controllers,DC=MYDOMAIN
Base Object Description: "DC Account Object"
Value Object Attribute Name: frsComputerReferenceBL
Value Object Description: "SYSVOL FRS Member Object"
Recommended Action: See Knowledge Base Article: Q312862
......................... IDS-SERVER failed test VerifyReferences
```
I've tried troubleshooting File Replication service as suggested in Q312862, but I'm stuck at the beginning :
```
C:\Documents and Settings\Administrator>ntfrsutl ds TFS
ERROR - Cannot bind w/authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot bind w/o authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot RPC to computer, TFS; 000006d9 (1753)
C:\Documents and Settings\Administrator>ntfrsutl ds MYPDC
ERROR - Cannot RPC to computer, MYPDC; 000006d2 (1746)
```
Any ideas on what to try next?
Btw, other Vista computers on this domain can login just fine. | 2009/06/15 | [
"https://serverfault.com/questions/25705",
"https://serverfault.com",
"https://serverfault.com/users/1725/"
] | Active Directory rides DNS, and works best/most completely when the AD server is the DNS server for the domain members.
For some reason, using an alternative DNS server results in some requests not being passed through to the AD server, resulting in incomplete functionality. | An obvious test perhaps, but if you fire up a command prompt on the 2003 server and type nslookup does it display something like:
```
c:\temp>nslookup
Default Server: mypdc.mydomain.local
Address: 192.168.1.1
```
and if you now type:
```
mypdc.mydomain.local
```
does it correctly resolve the PDC name?
JR
Edit: It looks as if DNS is OK or at least your 2k3 server is correctly using mypdc as the DNS server. Presumably you're logging into the 2k3 server as a local account if the domain account doesn't work. When you're logged in, if you open a command prompt and type:
```
net use \\mypdc\ipc$ /user:mydomain\administrator
```
(obviously replace "mydomain" by your domain name) and then feed in the domain administrator password, does this work?
Also is there anything relevant in the Security log on mypdc? |
25,705 | I've got a win 2003 server running a TFS server, and a Win 2008 server acting as a PDC.
A few days ago, I changed my DHCP and DNS server (which used to be the win 2008 server) to a Cisco Router.
Since then, I've not been able to log in on my TFS server, which keeps complaining that my domain doesn't exists.
I've run dcdiag from my local Admin account to debug :
```
dcdiag /v /s:MYPDC /u:MYDOMAIN\Brann /p:*
```
Which returned me this error:
```
* Active Directory LDAP Services Check
The host 95cb8ce0-ecb1-43e3-87aa-e4ce74fe6._msdcs.MYDOMAIN could not be resolved to an
IP address. Check the DNS server, DHCP, server name, etc
......................... MYPDC failed test Connectivity
```
I changed my DHCP server to use MYPDC as the primary DNS server again, and this error stopped appearing
I restarted the server, confident that the issue was solved, but now I'm getting this :
```
Starting test: VerifyReferences
Some objects relating to the DC IDS-SERVER have problems:
[1] Problem: Missing Expected Value
Base Object: CN=MYPDC,OU=Domain Controllers,DC=MYDOMAIN
Base Object Description: "DC Account Object"
Value Object Attribute Name: frsComputerReferenceBL
Value Object Description: "SYSVOL FRS Member Object"
Recommended Action: See Knowledge Base Article: Q312862
......................... IDS-SERVER failed test VerifyReferences
```
I've tried troubleshooting File Replication service as suggested in Q312862, but I'm stuck at the beginning :
```
C:\Documents and Settings\Administrator>ntfrsutl ds TFS
ERROR - Cannot bind w/authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot bind w/o authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot RPC to computer, TFS; 000006d9 (1753)
C:\Documents and Settings\Administrator>ntfrsutl ds MYPDC
ERROR - Cannot RPC to computer, MYPDC; 000006d2 (1746)
```
Any ideas on what to try next?
Btw, other Vista computers on this domain can login just fine. | 2009/06/15 | [
"https://serverfault.com/questions/25705",
"https://serverfault.com",
"https://serverfault.com/users/1725/"
] | >
> I changed my DHCP and DNS server
>
>
>
Just a thought ...
Did you move all of your service records (SRV) when you switched to the new DNS server? Active Directory *really* needs those records to operate. Without the SRV records you have no way of telling clients where your LDAP and Kerberos servers are (which is your PDC/GC).
Oh ... and was your TFS using DHCP? | Active Directory rides DNS, and works best/most completely when the AD server is the DNS server for the domain members.
For some reason, using an alternative DNS server results in some requests not being passed through to the AD server, resulting in incomplete functionality. |
25,705 | I've got a win 2003 server running a TFS server, and a Win 2008 server acting as a PDC.
A few days ago, I changed my DHCP and DNS server (which used to be the win 2008 server) to a Cisco Router.
Since then, I've not been able to log in on my TFS server, which keeps complaining that my domain doesn't exists.
I've run dcdiag from my local Admin account to debug :
```
dcdiag /v /s:MYPDC /u:MYDOMAIN\Brann /p:*
```
Which returned me this error:
```
* Active Directory LDAP Services Check
The host 95cb8ce0-ecb1-43e3-87aa-e4ce74fe6._msdcs.MYDOMAIN could not be resolved to an
IP address. Check the DNS server, DHCP, server name, etc
......................... MYPDC failed test Connectivity
```
I changed my DHCP server to use MYPDC as the primary DNS server again, and this error stopped appearing
I restarted the server, confident that the issue was solved, but now I'm getting this :
```
Starting test: VerifyReferences
Some objects relating to the DC IDS-SERVER have problems:
[1] Problem: Missing Expected Value
Base Object: CN=MYPDC,OU=Domain Controllers,DC=MYDOMAIN
Base Object Description: "DC Account Object"
Value Object Attribute Name: frsComputerReferenceBL
Value Object Description: "SYSVOL FRS Member Object"
Recommended Action: See Knowledge Base Article: Q312862
......................... IDS-SERVER failed test VerifyReferences
```
I've tried troubleshooting File Replication service as suggested in Q312862, but I'm stuck at the beginning :
```
C:\Documents and Settings\Administrator>ntfrsutl ds TFS
ERROR - Cannot bind w/authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot bind w/o authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot RPC to computer, TFS; 000006d9 (1753)
C:\Documents and Settings\Administrator>ntfrsutl ds MYPDC
ERROR - Cannot RPC to computer, MYPDC; 000006d2 (1746)
```
Any ideas on what to try next?
Btw, other Vista computers on this domain can login just fine. | 2009/06/15 | [
"https://serverfault.com/questions/25705",
"https://serverfault.com",
"https://serverfault.com/users/1725/"
] | >
> I changed my DHCP and DNS server
>
>
>
Just a thought ...
Did you move all of your service records (SRV) when you switched to the new DNS server? Active Directory *really* needs those records to operate. Without the SRV records you have no way of telling clients where your LDAP and Kerberos servers are (which is your PDC/GC).
Oh ... and was your TFS using DHCP? | For the record, I eventually left/rejoined the domain and it solved the problem.
I wanted to avoid this solution because my TFS server was a certification authority, thus preventing any domain/name change on it without messing with the installation, but in most scenario it shouldn't be a problem |
25,705 | I've got a win 2003 server running a TFS server, and a Win 2008 server acting as a PDC.
A few days ago, I changed my DHCP and DNS server (which used to be the win 2008 server) to a Cisco Router.
Since then, I've not been able to log in on my TFS server, which keeps complaining that my domain doesn't exists.
I've run dcdiag from my local Admin account to debug :
```
dcdiag /v /s:MYPDC /u:MYDOMAIN\Brann /p:*
```
Which returned me this error:
```
* Active Directory LDAP Services Check
The host 95cb8ce0-ecb1-43e3-87aa-e4ce74fe6._msdcs.MYDOMAIN could not be resolved to an
IP address. Check the DNS server, DHCP, server name, etc
......................... MYPDC failed test Connectivity
```
I changed my DHCP server to use MYPDC as the primary DNS server again, and this error stopped appearing
I restarted the server, confident that the issue was solved, but now I'm getting this :
```
Starting test: VerifyReferences
Some objects relating to the DC IDS-SERVER have problems:
[1] Problem: Missing Expected Value
Base Object: CN=MYPDC,OU=Domain Controllers,DC=MYDOMAIN
Base Object Description: "DC Account Object"
Value Object Attribute Name: frsComputerReferenceBL
Value Object Description: "SYSVOL FRS Member Object"
Recommended Action: See Knowledge Base Article: Q312862
......................... IDS-SERVER failed test VerifyReferences
```
I've tried troubleshooting File Replication service as suggested in Q312862, but I'm stuck at the beginning :
```
C:\Documents and Settings\Administrator>ntfrsutl ds TFS
ERROR - Cannot bind w/authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot bind w/o authentication to computer, TFS; 000006d9 (1753)
ERROR - Cannot RPC to computer, TFS; 000006d9 (1753)
C:\Documents and Settings\Administrator>ntfrsutl ds MYPDC
ERROR - Cannot RPC to computer, MYPDC; 000006d2 (1746)
```
Any ideas on what to try next?
Btw, other Vista computers on this domain can login just fine. | 2009/06/15 | [
"https://serverfault.com/questions/25705",
"https://serverfault.com",
"https://serverfault.com/users/1725/"
] | Active Directory rides DNS, and works best/most completely when the AD server is the DNS server for the domain members.
For some reason, using an alternative DNS server results in some requests not being passed through to the AD server, resulting in incomplete functionality. | For the record, I eventually left/rejoined the domain and it solved the problem.
I wanted to avoid this solution because my TFS server was a certification authority, thus preventing any domain/name change on it without messing with the installation, but in most scenario it shouldn't be a problem |
68,724,626 | I'm trying to learn Haskell by solving exercises and looking at others solutions when i'm stuck. Been having trouble understanding as functions get more complex.
```
-- Ex 5: given a list of lists, return the longest list. If there
-- are multiple lists of the same length, return the list that has
-- the smallest _first element_.
--
-- (If multiple lists have the same length and same first element,
-- you can return any one of them.)
--
-- Give the longest function a suitable type.
--
-- Examples:
-- longest [[1,2,3],[4,5],[6]] ==> [1,2,3]
-- longest ["bcd","def","ab"] ==> "bcd"
longest :: (Foldable t, Ord a) => t [a] -> [a]
longest xs = foldl1 comp xs
where
comp acc x | length acc > length x = acc
| length acc == length x = if head acc < head x then acc else x
| otherwise = x
```
So foldl1 works as follows - `input: foldl1 (+) [1,2,3,4] output: 10.` As I understand it, it takes a function applies it to a list and "folds" it. The thing I don't understand is that `comp acc x` compares **two lists** and outputs the larger length **list**.
The thing I don't understand is with `longest xs = foldl1 comp xs`. How are **two lists** provided to comp to compare and what is foldl1 "folding" and what is the **start** accumulator?
Here is another shorter example of another fold that I thought I understood.
```
foldl - input: foldl (\x y -> x + y) 0 [1,2,3] output: 6
```
It starts at 0 and adds each element from left one by one. How does foldl exactly apply the `two variables` in the anonymous function. For instance if the anonymous function was (\x y z-> x + y + z) it would fail which I don't yet understand why. | 2021/08/10 | [
"https://Stackoverflow.com/questions/68724626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16533351/"
] | I think your current notion of what `foldl1/foldl` does is not quite accurate. As others already explained `foldl1 f (x:xs) == foldl f x xs` so the first value in the list is taken as an accumulator.
You say that `foldl1 (+) list` takes each value of the `list` "one by one" and computes the sum. I think this notion is misleaing: Actually you do always take two values, add them and get an intermediate result. And you repeat that over and over again with one of the values being the intermediate result of the last. I really like following illustration:
[![enter image description here](https://i.stack.imgur.com/aMAoH.png)](https://i.stack.imgur.com/aMAoH.png)
[Source](https://cs.famaf.unc.edu.ar/%7Ehoffmann/pd18/martes23.html)
If you start to think about these intermediate values, it will make more sense that you always get the largets one. | I think it is easiest to understand if you look at a symbolic example:
```
foldl k z [a, b, c] = k (k (k z a) b) c
foldl1 k [a, b, c] = k (k a b) c
```
As you can see `foldl1` just starts with the first two arguments and then adds on the rest one by one using `k` to combine it with the accumulator.
And `foldl` starts by applying `k` to the initial accumulator `z` and the first element `a` and then adds on the rest one by one.
The `k` function only ever gets two arguments, so you cannot use a function with three arguments for that. |
8,392,754 | I have a cube geometry and a mesh, and i don't know how to change the width (or height... i can change x, y and z though).
Here's a snippet of what i have right now:
```
geometry = new THREE.CubeGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
// WebGL renderer here
function render(){
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
function changeStuff(){
mesh.geometry.width = 500; //Doesn't work.
mesh.width = 500; // Doesn't work.
geometry.width = 500; //Doesn't work.
mesh.position.x = 500// Works!!
render();
}
```
Thanks!
**EDIT**
Found a solution:
```
mesh.scale.x = 500;
``` | 2011/12/05 | [
"https://Stackoverflow.com/questions/8392754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313194/"
] | Just to complete comment and solution from question (and have an answer present with example code):
```js
// create a cube, 1 unit for width, height, depth
var geometry = new THREE.CubeGeometry(1,1,1);
// each cube side gets another color
var cubeMaterials = [
new THREE.MeshBasicMaterial({color:0x33AA55, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x55CC00, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x0000FF, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x5555AA, transparent:true, opacity:0.8}),
];
// create a MeshFaceMaterial, allows cube to have different materials on each face
var cubeMaterial = new THREE.MeshFaceMaterial(cubeMaterials);
var cube = new THREE.Mesh(geometry, cubeMaterial);
cube.position.set(0,0,0);
scene.add( cube );
cube.scale.x = 2.5; // SCALE
cube.scale.y = 2.5; // SCALE
cube.scale.z = 2.5; // SCALE
```
A slightly advanced, dynamic [example](https://www.matheretter.de/rechner/quader) (still the same scaling) implemented here: | Scale properties can be used to for changing width, height and and depth of cube.
```
//creating a cube
var geometry = new THREE.BoxGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial({color:"white"});
var cube = new THREE.Mesh(geometry, material);
//changing size of cube which is created.
cube.scale.x = 30;
cube.scale.y = 30;
cube.scale.z = 30;
``` |
8,392,754 | I have a cube geometry and a mesh, and i don't know how to change the width (or height... i can change x, y and z though).
Here's a snippet of what i have right now:
```
geometry = new THREE.CubeGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
// WebGL renderer here
function render(){
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
function changeStuff(){
mesh.geometry.width = 500; //Doesn't work.
mesh.width = 500; // Doesn't work.
geometry.width = 500; //Doesn't work.
mesh.position.x = 500// Works!!
render();
}
```
Thanks!
**EDIT**
Found a solution:
```
mesh.scale.x = 500;
``` | 2011/12/05 | [
"https://Stackoverflow.com/questions/8392754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313194/"
] | Just to complete comment and solution from question (and have an answer present with example code):
```js
// create a cube, 1 unit for width, height, depth
var geometry = new THREE.CubeGeometry(1,1,1);
// each cube side gets another color
var cubeMaterials = [
new THREE.MeshBasicMaterial({color:0x33AA55, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x55CC00, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x0000FF, transparent:true, opacity:0.8}),
new THREE.MeshBasicMaterial({color:0x5555AA, transparent:true, opacity:0.8}),
];
// create a MeshFaceMaterial, allows cube to have different materials on each face
var cubeMaterial = new THREE.MeshFaceMaterial(cubeMaterials);
var cube = new THREE.Mesh(geometry, cubeMaterial);
cube.position.set(0,0,0);
scene.add( cube );
cube.scale.x = 2.5; // SCALE
cube.scale.y = 2.5; // SCALE
cube.scale.z = 2.5; // SCALE
```
A slightly advanced, dynamic [example](https://www.matheretter.de/rechner/quader) (still the same scaling) implemented here: | You can dispose the geometry of cube and affect the new one like this :
```
let new_geometry = new THREE.CubeGeometry(500,200,200);
geometry.dispose();
cube.geometry = new_geometry;
``` |
8,392,754 | I have a cube geometry and a mesh, and i don't know how to change the width (or height... i can change x, y and z though).
Here's a snippet of what i have right now:
```
geometry = new THREE.CubeGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
// WebGL renderer here
function render(){
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
function changeStuff(){
mesh.geometry.width = 500; //Doesn't work.
mesh.width = 500; // Doesn't work.
geometry.width = 500; //Doesn't work.
mesh.position.x = 500// Works!!
render();
}
```
Thanks!
**EDIT**
Found a solution:
```
mesh.scale.x = 500;
``` | 2011/12/05 | [
"https://Stackoverflow.com/questions/8392754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313194/"
] | You can dispose the geometry of cube and affect the new one like this :
```
let new_geometry = new THREE.CubeGeometry(500,200,200);
geometry.dispose();
cube.geometry = new_geometry;
``` | Scale properties can be used to for changing width, height and and depth of cube.
```
//creating a cube
var geometry = new THREE.BoxGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial({color:"white"});
var cube = new THREE.Mesh(geometry, material);
//changing size of cube which is created.
cube.scale.x = 30;
cube.scale.y = 30;
cube.scale.z = 30;
``` |
26,957,520 | I am making a Guess the Number game in Python, and I want to make Python keep score of how many times it took you to guess the number before you got it right. How would I go about doing this? If needed, I can post my code to view. Thank you.
```
import time
import os
from random import randrange, uniform
#Difficulty - Easy
def easy():
print ("")
print ("Difficulty: Easy")
print ("")
irand = randrange(1,10)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Easy" + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Medium
def medium():
print ("")
print ("Difficulty: Medium")
print ("")
irand = randrange(1,100)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Medium" + "\n")
while True:
number = input("Pick a number 1 - 100: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Hard
def hard():
print ("")
print ("Difficulty: Hard")
print ("")
irand = randrange(1,1000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Hard" + "\n")
while True:
number = input("Pick a number 1 - 1,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Ultra
def ultra():
print ("")
print ("Difficulty: Ultra")
print ("")
irand = randrange(1,100000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Ultra" + "\n")
while True:
number = input("Pick a number 1 - 100,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#Difficulty - Master
def master():
print ("")
print ("Difficulty: Master")
print ("")
irand = randrange(1,1000000)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Master" + "\n")
while True:
number = input("Pick a number 1 - 1,000,000: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
#This is the MainMenu
def main():
time.sleep(2)
while True:
print ("Please select a difficulty when prompted!")
time.sleep(1)
print ("[1] Easy")
time.sleep(1)
print ("[2] Medium")
time.sleep(1)
print ("[3] Hard")
time.sleep(1)
print ("[4] Ultra")
time.sleep(1)
print ("[5] Master")
time.sleep(1)
print ("[6] Exit")
print ("")
time.sleep(1)
choice = input ("Please Choose: ")
if choice == '1':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
easy()
elif choice == '2':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
medium()
elif choice == '3':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
hard()
elif choice == '4':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
ultra()
elif choice == '5':
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
master()
elif choice == '6':
time.sleep(2)
print ("")
print ("Exiting the game!")
print ("")
print ("3")
time.sleep(0.5)
print ("2")
time.sleep(0.5)
print ("1")
time.sleep(2)
SystemExit
else:
print ("Invalid Option: Please select from those available.")
print("")
time.sleep(1)
print ("Welcome to GTN!")
time.sleep(2)
print ("Developed by: oysterDev")
time.sleep(2)
print ("Version 1.1.0")
print (" ")
main()
``` | 2014/11/16 | [
"https://Stackoverflow.com/questions/26957520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | @Benjamin's answer would work. But to answer your question about how to start enforcing DRY, you could do something like this:
Your whole main game code could go into this function, taking in some key parameters that define the hardness:
```
def the_game(difficulty_name, range_start, range_end):
score = 0
print ("")
print ("Difficulty: %s" % difficulty_name)
print ("")
irand = randrange(range_start, range_end)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " %s" % difficulty_name + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
score += 1
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
score += 1
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
print("You guessed wrong " + str(score) + " times")
time.sleep(2)
main()
break
```
Then you could define little functions that call the game based on the hardness level chosen by the user, like so:
```
#Difficulty - Easy
def easy():
the_game("Easy", 1, 10)
#Difficulty - Medium
def medium():
the_game("Medium", 1, 100)
#Difficulty - Hard
def hard():
the_game("Hard", 1, 1000)
#Difficulty - Ultra
def ultra():
the_game("Ultra", 1, 100000)
#Difficulty - Master
def master():
the_game("Master", 1, 1000000)
```
And finally, you can define the main function like so:
```
#This is the MainMenu
def main():
time.sleep(2)
while True:
print ("Please select a difficulty when prompted!")
time.sleep(1)
print ("[1] Easy")
time.sleep(1)
print ("[2] Medium")
time.sleep(1)
print ("[3] Hard")
time.sleep(1)
print ("[4] Ultra")
time.sleep(1)
print ("[5] Master")
time.sleep(1)
print ("[6] Exit")
print ("")
time.sleep(1)
choice = input ("Please Choose: ")
def show_loading_screen():
time.sleep(2)
print ("")
print ("Loading game...")
time.sleep(2)
def show_exit_screen():
time.sleep(2)
print ("")
print ("Exiting the game!")
print ("")
print ("3")
time.sleep(0.5)
print ("2")
time.sleep(0.5)
print ("1")
time.sleep(2)
if choice == '1':
show_loading_screen()
easy()
elif choice == '2':
show_loading_screen()
medium()
elif choice == '3':
show_loading_screen()
hard()
elif choice == '4':
show_loading_screen()
ultra()
elif choice == '5':
show_loading_screen()
master()
elif choice == '6':
show_exit_screen()
SystemExit
else:
print ("Invalid Option: Please select from those available.")
print("")
time.sleep(1)
```
You will find that we have extracted some repeating screen loading lines of code into inline functions, that we can reuse.
In the end, you can call this main function IF this Python file is being executed as a script. This is a good practice. You can do it like so:
```
if __name__ == "__main__":
print ("Welcome to GTN!")
time.sleep(2)
print ("Developed by: oysterDev")
time.sleep(2)
print ("Version 1.1.0")
print (" ")
main()
```
Hopefully, this was helpful to understand how to start refactoring for DRY. | try to make a variable named ex. "score" and add 1 to it every time they guess wrong.
this should work.
```
def easy():
score = 0
print ("")
print ("Difficulty: Easy")
print ("")
irand = randrange(1,10)
with open("GTN.txt", "a") as text_file:
text_file.write(str(irand) + " Easy" + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
score += 1
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
score += 1
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
print("You guessed wrong " + str(score) + " times")
time.sleep(2)
main()
break
```
hope it helps. |
17,667,876 | We are planning to use Stash. To my knowledge we already have a Git installation and need to configure Stash to use it. My understanding is that Stash can help configure branches, merges, and other stuff.
So do my development teams need to use Stash to check in code or should they use another Git client? Is Stash used only by the admin to configure the repositories? | 2013/07/16 | [
"https://Stackoverflow.com/questions/17667876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1550705/"
] | What Atlassian's Stash brings to the party is a really easy way to administer git behind the firewall (or at least self hosted) - to create repositories, assign user permissions to said repositories and also a really slick user interface to see whats going on.
Can you manage without it? Sure, but it's sometimes so much nicer to just use a nice UI rather than remember the commands.
Git clients (such as [SourceTree](http://www.sourcetreeapp.com/)) give you a client-side UI to connect to the repository and perform the various commands.
There is also the ability to browse projects and repositories in Stash (discovery!) - something that's only present in git clients if you've already added all the repo URLs. | Stash has many features one among them is Pull request. This option provides capability of reviewing the code. You can write your own plugins with the Java api provided by Stash.
Branching Strategies are simple to maintain in Stash.
with these Stash is easy to maintain :).
Git client 1.8 and above should be used if you are using Stash.
Is there any other tool like stash? yes gitolite is the tool which does the same task. Gitolite is opensource. |
569,261 | Is there a continuous function $f:S^1 \to \mathbb R$ which is one-one? | 2013/11/16 | [
"https://math.stackexchange.com/questions/569261",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/109238/"
] | Suppose such a function $f$ exists. $f(S^1)$ must be connected and compact. $f$ is one-one so it cannot be constant. It follows that $f(S^1) = [a, b]$ for $a \ne b$.
Pick a point $s \in S^1$ such that $f(s) \not\in \{a, b\}$. $S^1 - \{s\}$ is connected, but $[a, b] - \{f(s)\}$ is not. We conclude that such a function $f$ cannot exist.
---
Alternatively, if you're familiar with the concept of the fundamental group: The restriction $f : S^1 \to f(S^1)$ must be a homeomorphism (being a continuous bijection from a compact space onto a Hausdorff space). But we know that $\pi\_1(S^1) = \mathbb Z$ whereas any connected subset of $\mathbb R$ is contractible; hence it has a trivial fundamental group. | Suppose such a function exists. Let $u : [0,1] \to S^1$ be a suitable path that traces around the circle, and consider $g = fu$. This $g : [0,1] \to \mathbb R$ is one-to-one except that $g(0) = g(1)$.
Consider $y = g(1/2)$. It must be either greater than or less than $g(0)$. Pick some value $z$ between $g(0)$ and $y$. Apply the intermediate value theorem on both the intervals $[0,1/2]$ and $[1/2,1]$ and show that there must be some $c$ and $d$ in $(0,1/2)$ and $(1/2,1)$ respectively with $g(c) = g(d) = z$, contradicting $g$ being one-to-one.
In simple terms: the function must go either up or down from where it starts, but then it needs to go back through territory it's already visited to get back to the first point. |
569,261 | Is there a continuous function $f:S^1 \to \mathbb R$ which is one-one? | 2013/11/16 | [
"https://math.stackexchange.com/questions/569261",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/109238/"
] | Suppose such a function $f$ exists. $f(S^1)$ must be connected and compact. $f$ is one-one so it cannot be constant. It follows that $f(S^1) = [a, b]$ for $a \ne b$.
Pick a point $s \in S^1$ such that $f(s) \not\in \{a, b\}$. $S^1 - \{s\}$ is connected, but $[a, b] - \{f(s)\}$ is not. We conclude that such a function $f$ cannot exist.
---
Alternatively, if you're familiar with the concept of the fundamental group: The restriction $f : S^1 \to f(S^1)$ must be a homeomorphism (being a continuous bijection from a compact space onto a Hausdorff space). But we know that $\pi\_1(S^1) = \mathbb Z$ whereas any connected subset of $\mathbb R$ is contractible; hence it has a trivial fundamental group. | It cannot be 1-1 because of the one-dimensional version of Borsuk-Ulam: for every continuous $f: S^1 \rightarrow \mathbb{R}$ there exists an $x \in S^1$ such that $f(x) = f(-x)$.
The proof in the one-dimensional case (it's true for all $S^n$ and $\mathbb{R}^n$ but harder to prove) is not very hard: define $g(x) = f(x) - f(-x)$. Suppose for some $p \in S^1$, $g(p) \neq 0$ (otherwise we would be done anyway), then $g(-p) = -g(p)$ by definition and so then $g$ assumes positive and negative values in $\mathbb{R}$, and so also assumes the value $0$ by the intermediate value theorem (we use the connectedness of $S^1$). And we are done for such a value: $g(x) = 0$ iff $f(x) = f(-x)$. |
32,323,320 | ```
#include
int main()
{
//code
return 0;
}
```
Now here I haven't mentioned the name of any file so is it a part of compile-time error or the pre-processor would take care of it ,i.e. can this exclusion of header file considered a part of compile-time error(syntax error) or not ? | 2015/09/01 | [
"https://Stackoverflow.com/questions/32323320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080828/"
] | The ISO C standard specifies the behaviour of both the preprocessor *and* compiler stages, there are various translation phases which make up the whole "chain" (see `C11 5.1.1.2 Translation phases` for details).
Since the standard `C11 6.10.2 Source file inclusion` specifically states the format of an include directive must be one of the forms:
```
# include <h-char-sequence> new-line
# include "q-char-sequence" new-line
# include pp-tokens new-line
```
(with the latter being subject to macro replacement but required to end up as one of the first two forms), that means what you have is definitely a syntax error. | 1. `#include` is handled by the C pre-processor.
2. The line
```
#include
```
is incomplete.
3. Pre-processessing fails.
Conclusion:
No, this won't result in a "compiler-error" (as the compiling phase is not even reached) but in a pre-processor-error. |
32,323,320 | ```
#include
int main()
{
//code
return 0;
}
```
Now here I haven't mentioned the name of any file so is it a part of compile-time error or the pre-processor would take care of it ,i.e. can this exclusion of header file considered a part of compile-time error(syntax error) or not ? | 2015/09/01 | [
"https://Stackoverflow.com/questions/32323320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080828/"
] | The standard supports three forms of `#include`.
```
# include <h-char-sequence> new-line
# include "q-char-sequence" new-line
# include pp-tokens new-line
```
with the caveat that the last form must transform to one of the first two forms.
Your code is not any of the above three forms. Hence, it is not legal. | 1. `#include` is handled by the C pre-processor.
2. The line
```
#include
```
is incomplete.
3. Pre-processessing fails.
Conclusion:
No, this won't result in a "compiler-error" (as the compiling phase is not even reached) but in a pre-processor-error. |
69,142,868 | I have 3 files in current directory
```
t1
t2
t3
```
Command
```
for x in t* ; do echo $x ; done
```
returns
```
t1
t2
t3
```
How does for loop knows x is a file? | 2021/09/11 | [
"https://Stackoverflow.com/questions/69142868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15190838/"
] | This is due to Bash's [Shell-Expansions](https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions), and more specifically [Filename-Expansions](https://www.gnu.org/software/bash/manual/bash.html#Filename-Expansion) and [Pattern-Matching](https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching). You are using the `*` wildcard which matches "Matches any string, including the null string." So any files in the current directory that matching `t*` will be iterated over in the for loop. In this case it is just t1, t2, and t3.
That being said, Bash itself doesn't have the concept of "files" rather these are simple strings that point to a specific path on the file system, which can then be used with other commands. You can test if something is a file with the `-f` flag to the `test` command. | The `for-loop` does not know anything about files. This is due to the [evaluation of the globs](https://mywiki.wooledge.org/glob). |
64,020,959 | is there an example to change color of the text based on conditions?
for example i want to make condition when `$hasil>=80` it will turn green color, `$hasil>=70` yellow, and below that is red color.
here's my logic code
```php
while ($data = mysqli_fetch_assoc($result))
{
$n1 = ($data["nilai_output"]) * 0.7;
$n2 = ($data["nilai_atasan"]) * 0.1;
$n3 = ($data["nilai_learning"]) * 0.1;
$n4 = ($data["nilai_kedisiplinan"]) * 0.05;
$n5 = ($data["nilai_5r"]) * 0.05;
$hasil = ($n1 + $n2 + $n3 + $n4 + $n5);
if ($hasil >= 95)
{
$grade = 1.25;
$ikk = "istemewa";
}
elseif ($hasil >= 90)
{
$grade = 1.10;
$ikk = "Sangat Memuaskan";
}
elseif ($hasil >= 85)
{
$grade = 1.00;
$ikk = "Memuaskan";
}
elseif ($hasil >= 80)
{
$grade = 0.90;
$ikk = "Cukup Memuaskan";
}
elseif ($hasil >= 75)
{
$grade = 0.75;
$ikk = "Memadai";
}
elseif ($hasil >= 70)
{
$grade = 0.50;
$ikk = "Kurang Memadai";
}
elseif ($hasil >= 1)
{
$grade = 0.25;
$ikk = "Tidak Memadai";
}
else
{
$ikk = "Tidak Berkontribusi";
}
$no++;
```
and here's my table column
```
<td class="font-weight-bold text-danger"><?php echo $hasil;?></td>
<td class="font-weight-bold text-danger"><?php echo $grade;?></td>
<td class="font-weight-bold text-danger"><?php echo $ikk;?></td>
```
i want that those three column is using color condition
thanks before | 2020/09/23 | [
"https://Stackoverflow.com/questions/64020959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12463715/"
] | Try like this
```
if ($hasil >= 80) {
$grade = 0.90;
$color = 'green';
$ikk = "Cukup Memuaskan";
}elseif($hasil >= 70 && $hasil < 80 ) {
$grade = 0.75;
$color = 'yellow';
$ikk = "Memadai";
}elseif($hasil >= 1 && $hasil < 70 ) {
$grade = 0.50;
$color = 'red';
$ikk = "Kurang Memadai";
}else{
$ikk = "Tidak Berkontribusi";
}
<td class="font-weight-bold text-danger" style="color:<?=$color;?>"><?php echo $hasil;?></td>
```
I hope this is helps you! | there are many ways to do what you want. Here's one.
```php
if ($hasil >= 80) {
$color = 'green';
}
elseif ($hasil >= 70) {
$color = 'yellow';
}
else {
$color = 'red';
}
```
then inside your html
```html
<td class="font-weight-bold text-danger <?php echo $color ?>"><?php echo $hasil ?></td>
```
and finally css
```css
.green {
color: green;
}
.yellow {
color: yellow;
}
.red {
color: red;
}
``` |
121,663 | I'd like to find a way to add holes caused by a 'bomb' to my floor sprite, a bit like what is in this game [here](https://www.microsoft.com/en-us/store/apps/7bomb/9nblggh08dd0).
Basically there is a sprite (the green floor) and another sprite (the bomb) that falls on top of the green floor and the bomb then explodes. Once exploded part of the green floor sprite is gone. The player (red ball) can then move the sprite inside the new cavity that was created in the green floor sprite.
[![enter image description here](https://i.stack.imgur.com/BlGmP.png)](https://i.stack.imgur.com/BlGmP.png) | 2016/05/19 | [
"https://gamedev.stackexchange.com/questions/121663",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/83669/"
] | It isn't possible to prevent that, however you can get a call when the parent transform changes and set it back to the correct value.
```
Transform m_DesiredParent;
void Awake()
{
m_DesiredParent = transform.parent;
}
void OnTransformParentChanged()
{
if(transform.parent != m_DesiredParent)
{
transform.SetParent(m_DesiredParent);
Debug.LogError("Cant change this parent, setting back to desired parent");
}
}
```
Biggest downside is that you cant control if the position/rotation/scale will be set back to the same value since there is no way of knowing whether the call that changed it saved its local position/rotation/scale or its world/position/rotation/scale | No, not really, as the method is not virtual.
The closest reasonable approach is to derive from `GameObject` and implement a *new* `SetParent` method:
```
public new void SetParent (Transform transform) {
throw new NotSupportedException("I'm afraid I can't do that.");
}
```
However, this will only fail at runtime and even then only if you call `SetParent` through an instance that is of the type of your subclass. That is, this code:
```
MyGameObject instance = new MyGameObject();
instance.SetParent(...);
```
will throw when `SetParent` is called. However this (likely very common) code:
```
GameObject instance = new MyGameObject();
instance.SetParent(...);
```
will not throw, because `SetParent` isn't virtual.
---
I suspect that whatever you're trying to accomplish by preventing `SetParent` from getting called, you're going to have to try doing so at a higher level, but without more information it's hard to suggest what you should try. |
121,663 | I'd like to find a way to add holes caused by a 'bomb' to my floor sprite, a bit like what is in this game [here](https://www.microsoft.com/en-us/store/apps/7bomb/9nblggh08dd0).
Basically there is a sprite (the green floor) and another sprite (the bomb) that falls on top of the green floor and the bomb then explodes. Once exploded part of the green floor sprite is gone. The player (red ball) can then move the sprite inside the new cavity that was created in the green floor sprite.
[![enter image description here](https://i.stack.imgur.com/BlGmP.png)](https://i.stack.imgur.com/BlGmP.png) | 2016/05/19 | [
"https://gamedev.stackexchange.com/questions/121663",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/83669/"
] | It isn't possible to prevent that, however you can get a call when the parent transform changes and set it back to the correct value.
```
Transform m_DesiredParent;
void Awake()
{
m_DesiredParent = transform.parent;
}
void OnTransformParentChanged()
{
if(transform.parent != m_DesiredParent)
{
transform.SetParent(m_DesiredParent);
Debug.LogError("Cant change this parent, setting back to desired parent");
}
}
```
Biggest downside is that you cant control if the position/rotation/scale will be set back to the same value since there is no way of knowing whether the call that changed it saved its local position/rotation/scale or its world/position/rotation/scale | It is very possible(with a quick refactoring), and you dont need to know the actual type, worry about deriving or need to instantiate every gameObejct manually in code. A simple trick with [extension methods](https://unity3d.com/learn/tutorials/modules/intermediate/scripting/extension-methods) will do: just "add" a field and extension method to the `GameObject` class:
```
public static class GameObjectExtensions
{
private static readonly ConditionalWeakTable<GameObject, bool> _canSet = new ConditionalWeakTable<GameObject, bool>();
public static void ChangeCanSetParent(this GameObject go, bool value)
{
_canSet.Remove(go);
_canSet.Add(go, value);
}
public static void TrySetParent (this GameObject go, Transform transform)
{
bool can;
if(!_canSet.TryGetValue(go, out can) || can)
go.SetParent(transform);
else {
//or just ignore it
throw new ApplicationException("method SetParent() is disabled on this GameObject.");
}
}
}
```
Now just find/replace all(or simply just where it matters) occurrences of `SetParent` with your new custom `TrySetParent`, usage:
```
GameObject player; //can set safely from editor, it IS actually "normal" game object
//originally player.SetParent()
player.TrySetParent(transform); //will work
player.ChangeCanSetParent(false); //disable it
player.TrySetParent(transform); //will throw
```
while it does not technically disable original `SetParent`, it is clean solution with backwards compatibility and without worrying anything in "user" code, or unexpected behavior and errors caused by not testing for/casting to actual type. |
3,273,212 | I'm using the `scoped_search` gem for basic search functionality on my site. Scoped search: <http://github.com/wvanbergen/scoped_search>
I'm using the most basic possible implementation of this gem. I'm searching on the name attribute in a user model only. On the frontend, in users/index, the search input is a `text_field_tag.`
```
<% form_tag users_path, :method => :get do %>
<%= text_field_tag :search, params[:search], :value => 'Search' %>
<%= submit_tag "Go", :name => nil %>
<%end%>
```
In the user model, I have:
```
scoped_search :on => :name
```
I want to implement basic auto-complete functionality on the user model, name attribute. This would be the most basic use case if I was searching in a form element of the user model, but the `scoped_search` part is throwing me off.
I was planning to use DHH's auto\_complete plugin, but I'm open to using whatever tool helps me accomplish this.
Auto-complete: <http://github.com/rails/auto_complete>
Thanks. | 2010/07/17 | [
"https://Stackoverflow.com/questions/3273212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159115/"
] | * In the model you should replace the
line:
scoped\_search :on => :name
with:
```
scoped_search :on => :name, :complete_value => true
```
* In the view replace the line:
<%= text\_field\_tag :search, params[:search], :value => 'Search' %>
with:
```
<%= auto_complete_field_tag_jquery(:search, params[:search], {},{}) %>
```
* In the controller you should add the following method:
def auto\_complete\_search
@items = User.complete\_for(params[:search])
render :json => @items
end | did you see the demo app at <https://github.com/abenari/scoped_search_demo_app> ?
Alternatively, you can see how I use it in my project - <https://github.com/ohadlevy/foreman>
Ohad |
4,385,797 | Why does $\sqrt{ab} = \sqrt{a}\sqrt{b}$? ( Considering that they are both surds)
From the definition of a nth root that means "what number multiplied by itself n times will get you back to the original number under the root", only justifies for single nth roots. Eg. square root of $49$ is $7$; because $7$ times $7$ gets you $49$. However, this doesn't explain why you can combine two surds together by just multiplying the numbers beneath the roots. Is there a logical proof of this that can make me understand this better? | 2022/02/19 | [
"https://math.stackexchange.com/questions/4385797",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/757425/"
] | If the definition of $y = \sqrt x$ is "that number $y$ for which $y^2 = x$", and if you also agree that (positive) square roots are unique (there is only one; any two positive numbers $y\_1$, $y\_2$ with the property that $y\_1^2 = x = y\_2^2$ must in fact be the same, $y\_1 = y\_2$), then it is not hard to prove that $\sqrt a \sqrt b = \sqrt {ab}$.
Here is a proof: if you claim that $y\_1 = \sqrt a \sqrt b$ and $y\_2 = \sqrt{ab}$ are in fact the same, you can demonstrate it by showing that they satisfy the same property; namely, $y\_1^2 = y\_2^2 = ab$.
Indeed, $y\_1^2 = (\sqrt a \sqrt b)^2 = \sqrt a^2 \sqrt b^2$ (by commutativity of multiplication), and $\sqrt a^2 \sqrt b^2 = ab$ by definition of square root.
Likewise, $y\_2^2 = \sqrt{ab}^2 = ab$ by definition of square root.
Hence $y\_1^2 = y\_2^2$, ie each of $y\_1$ and $y\_2$ satisfy the property of "is a square root of $ab$"; since (positive) square roots are unique, then $y\_1 = y\_2$.
You can present an even shorter proof once you are savvy with definitions; observe $(\sqrt a \sqrt b)^2 = \sqrt a^2 \sqrt b^2 = ab$, then immediately by definition we have $\sqrt{ab} = \sqrt a \sqrt b$. | If the square root of x is defined to be the positive version you don't need the plus or minus for the proof.
\begin{align}1.\hspace{2mm} (a)(b)=(ab)\end{align} using the property of surds/roots you just explained("what number multiplied by itself n times will get you back to the original number under the root"):\begin{align}2.\hspace{2mm} (\pm\sqrt{a})(\pm\sqrt{a})(\pm\sqrt{b})(\pm\sqrt{b})=(ab)\end{align}
Next use the commutative property of multiplication when you multiply an even number of plus or minuses you get plus;\begin{align} 3.\hspace{2mm} ((\pm)^4(\sqrt{a}\sqrt{b})(\sqrt{a}\sqrt{b})=(ab)\end{align}The plus or minuses cancel and there are two values being multiplied making a square. \begin{align}(\sqrt{a}\sqrt{b})^2= (ab)\end{align} Then use the square root function on both sides you only put the plus or minus on one side because they would cancel otherwise.\begin{align}5a.\hspace{2mm} \sqrt{a}\sqrt{b}= \pm\sqrt{ab}\end{align} The square root is defined as the positive solution for positive numbers so you get :\begin{align}5b.\hspace{2mm} \sqrt{a}\sqrt{b}= \sqrt{ab}\end{align} |
317,288 | **Figure 1**
![schematic](https://i.stack.imgur.com/sQ4Cr.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fsQ4Cr.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
I am using a TL074CN comparator to compare a fullwave rectified input voltage with a DC voltage of 1.4 V as shown in the above figure. At the output of the comparator, I am receiving a square wave which goes from +12V to -12V.
---
**Figure 2**
[![enter image description here](https://i.stack.imgur.com/jX1ss.jpg)](https://i.stack.imgur.com/jX1ss.jpg)
The figure 2 above shows the square wave generated in microsecond level. As you can see the waveform is very unstable at the moment. So far what I tried was
1) I also added a 100u capacitor at the output of the opmamp but it doesn't stabilize the waveform , it instead curves the waveform at the edges
2) I added a 10K resistor at the output but it doesn't help either.
3) I switched the TL074CN with an LM324N and still did not stabilize the waveform
Is there anything which I can do to make this square wave stable? | 2017/07/14 | [
"https://electronics.stackexchange.com/questions/317288",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/151685/"
] | The TL074 and LM324 are op-amps, not comparators.
If you want a device to operate as a comparator, you should use something designed for that application, like an LM319. | **Figure 3**
[![enter image description here](https://i.stack.imgur.com/6nxhd.jpg)](https://i.stack.imgur.com/6nxhd.jpg)
My error was that I was not triggering correctly. This time I selected the trigger mode to channel 3 which is the output square wave and selected the "slope" to be falling.
As you can see that when slope was selected to be falling, the **falling edge** of the square wave is stable while the **rising edge** shows some instability.
And when experimented vice versa, the rising edge was stable while the falling edge was not. |
17,687,778 | I'm building a custom kernel for Mac OS (Mountain Lion, Darwin 2050.22.13).
I can build the kernel just fine and I can add stuff to it but I'm missing something.
To keep things short, here is a sample of what I'm trying to do.
Let's say that I want to add a function [my\_func(void\*)] to say, bsd/kern/kern\_fork.c
I can add an include file and stick it into osfmk/bsd and change the Makefile so that the new .h file is now copied to BUILD/obj/RELEASE\_X86\_64/EXPORT\_HDRS/
I also added the function name to config/BSDKernel.exports.
I can see the function with its symbol in /mach\_kernel so it would appear to be fine.
Now, here's the tricky part. It's not tricky per se but I can't figure it out. What I want to do is to be able to make a call to my function from a kext that I am also writing. Basically it would be some sort of private API for me.
My kext compiles fine but when I run kextload/kextutil it complains that it can't find the my\_func symbol.
(kernel) kxld[com.blah.foo.kext]: The following symbols are unresolved by this kext
(kernel) kxld[com.blah.foo.kext]: \_my\_func
kextlibs returns:
For all architectures:
com.apple.kpi.libkern = 12.3
for x86\_64:
1 symbol not found in any library kext
So the question is how do I do to make my function(s) visible to my kext(s)?
Thanks! | 2013/07/16 | [
"https://Stackoverflow.com/questions/17687778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2589065/"
] | The error was in the Query itself. All I had to do was give the last Column something to compare to so I just added $ship\_weight again. Here is the code.
```
$result = mysql_query("SELECT * FROM weight WHERE '$ship_weight' >= from_weight AND '$ship_weight' <= to_weight");
``` | I think the problem is that `$result` will never be `empty()`
If the query works if will be a `resource handle` and if it fails it will be `false`.
So try this:
```
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if($result !== FALSE){
if (mysql_num_rows($result) > 0) {
$response["userID"] = array();
while ($row = mysql_fetch_array($result)) {
$custID = array();
$custID["shipping_cost"] = $row["shipping_cost"];
array_push($response["userID"], $custID);
}
$response["success"] = 1;
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "No shipping found";
echo json_encode($response);
}
``` |
17,687,778 | I'm building a custom kernel for Mac OS (Mountain Lion, Darwin 2050.22.13).
I can build the kernel just fine and I can add stuff to it but I'm missing something.
To keep things short, here is a sample of what I'm trying to do.
Let's say that I want to add a function [my\_func(void\*)] to say, bsd/kern/kern\_fork.c
I can add an include file and stick it into osfmk/bsd and change the Makefile so that the new .h file is now copied to BUILD/obj/RELEASE\_X86\_64/EXPORT\_HDRS/
I also added the function name to config/BSDKernel.exports.
I can see the function with its symbol in /mach\_kernel so it would appear to be fine.
Now, here's the tricky part. It's not tricky per se but I can't figure it out. What I want to do is to be able to make a call to my function from a kext that I am also writing. Basically it would be some sort of private API for me.
My kext compiles fine but when I run kextload/kextutil it complains that it can't find the my\_func symbol.
(kernel) kxld[com.blah.foo.kext]: The following symbols are unresolved by this kext
(kernel) kxld[com.blah.foo.kext]: \_my\_func
kextlibs returns:
For all architectures:
com.apple.kpi.libkern = 12.3
for x86\_64:
1 symbol not found in any library kext
So the question is how do I do to make my function(s) visible to my kext(s)?
Thanks! | 2013/07/16 | [
"https://Stackoverflow.com/questions/17687778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2589065/"
] | The error was in the Query itself. All I had to do was give the last Column something to compare to so I just added $ship\_weight again. Here is the code.
```
$result = mysql_query("SELECT * FROM weight WHERE '$ship_weight' >= from_weight AND '$ship_weight' <= to_weight");
``` | Is this a copy and paste of your code? If so, look at this line:
```
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
```
PHP is considering your `$ship_weight` variable as part of the string. Change it to:
```
$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '".$ship_weight."' AND to_weight <= '".$ship_weight."'");
```
Also, mysql\_\* is deprecated. Take a look at the [mysqli\_\* extension](http://www.php.net/manual/en/mysqli.query.php "mysqli_* extension"). |
7,299,679 | I'm trying to learn C++, Thanks to this article I find many similarity between C++ and Python and Javascript: <http://www.cse.msu.edu/~cse231/python2Cpp.html>
But I can't understand C++ Classes at all, they looks like Javascript prototypes, but not that easy.
For example:
```
//CLxLogMessage defined in header
class myLOG: public CLxLogMessage{
public:
virtual const char * GetFormat (){
return "Wavefront Object";
}
void Error (const std::string &msg){
CLxLogMessage::Error (msg.c_str ());
}
void Info (const std::string &msg){
CLxLogMessage::Info (msg.c_str ());
}
private:
std::string authoringTool;
};
```
Question: What is this Public/Private stuff at all!?
Edit: To be honest, I more enjoy C++ than Python, because I can learn truth meaning of everything, not simple automated commands, for example I preferred to use "int X" rather than "X" alone.
Thanks | 2011/09/04 | [
"https://Stackoverflow.com/questions/7299679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877276/"
] | `myLOG` is the name of the class. It inherits (look it up2) from `CLxLogMessage` and has the functions `GetFormat` (which is `virtual` and can be overridden by subclasses and called through base class pointers, look it up2), `Error`, and `Info`. It has the data member `authoringTool` which is a string.
The `public` and `private` stuff is access specifiers. Something in the `private` section can only be used by the class's member functions, and stuff in the `public` section can be used by anybody. There is another type of section called `protected` which means that only a class and its subclasses can access it, but nobody else1.
If you start adding stuff to a class without setting an access level first, it defaults to `private`.
You can have as many `public`, `private`, and `protected` sections as you want, in any order.
You need these different protection levels because you don't want other people messing with your data when you don't know about it. For example, if you had a class representing fractions, you wouldn't want someone to change the denominator to a 0 right under your nose. They'd have to go through a setter function which would check that the new value was valid before setting the denominator to it. That's just a trivial example though. The fact that Python does not have these is a shortcoming in the language's design.
All your questions would be answered if you had read a C++ book. There is no easy way out with C++. If you try to take one, you'll end up being a horrible C++ programmer.
1 You can let somebody else access `private` and `protected` members by declaring them as `friend`s (look it up2).
2 Sorry for saying "look it up" so much, but it's too much information for me to put here. You'll have to find a good resource for these kinds of things. | The private and public is to do with data encapsulation, it means you can change the implementation of the class without affecting how it is used. I suggest reading up on some of the theory of object orientation. |
7,299,679 | I'm trying to learn C++, Thanks to this article I find many similarity between C++ and Python and Javascript: <http://www.cse.msu.edu/~cse231/python2Cpp.html>
But I can't understand C++ Classes at all, they looks like Javascript prototypes, but not that easy.
For example:
```
//CLxLogMessage defined in header
class myLOG: public CLxLogMessage{
public:
virtual const char * GetFormat (){
return "Wavefront Object";
}
void Error (const std::string &msg){
CLxLogMessage::Error (msg.c_str ());
}
void Info (const std::string &msg){
CLxLogMessage::Info (msg.c_str ());
}
private:
std::string authoringTool;
};
```
Question: What is this Public/Private stuff at all!?
Edit: To be honest, I more enjoy C++ than Python, because I can learn truth meaning of everything, not simple automated commands, for example I preferred to use "int X" rather than "X" alone.
Thanks | 2011/09/04 | [
"https://Stackoverflow.com/questions/7299679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877276/"
] | Even though there's no way to give a comprehensive answer or anything near that, maybe think about it like this: classes are **types**. Consider this:
```
int n;
```
Here "int" is the name of a type, and "x" is a variable of type "int". There are basic types in C++, like "int", "char", "double". Now we can also make new, compound types from old types:
```
struct Foo
{
int n;
char c;
double d;
};
```
This defines a new type called "Foo", and `Foo x;` makes a new variable of that type. Now we can add some magic to the type "Foo":
```
class Foo
{
int n;
double d;
public:
Foo() : n(20), d(0.5) { } // "constructor"
};
```
The keywords `struct` and `class` almost mean the same thing, so we still have a compound type that has two member variables, `n` and `d`. However, this type also has a member *function*, and this one gets called every time you create a new Foo object. So when you say, `Foo x;`, then this variable's member value `x.n` will be set to 20 and `x.d` will be set to 0.5.
So that's that in a nutshell: Classes are types with built-in magic. And you are the magician. | The private and public is to do with data encapsulation, it means you can change the implementation of the class without affecting how it is used. I suggest reading up on some of the theory of object orientation. |
7,299,679 | I'm trying to learn C++, Thanks to this article I find many similarity between C++ and Python and Javascript: <http://www.cse.msu.edu/~cse231/python2Cpp.html>
But I can't understand C++ Classes at all, they looks like Javascript prototypes, but not that easy.
For example:
```
//CLxLogMessage defined in header
class myLOG: public CLxLogMessage{
public:
virtual const char * GetFormat (){
return "Wavefront Object";
}
void Error (const std::string &msg){
CLxLogMessage::Error (msg.c_str ());
}
void Info (const std::string &msg){
CLxLogMessage::Info (msg.c_str ());
}
private:
std::string authoringTool;
};
```
Question: What is this Public/Private stuff at all!?
Edit: To be honest, I more enjoy C++ than Python, because I can learn truth meaning of everything, not simple automated commands, for example I preferred to use "int X" rather than "X" alone.
Thanks | 2011/09/04 | [
"https://Stackoverflow.com/questions/7299679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877276/"
] | `myLOG` is the name of the class. It inherits (look it up2) from `CLxLogMessage` and has the functions `GetFormat` (which is `virtual` and can be overridden by subclasses and called through base class pointers, look it up2), `Error`, and `Info`. It has the data member `authoringTool` which is a string.
The `public` and `private` stuff is access specifiers. Something in the `private` section can only be used by the class's member functions, and stuff in the `public` section can be used by anybody. There is another type of section called `protected` which means that only a class and its subclasses can access it, but nobody else1.
If you start adding stuff to a class without setting an access level first, it defaults to `private`.
You can have as many `public`, `private`, and `protected` sections as you want, in any order.
You need these different protection levels because you don't want other people messing with your data when you don't know about it. For example, if you had a class representing fractions, you wouldn't want someone to change the denominator to a 0 right under your nose. They'd have to go through a setter function which would check that the new value was valid before setting the denominator to it. That's just a trivial example though. The fact that Python does not have these is a shortcoming in the language's design.
All your questions would be answered if you had read a C++ book. There is no easy way out with C++. If you try to take one, you'll end up being a horrible C++ programmer.
1 You can let somebody else access `private` and `protected` members by declaring them as `friend`s (look it up2).
2 Sorry for saying "look it up" so much, but it's too much information for me to put here. You'll have to find a good resource for these kinds of things. | Even though there's no way to give a comprehensive answer or anything near that, maybe think about it like this: classes are **types**. Consider this:
```
int n;
```
Here "int" is the name of a type, and "x" is a variable of type "int". There are basic types in C++, like "int", "char", "double". Now we can also make new, compound types from old types:
```
struct Foo
{
int n;
char c;
double d;
};
```
This defines a new type called "Foo", and `Foo x;` makes a new variable of that type. Now we can add some magic to the type "Foo":
```
class Foo
{
int n;
double d;
public:
Foo() : n(20), d(0.5) { } // "constructor"
};
```
The keywords `struct` and `class` almost mean the same thing, so we still have a compound type that has two member variables, `n` and `d`. However, this type also has a member *function*, and this one gets called every time you create a new Foo object. So when you say, `Foo x;`, then this variable's member value `x.n` will be set to 20 and `x.d` will be set to 0.5.
So that's that in a nutshell: Classes are types with built-in magic. And you are the magician. |
51,296,837 | Have been having a little issue for the last couple of days now where I will create a new Xamarin Forms project on Visual Studio 2017 and add a Xamarin.UITest Cross-Platform Test Project for unit testing I recieve a series of NU1201 Errors when I reference the .Android App in the UITest Project.
Here is the exact error i get:
```
Error NU1201 Project App1.Android is not compatible with net461 (.NETFramework,Version=v4.6.1) / win-x64. Project App1.Android supports: monoandroid81 (MonoAndroid,Version=v8.1)
```
I have played around with the Android version numbers to see if the UITesting package doesnt support the latest android but no matter what version of android i target the problem remains the same.
Here is a screenshot of the project.
[![enter image description here](https://i.stack.imgur.com/VO4Be.png)](https://i.stack.imgur.com/VO4Be.png)
All the code is unchanged from the default project and runs in the simulator fine but only produces these errors when the Android app is referenced to the UITest project. | 2018/07/12 | [
"https://Stackoverflow.com/questions/51296837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10068055/"
] | Solved it after many more hours of testing and trialling. Instead of adding the Android project to the references, Within the AppInitializer I added another method to the StartApp() call like so:
```
public class AppInitializer
{
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp.Android.InstalledApp("com.companyname.App1").StartApp();
}
return ConfigureApp.iOS.StartApp();
}
}
```
Therefore once I had already run the app via the emulator for the first time and installed on the device, the UITest simply uses the installed APK on the emulator instead of the project. | For those who ran into error NU1201, you might have come to the right place. This may not apply to the question asked but I ran into error NU1201 the other day and the reason for that is the nuproj configuration file for our nuget project has target configuration wrong. It should have been
>
> `<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>`
>
>
>
instead of
>
> `<TargetFramework>net462</TargetFramework>`
>
>
>
because the project is not of "SDK-style."
References: <https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-target-framework-and-target-platform?view=vs-2019> |
60,236,888 | I'm very new to this community. As i'm asking question if there is something i claim not right, please correct me.
Now to the point, i'm design a particle system using Three.js library, particularly i'm using **THREE.Geometry()** and control the vertex using shader. I want my particle movement restricted inside a box, which means when a particle crosses over a face of the box, it new position will be at the opposite side of that face.
Here's how i approach, in the vertex shader:
```c
uniform float elapsedTime;
void main() {
gl_PointSize = 3.2;
vec3 pos = position;
pos.y -= elapsedTime*2.1;
if( pos.y < -100.0) {
pos.y = 100.0;
}
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0 );
}
```
The ellapsedTime is sent from javascript animation loop via uniform. And the y position of each vertex will be update corresponding to the time. As a test, i want if a particle is lower than the bottom plane ( y = -100) it will move to the top plane. That was my plan. And this is the result after they all reach the bottom:
Start to fall
![Start to fall](https://i.stack.imgur.com/rSJxB.png)
After reach the bottom
![After reach the bottom](https://i.stack.imgur.com/42TWM.png)
So, what am i missing here? | 2020/02/15 | [
"https://Stackoverflow.com/questions/60236888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12902217/"
] | You can achieve it, using `mod` function:
```js
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 0, 300);
var renderer = new THREE.WebGLRenderer({
antialis: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var gridTop = new THREE.GridHelper(200, 10);
gridTop.position.y = 100;
var gridBottom = new THREE.GridHelper(200, 10);
gridBottom.position.y = -100;
scene.add(gridTop, gridBottom);
var pts = [];
for (let i = 0; i < 1000; i++) {
pts.push(new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiplyScalar(100));
}
var geom = new THREE.BufferGeometry().setFromPoints(pts);
var mat = new THREE.PointsMaterial({
size: 2,
color: "aqua"
});
var uniforms = {
time: {
value: 0
},
highY: {
value: 100
},
lowY: {
value: -100
}
}
mat.onBeforeCompile = shader => {
shader.uniforms.time = uniforms.time;
shader.uniforms.highY = uniforms.highY;
shader.uniforms.lowY = uniforms.lowY;
console.log(shader.vertexShader);
shader.vertexShader = `
uniform float time;
uniform float highY;
uniform float lowY;
` + shader.vertexShader;
shader.vertexShader = shader.vertexShader.replace(
`#include <begin_vertex>`,
`#include <begin_vertex>
float totalY = highY - lowY;
transformed.y = highY - mod(highY - (transformed.y - time * 20.), totalY);
`
);
}
var points = new THREE.Points(geom, mat);
scene.add(points);
var clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
uniforms.time.value = clock.getElapsedTime();
renderer.render(scene, camera);
});
```
```css
body {
overflow: hidden;
margin: 0;
}
```
```html
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
``` | You can not change state in a shader. vertex shaders only output is `gl_Position` (to generate points/lines/triangles) and varyings that get passed to the fragment shader. Fragment shader's only output is `gl_FragColor` (in general). So trying to change `pos.y` will do nothing. The moment the shader exits your change is forgotten.
For your particle code though you could make the position a repeating function of the time
```
const float duration = 5.0;
float t = fract(elapsedTime / duration);
pos.y = mix(-100.0, 100.0, t);
```
Assuming elapsedTime is in seconds then pos.y will go from -100 to 100 over 5 seconds and repeat.
Note in this case all the particles will fall at the same time. You could add an attribute to give them each a different time offsets or you could work their position into your own formula. Related to that you might find [this article](https://webglfundamentals.org/webgl/lessons/webgl-drawing-without-data.html) useful.
You could also do the particle movement in JavaScript like [this example](https://github.com/mrdoob/three.js/blob/master/examples/webgl_points_dynamic.html) and [this one](https://github.com/mrdoob/three.js/blob/master/examples/webgl_points_waves.html), updating the positions in the Geometry (or better, BufferGeometry)
Yet another solution is to do the movement in a separate shader by storing the positions in a texture and updating them to a new texture. Then using that texture as input another set of shaders that draws particles. |
49,207,064 | So what I am trying to do is align these divs within a bootstrap card. My issue is, I am able to get the left half of it right, but I can't figure out how to align the far right elements. I am currently using width percentages to allow this to stay responsive, though I have one thing set as fixed due to pictures always being the same size.
```html
<div class="card" style="width:65%;float:left;">
<h5 class="card-header">Window Latch Black (Small)</h5>
<div class="card-body clearfix text-center" style="width:100%;display:inline-block;background-color: aqua;">
<div class="cartimage" style="background-color:red;float:left">
<img class="rounded-circle" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="140" height="140">
</div>
<div class="carttext" style="height:50%;width:75%;background-color:green;">
khjg
</div>
<div class="cartamt" style="height:50%;width:75%;background-color:yellow;">
amt
</div>
<div class="cartprice" style="height:50%;width:15%;background-color:purple;float:right">
price
</div>
<div class="cartbutton" style="height:50%;width:15%;background-color:pink;float:right">
button
</div>
</div>
</div>
```
[![What is currently happening](https://i.stack.imgur.com/7jkjw.png)](https://i.stack.imgur.com/7jkjw.png)
[![What I am trying to achieve](https://i.stack.imgur.com/lNimF.png)](https://i.stack.imgur.com/lNimF.png) | 2018/03/10 | [
"https://Stackoverflow.com/questions/49207064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8372325/"
] | You need to adjust the order and replace 15% with 25% to have a total of 100% per row. You need to also set a height to parent container to use % height with child element:
```css
.rounded-circle {
border-radius:50%;
vertical-align:top;
}
```
```html
<div class="card" style="width:65%;float:left;">
<h5 class="card-header">Window Latch Black (Small)</h5>
<div class="card-body clearfix text-center" style="width:100%;display:inline-block;background-color: aqua;height:140px">
<div class="cartimage" style="background-color:red;float:left">
<img class="rounded-circle" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="140" height="140">
</div>
<div class="cartprice" style="height:50%;width:25%;background-color:purple;float:right">
price
</div>
<div class="carttext" style="height:50%;width:75%;background-color:green;">
khjg
</div>
<div class="cartbutton" style="height:50%;width:25%;background-color:pink;float:right">
button
</div>
<div class="cartamt" style="height:50%;width:75%;background-color:yellow;">
amt
</div>
</div>
</div>
```
By the way, since you are using Bootstrap V4 you can rely on flex to create your layout:
```css
.rounded-circle {
border-radius: 50%;
vertical-align: top;
}
.cartprice {
background: red;
flex-basis: 75%;
}
.carttext {
background: green;
flex-basis: 25%;
}
.cartbutton {
background: blue;
flex-basis: 75%;
}
.cartamt {
background: yellow;
flex-basis: 25%;
}
```
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="card">
<h5 class="card-header">Window Latch Black (Small)</h5>
<div class="card-body text-center d-flex">
<div class="cartimage">
<img class="rounded-circle" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="140" height="140">
</div>
<div class="d-flex flex-wrap w-100" >
<div class="cartprice">
price
</div>
<div class="carttext">
khjg
</div>
<div class="cartbutton">
button
</div>
<div class="cartamt">
amt
</div>
</div>
</div>
</div>
``` | If you are using `bootstrap4`, I don't understand why using `float`...Use boostartp4 **[[Flex Utilities]](https://getbootstrap.com/docs/4.0/utilities/flex/)** classes instead to make these type of grid layout...Also for good practice try to wrap your divs into a wrapper divs
***Stack Snippet***
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="card">
<h5 class="card-header">Window Latch Black (Small)</h5>
<div class="card-body text-center p-0 d-flex no-gutters" style="background-color: aqua;">
<div class="cartimage" style="background-color:red;">
<img class="rounded-circle" src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Generic placeholder image" width="140" height="140">
</div>
<div class="d-flex flex-column" style="flex: 2;">
<div class="carttext col" style="background-color:green;">
khjg
</div>
<div class="cartamt col" style="background-color:yellow;">
amt
</div>
</div>
<div class="d-flex flex-column col">
<div class="cartprice col" style="background-color:purple">
price
</div>
<div class="cartbutton col" style="background-color:pink">
button
</div>
</div>
</div>
</div>
``` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | add below code in onCreate
---
```
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
}
```
---
`R.drawable.back_dark` is back button image
remove this `actionBar.setHomeButtonEnabled(true);` from your code
---
***EDITED:*** found one thing, change below method
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
//if (id == R.id.action_settings) {
//return true;
//}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
```
***otherwise your all code is perfect! no need to change naythig***
---
@JonasSeputis: i have use your activity and run in android device its showing toast *"Back button clicked"* check below code and comment other code for sometime
----------------------------------------------------------------------------------------------------------------------------------------------------------------
```
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_settings) {
return true;
}*/
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
``` | just add this line in
`onCreate`:
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | You need to call **setHomeAsUpIndicator** & **setDisplayHomeAsUpEnabled**
>
> Set an alternate drawable to display next to the icon/logo/title when
> DISPLAY\_HOME\_AS\_UP is enabled. This can be useful if you are using
> this mode to display an alternate selection for up navigation, such as
> a sliding drawer.
>
>
>
```
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
```
**Now**
For this handling need to override **`onOptionsItemSelected(MenuItem item)`** method in your Activity .
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
``` | add below code in onCreate
---
```
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
}
```
---
`R.drawable.back_dark` is back button image
remove this `actionBar.setHomeButtonEnabled(true);` from your code
---
***EDITED:*** found one thing, change below method
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
//if (id == R.id.action_settings) {
//return true;
//}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
```
***otherwise your all code is perfect! no need to change naythig***
---
@JonasSeputis: i have use your activity and run in android device its showing toast *"Back button clicked"* check below code and comment other code for sometime
----------------------------------------------------------------------------------------------------------------------------------------------------------------
```
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_settings) {
return true;
}*/
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
``` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | In your
```
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (id == android.R.id.home){
// add intent to class you wish to navigate
Intent i = new Intent("com.your.package.classname");
startActivity(i);
}
}
``` | just add this line in
`onCreate`:
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | Alright make sure u do declare activity layout as below -
```
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
```
Now in every activity add below code
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
``` | just add this line in
`onCreate`:
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | You need to call **setHomeAsUpIndicator** & **setDisplayHomeAsUpEnabled**
>
> Set an alternate drawable to display next to the icon/logo/title when
> DISPLAY\_HOME\_AS\_UP is enabled. This can be useful if you are using
> this mode to display an alternate selection for up navigation, such as
> a sliding drawer.
>
>
>
```
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
```
**Now**
For this handling need to override **`onOptionsItemSelected(MenuItem item)`** method in your Activity .
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
``` | just add this line in
`onCreate`:
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | You need to call **setHomeAsUpIndicator** & **setDisplayHomeAsUpEnabled**
>
> Set an alternate drawable to display next to the icon/logo/title when
> DISPLAY\_HOME\_AS\_UP is enabled. This can be useful if you are using
> this mode to display an alternate selection for up navigation, such as
> a sliding drawer.
>
>
>
```
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
```
**Now**
For this handling need to override **`onOptionsItemSelected(MenuItem item)`** method in your Activity .
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
``` | In your
```
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (id == android.R.id.home){
// add intent to class you wish to navigate
Intent i = new Intent("com.your.package.classname");
startActivity(i);
}
}
``` |
35,057,188 | I am beginner programmer and just resent started android developing.
Watched many answers and couldn't find answer witch would fit for me.
I have added back arrow button in my action bar, but couldn't figure out how to add navigation to first loaded screen.
>
> MainActivity.java
>
>
>
```
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about) {
fragment = DemoFragment.newInstance("about");
text.setText("1");
} else if (id == R.id.nav_settings) {
fragment = DemoFragment.newInstance("nav settings");
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
```
>
> DemoFragment.java
>
>
>
```
public class DemoFragment extends Fragment {
public static final String TEXT = "text";
public static DemoFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
}
```
>
> AndroidManifest.xml
>
>
>
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
```
>
> activity\_main.xml
>
>
>
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
```
>
> app\_bar\_main.xml
>
>
>
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
```
>
> content\_main.xml
>
>
>
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MAIN_ACTIVITY" />
```
>
> fragment\_demo.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
>
> nav\_header\_main.xml
>
>
>
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[email protected]" />
```
>
> activity\_main\_drawer.xml
>
>
>
```
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
``` | 2016/01/28 | [
"https://Stackoverflow.com/questions/35057188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644871/"
] | You need to call **setHomeAsUpIndicator** & **setDisplayHomeAsUpEnabled**
>
> Set an alternate drawable to display next to the icon/logo/title when
> DISPLAY\_HOME\_AS\_UP is enabled. This can be useful if you are using
> this mode to display an alternate selection for up navigation, such as
> a sliding drawer.
>
>
>
```
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
}
```
**Now**
For this handling need to override **`onOptionsItemSelected(MenuItem item)`** method in your Activity .
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
``` | Alright make sure u do declare activity layout as below -
```
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
```
Now in every activity add below code
```
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
``` |
40,301,499 | i have this schema
lists TABLE
>
> id | movie\_id(fk) | user\_id
>
>
>
Movies TABLE
>
> id(pk) | genre1 | genre2
>
>
>
so i want to get the most reacurrence genres in one user's list
, i tried
```
SELECT lists.movie_id, movies.genre1, count(movies.genre1) as counting, movies.id
FROM movies
LEFT JOIN lists ON (movies.id = lists.movie_id)
group by lists.movie_id, movies.genre1, movies.id
```
this sql query returning
>
> [
> {"movie\_id":100,"genre1":"Crime","counting":1,"id":100},{"movie\_id":141267,"genre1":"Crime","counting":1,"id":141267},{"movie\_id":207932,"genre1":"Crime","counting":1,"id":207932},{"movie\_id":238636,"genre1":"Thriller","counting":1,"id":238636}
> ]
>
>
>
although Crime genre is present 3 times in the array it counted it once at a time, it should be "counting" : 3 for Crime
what did i do wrong ? | 2016/10/28 | [
"https://Stackoverflow.com/questions/40301499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5318737/"
] | You will need to add to your custom dialog the following:
(extracted from <https://github.com/watson-virtual-agents/virtual-agent-dialog/blob/master/dialog-contract.md?cm_mc_uid=77031076060014712594367&cm_mc_sid_50200000=1477519039>)
```
{
"output": {
"text": "Select your store",
"layout": {
"name": "show-locations"
}
},
"context": {
"request": {
"args": {
"location": "$user_location",
"location-type": "$location_type"
},
"name": "getStoreList"
}
}
}
``` | let me see if I understood. Do you want send a map location to the users based on their intent to the Conversation messaging.
First- Conversation is only the API where you can use the request/response Machine Learning embedded in you app.
Second- Based on the user`s message you need to create a logic in your app to request a map or check a db list to show the option.
On the basic application using the Conversation API, you should focus on your Backend where you will create the services for the business and ux layers. Until this moment, this location will not appear directly (otherwise you need to create entities with all stores and all locations to answer it without request a DB to provide you a list.
Good Luck |
67,629,555 | ```
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling the dices...")
print ("The values are....")
print random.randint(min, max)
print random.randint(min, max)
roll_again = raw_input("Roll the dices again?")
```
and this is the error
```none
File "main.py", line 10
print random.randint(min, max)
^
SyntaxError: invalid syntax
```
Where am I going wrong and how do I fix ? | 2021/05/21 | [
"https://Stackoverflow.com/questions/67629555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15987028/"
] | You need parentheses for your `print()` calls. Try this:
```
print(random.randint(min, max))
```
Also, since you're using Python 3 you should use `input()` instead of `raw_input()`. | Between Python 2.7 and Python 3.0, `print` changed from a statement to a function. The line producing your error was perfectly valid in Python 2.7, but functions require their arguments to be enclosed in parentheses. In this case, Python encountered a function name that wasn't followed by an opening parenthesis so it didn't know how to interpret what followed. Even though the error pointed to `random` as the problem, the error actually occurred prior to that. As [@QWERTYL pointed out](https://stackoverflow.com/a/67629586/5987) the solution is very simple, turn the `print` into a proper function call by putting the arguments inside parentheses.
```
print(random.randint(min, max))
```
P.S. don't use variable names like `min` and `max`, those are already used by Python itself and can lead to some hard to find bugs. Maybe `smallest` and `largest` would be better. |
75,400 | Vision is a humanoid of pure logic. Also, he wishes not for the destruction of humanity like Ultron and is worthy enough to hold Thor's hammer.
Why does such being enter the Iron Man's team to force Avengers to obey UN's orders?
Shouldn't it be with Cap's team? Or at least stay neutral and do his best to avoid civil war?
\* Bonus: Should we consider his lack of instinct/soul/empathy a factor for his actions, as opposed to Captain America for example? | 2017/06/27 | [
"https://movies.stackexchange.com/questions/75400",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/35047/"
] | TL;DR: It's specifically *because* he's a being of logic. Also, because of love.
First and foremost, it's important to remember Vision's original statement of loyalty from *Age of Ultron*. He is going to side with whichever group will protect life the best.
>
> CAPTAIN AMERICA: Are you? On our side?
>
>
> VISION: It's not that simple. (pause) I'm on the side of life. Ultron is not.
>
>
>
He explains that he sees logic in the oversight (all following quotes from [the Civil War transcript](http://transcripts.wikia.com/wiki/Captain_America:_Civil_War)):
>
> Vision: In the 8 years since Mr. Stark announced himself as Iron Man, the number of known enhanced persons has grown exponentially. And during the same period, the number of potentially world-ending events has risen at a commensurate rate.
>
>
> Steve Rogers: Are you saying it's our fault?
>
>
> Vision: I'm saying there may be a causality. Our very strength invites challenge. Challenge incites conflict. And conflict... breeds catastrophe. Oversight... **Oversight is not an idea that can be dismissed out of hand.**
>
>
>
He loves Wanda. Actor Paul Bettany confirms this in [an interview with EW](http://ew.com/article/2016/05/09/captain-america-civil-war-vision-paul-bettany-scarlet-witch/). Speaking of why he accidentally blasted Rhodey out of the sky, he says
>
> “**What happened there is that his judgment was clouded there by real love and affection**,” says Bettany. “And he responded in a quick and thoughtless way.… I really love that the moral compass of the movie is this synthetic person who’s trying to figure out what it means to be human. It’s a neat idea, you know?”
>
>
>
Because he loves Wanda, he believes that this is the best way to protect her.
>
> Tony Stark: If we don't do this now, it's gonna be done to us later. That's the fact. That won't be pretty.
>
>
> Wanda Maximoff: You're saying they'll come for me.
>
>
> Vision: We would protect you.
>
>
>
He truly believes that protecting Wanda from the public is also protecting the public.
>
> Wanda Maximoff: Vision, are you not letting me leave?
>
>
> Vision: [He blocks her way.] It is a question of safety.
>
>
> Wanda Maximoff: I can protect myself.
>
>
> Vision: [He holds her arm.] Not yours. Mr. Stark would like to avoid the possibility of another public incident. Until the Accords are on a... more secured foundation.
>
>
> Wanda Maximoff: And what do you want?
>
>
> Vision: For people to see you... as I do. [She looks at him gravely.]
>
>
>
and
>
> Vision: [He faulters.] If you do this... they will never stop being afraid of you.
>
>
>
So, he decides to go the utilitarian route: the greatest good for the greatest number:
>
> Vision: Captain Rogers. I know you believe what you're doing is right. But for the collective good you must surrender now. [Tony's team arrives.]
>
>
>
Of course, being that he is basing his allegiance on logic, he is willing to swap sides.
Actor Paul Bettany addressed this briefly in the interview mentioned earlier.
>
> “**He has logic in abundance. And logic does not afford any room for loyalty. New information could come to light and he might flip to Captain America’s side.** But love solidifies things and provides loyalty. So if he’s there to protect mankind – or frankly, the universe – he needs to figure out what’s good about these creatures, and I think that’s the quest that you find him on. And, of course, in the comics, the relationship becomes romantic. We’ll see moving forward what happens for Vision and Wanda.”
>
>
> | * You describe Vision as a being of pure logic. Logic is built on (unbreakable) rules. Exceptions to rules are, by definition, illogical to the rule. If Vision is placed based on his logical aptitude, I think he's in the right team already.
* Tony, while very flamboyant and extraverted, is a highly logical person. He is considerably more pragmatic than Cap; who goes with his gut more than Tony. It makes sense for Vision to agree with Tony, because they approach things the same way (analytically).
* Cap goes with his gut, and focuses more on "the human element". His stance is based on his tendency to **do good** more than being right or effective. This is an emotional stance, it is based on empathy more than logic. Almost in all media (even surpassing the MCU) that addresses differences between humans and machines, **empathy is THE skill that machines (and logical beings) archetypically lack**.
Three very good reasons why Vision picks the UN side of the debate, *if we assume he chooses logic above all else*.
However, it's not impossible that Vision is capable of making a "human" decision rather than a logical one; and that it is simply his opinion which causes him to pick Tony's side (just like how Tony's stance is an opinion).
Vision has shown to be able to have deep emotional talks; so it's not impossible for him to understand, acknowledge and even experience human emotions.
---
**Edit** - Another remark about what you say:
>
> [Vision] is worthy enough to hold Thor's hammer.
>
>
>
Take a step back, and look at who Thor is. Thor is the son of a **monarch**, which has ruled with an iron fist and very much controls the ins and outs of Asgard.
Thor is not someone who would fight for personal freedom **over** a controlling hand; as he is heir to the throne that controls Asgard.
Wielding Mjölnir does not in any way reflect on Vision's suggested stance in Civil War. And if it does, it would argue in favor of UN control; not against it. |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | I believe this depends on the performer/composer. There are songs that the melody is just being sung and there are songs that the melody is being sung *and* played at the piano (or some other instrument).
Also, sometimes the melody is being played on the piano *before* the singer starts singing it.
If the composer wants to do something specific, this will most likely be denoted on the sheet music; otherwise, it's up to you to do what you like. | It has to be noted that much piano sheet music is not designed for accompanists, but for solo players, so has a tendency to include the melody in the top line, rather than being a literal translation of the original piano part [if any]
I would tend to treat this type of sheet music as a guide rather than an absolute, & work from memory as to what the original or favourite version of the song actually did. |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | I believe this depends on the performer/composer. There are songs that the melody is just being sung and there are songs that the melody is being sung *and* played at the piano (or some other instrument).
Also, sometimes the melody is being played on the piano *before* the singer starts singing it.
If the composer wants to do something specific, this will most likely be denoted on the sheet music; otherwise, it's up to you to do what you like. | I agree with everything everyone has said above. Just to add to what they've already said, sometimes its just better to play by ear. For example, if your wanting to sing and play an Adele song, like "No One Like You", you can replicate the same version if you just play what's on the recording. It is easier said than done, but you have a lot more flexibility if you develop that skill. Its better than being dependent solely on sheet music, because if you follow too adhesively to it, your at the mercy at some other musician's interpretation of the music. (Not to say that sheet music isn't great! Or a great place to start.) |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | I believe this depends on the performer/composer. There are songs that the melody is just being sung and there are songs that the melody is being sung *and* played at the piano (or some other instrument).
Also, sometimes the melody is being played on the piano *before* the singer starts singing it.
If the composer wants to do something specific, this will most likely be denoted on the sheet music; otherwise, it's up to you to do what you like. | A melodic playalong is mostly working well for simple music and simple interpretations. If you have a singing style with melodic and rhythmic freedoms, an accompanist will do the performance no favor by trying to follow the line along, even when self-accompanying. You also get the problem on a piano that it is a percussive instrument and thus has problems in delivering an even texture when long and short syllables are alternating.
In that case basically working on the chords, often arpeggiating them over both hands in order not to get a wham-wham-wham accentuation on the beats/changes tends to turn out nicer.
Piano extracts of music for choir and orchestra are not really helpful here since they are intended as rehearsal aids and thus integrate the singers as well. You see similar effects in piano extracts for solo music: they tend to remain perfectly recognizable even if nobody sings along. |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | There is a lot of sheet music available which has 3 lines of manuscript. The lower two are the standard treble and bass clef that most people know from piano music, and the top line is often treble clef, and has the melody line, usually with the lyrics. Looking at the middle line, you'll find that the top line is often duplicated, but there are also other right hand notes to play.When a singer is there, the top part of the middle line is optional, it doesn't need to play the melody, because it's being sung. However, it can be played if the vocals and piano player so wish.
If you're working from real or fake books, all you'll get is the melody line and chord changes. You have the choice to play chords with the left hand, and melody with right, but if a singer is singing, it makes more sense to play chords and extensions, or fill in bits, with the right hand. | It has to be noted that much piano sheet music is not designed for accompanists, but for solo players, so has a tendency to include the melody in the top line, rather than being a literal translation of the original piano part [if any]
I would tend to treat this type of sheet music as a guide rather than an absolute, & work from memory as to what the original or favourite version of the song actually did. |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | It has to be noted that much piano sheet music is not designed for accompanists, but for solo players, so has a tendency to include the melody in the top line, rather than being a literal translation of the original piano part [if any]
I would tend to treat this type of sheet music as a guide rather than an absolute, & work from memory as to what the original or favourite version of the song actually did. | A melodic playalong is mostly working well for simple music and simple interpretations. If you have a singing style with melodic and rhythmic freedoms, an accompanist will do the performance no favor by trying to follow the line along, even when self-accompanying. You also get the problem on a piano that it is a percussive instrument and thus has problems in delivering an even texture when long and short syllables are alternating.
In that case basically working on the chords, often arpeggiating them over both hands in order not to get a wham-wham-wham accentuation on the beats/changes tends to turn out nicer.
Piano extracts of music for choir and orchestra are not really helpful here since they are intended as rehearsal aids and thus integrate the singers as well. You see similar effects in piano extracts for solo music: they tend to remain perfectly recognizable even if nobody sings along. |
24,909 | In general on piano do you play the melody of a song if you intend to sing? Is it the case that you play a much more basic version of a song if you intend to also sing? If I am looking at sheet music is this denoted in any fashion? | 2014/11/10 | [
"https://music.stackexchange.com/questions/24909",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/15263/"
] | There is a lot of sheet music available which has 3 lines of manuscript. The lower two are the standard treble and bass clef that most people know from piano music, and the top line is often treble clef, and has the melody line, usually with the lyrics. Looking at the middle line, you'll find that the top line is often duplicated, but there are also other right hand notes to play.When a singer is there, the top part of the middle line is optional, it doesn't need to play the melody, because it's being sung. However, it can be played if the vocals and piano player so wish.
If you're working from real or fake books, all you'll get is the melody line and chord changes. You have the choice to play chords with the left hand, and melody with right, but if a singer is singing, it makes more sense to play chords and extensions, or fill in bits, with the right hand. | I agree with everything everyone has said above. Just to add to what they've already said, sometimes its just better to play by ear. For example, if your wanting to sing and play an Adele song, like "No One Like You", you can replicate the same version if you just play what's on the recording. It is easier said than done, but you have a lot more flexibility if you develop that skill. Its better than being dependent solely on sheet music, because if you follow too adhesively to it, your at the mercy at some other musician's interpretation of the music. (Not to say that sheet music isn't great! Or a great place to start.) |