Relationship of "Threadsafe" with "Atomic Operation"

Question: From MSDN here (http://msdn.microsoft.com/en-us/library/aa691278(v=vs.71).aspx) you can see that basic types such as int,byte……are all readable/writable atomic. So I wonder since they are all "atomic":
What's the relationship between "An atomic operation" and "lock"? In my mind, if an operation is "atomic", we don't need lock anymore because they must be "thread-safe", am I right?
And anyway, I was told by someone on the website's forum, are they right?
1) Any reference type is "Atomic Operation".
2) Types such as i++ or --i aren't atomic operations(So how can I check which operation is "atomic", which is NOT?)
I'm always feeling puzzled by these problems....

@Daniel Brückner and @keshlam:
It seems that a mixed operation such as ++i (first read/then write) isn't an atomic. However I feel interested in that if I seperate them into two steps like below:
//suppose I have "i" defined and assigned a value
void Fun()
{
   if(i==1)
   {
     i=2;
   }
}

If the codes above will be called by several threads, and "if" part only reads (atomic step), and "i=2" (another atomic step), so I don't need lock?
Comment: This statement: "Any reference type is 'Atomic Operation'" makes no sense. A type is not an operation.
Comment: when a type is larger than the native register size then "there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement."
Comment: @MitchWheat: What do you mean by "a type is larger than the native register size"?
Answer: An atomic operation is one which is inherently uninterruptable -- there is no way for anyone else to see the system in an inconsistent state, only before or after the whole operation.
A single read or write of a primitive value is atomic FOR THAT CORE. It may not be safe if there's code running in other processor cores; values often aren't flushed out of processor cache and made visible to other cores until the operating system explicitly performs that operation. I don't know enough about C# threading to know how much of a risk exists there.
A read-modify-write, which is what we're more often concerned with, often isn't -- which includes the ++ and -- operations. In SOME architectures, there are single instructions with implement an inherently atomic test-and-set, which is a specialized case of read-modify-write that can be used to implement a very lightweight form of threadsafe locking/counting.... but that depends very much on which processor you're running on.
An operation which involves reading and/or changing several primitive values, or which is doing a nontrivial operation upon a value, won't be atomic no matt1er how you slice it. And most real-world tasks above the level of implementing primitive semaphores do involve more than one value that have to be kept synchronized with each other. So while knowing that some operations are atomic is helpful for the simplest case, you will find that this isn't enough once you get above the very lowest level of subroutines. At that point you need to use an explicit lock to keep other threads from interrupting the aggregate operation. Semaphores/locks basically use a primitive atomic as a fence around the more complicated operation, taking advantage of operating system functions to make the second (or later) thread to try to access to lock wait for it VERY efficiently (basically, going to sleep until the lock is released, rather than going into a spin loop). This lets you create larger operations that behave atomically, though they have to cooperate with each other to achieve that.
Summary: If you don't KNOW something is inherently atomic, always assume that it isn't, and that if it's going to be accessed from more than one thread it had to be protected by a lock. Failing to do so results in garbled values and extremely annoying debugging scenarios. Don't take chances; if in doubt, protect it explicitly.
(And don't forget that having a structure be atomic doesn't ensure that its contents are atomic. I had to debug a case last year where someone was using one of Java's atomic collection types but forgot that the structure they were storing into the collection also had to protect its own contents.)
Comment: Many thanks! According to what you said, it seems that on MSDN, you mean ONLY a variable type such as what is said above like (int, byte……) are thread-safe and atomic in single thread mode with either reading value from it or writing a value into that? Then why does Microsoft make them "atomic"? It's of no use if they cannot work properly in the multiple thread environment……I still cannot understand why MSDN says this?
Answer: Data types are not atomic, some operation with them are or can be atomic. Assigning a 32 bit integer variable
Int32 foo = 123456789;

is, for example, an atomic operation. It will never happen that another thread observes foo to be 52501, that is the least significant 16 bits are assigned but not yet the most significant 16 bits. The same is not true for Int64 - it may happen that another thread sees an assignment operation only partially executed.
Many other operations are not atomic. For example
foo++;

requires reading, modifying and writing the value and therefore another thread may read and change the value of foo after you read it but before your were able to write the updated value back. You can use Interlocked.Increment() to perform this operation atomically and there are methods for a couple of other operations, too.
So in essence what you called atomic data types only guarantees that variable assignments are performed atomically and this is true for primitive data types and references except Double, Decimal, Int64and UInt64.
void Fun()
{
  if (i == 1)
  {
     i = 2; // I may have any value here because another thread might
            // have assigned a new value after the test i == 1 but
            // before this assignment.
  }
}

Comment: Many thanks!I can change to another interesting problem:If I wrote a method that would be called by several threads, It began with reading a value with a "if" check, and then when it satisfies the certain condition, it will write a new value directly into the variable itself. So don't we need a lock because each step is atomic?
Comment: It depends on what you want to do. Without a lock it may happen that you read `1`, another thread writes `2` and then inside your `if` block you overwrite `2` with `3` and your thread never notices that the `1` was changed to a `2`.


Combinatorics - Number of Paths in a Grid with a Hole

Question: Given a $12\times12$ grid with a hole of $4\times4$ in its middle, how many short paths (right or up only) are there from $(0,0)$ to $(12,12)$.
I tried using inclusion-exclusion by counting the number of paths that go through at least one point inside the hole, then count the paths that go through at least 2 points in the hole etc. but so far I got lost. Would appreciate any (perhaps simpler) suggestions to try solve this.
Thanks
Comment: Is this a $12\times12$ grid or a $13\times13$ grid? If the latter, which lattice points are disallowed?
Comment: (0,0) is the bottom left corner and (12,12) is the top right. Disallowed are the 3*3 points inside the (4,4) (8,8) square.
Answer: Possible hint: the path must go through exactly one of the points on the diagonal line joining the top left to the lower right corner of the grid. Count those for the points not in the hole.
Comment: But couldn't the path go through more than exactly one of the points on the diagonal line joining the corners of the grid (any path starting with up right up right for ex.)?
Comment: @Ron I mean the _other_ diagonal. I will edit my answer.
Comment: Oh, I think I got it! so I take 2n choose n then I subtract the sum of the possibilities to go through each of the 3 central points on that diagonal.
Answer: We need a way of grouping the paths into disjoint sets. Let $N_i$ be the number through the point $(i,12-i)$ for $i=0,1,2,3,4,8,9,10,11,12$.
We have $N_i={12\choose i}^2$, so the total number of paths is $2\left({12\choose0}^2+{12\choose1}^2+{12\choose2}^2+{12\choose3}^2+{12\choose4}^2\right)=595852$.
Comment: I do not completely understand the formula for your term $N_i$. For each $i, i=0,1,2,3,4$ you draw $i$ '$x$'-coordinates for an 'up' movement from a universe of $13-(4-i)$. Therefore I would expect $N_i = {9+i \choose i}^2$ to hold. Could you be so kind to explain? (any coordinate set for a given $i$ determines the path; I do follow your reasoning for the square and the doubling due to the problem symmetries).
Comment: For any given $i$ we have to traverse two rectangles one after the other. Each is $i\times(12-i)$. So for each one we have 12 moves, $i$ of which are in one direction, the remainder in the other. To take the simplest case: for $i=0$, we have to make 12 vertical moves (1 possibility) followed by 12 horizontal moves (1 possiblity), total $1^2$ possibilities.
Comment: Got the error in my reasoning (drawing without repetition while in fact the '$x$'-coordinates for the up move may repeat). thank you.


Query performance; not sure what's happening

Question: I had issues with my query that took 17 seconds to execute (350k rows):
SELECT idgps_unit, MAX(dt)
         FROM gps_unit_location
        GROUP BY 1

Explain
1   SIMPLE  gps_unit_location   index       fk_gps2 5       422633

After playing with it, I came with this solution that takes 1second:
Select idgps_unit, MAX(dt) from (
SELECT idgps_unit,  dt
         FROM gps_unit_location
) d1
Group by 1

Explain:
1   PRIMARY <derived2>  ALL                 423344  Using temporary; Using filesort
2   DERIVED gps_unit_location   index       gps_unit_location_dt_gpsid  10      422617  Using index

And now I am confused- why query #2 is fast, while query #1 seems to be the same query and seems to be written more efficiently.
Index1 :DT, Index2: idgps_unit, Index3: idgps_unit+DT
The execution times are consistent; query #1 always takes 17-19sec; while #1 <1sec.
I am using Godaddy VPS Windows Server 2008 Economy
Table example:
id | idgps_unit | dt | location
1 | 1 | 2012-01-01 | 1
2 | 1 | 2012-01-02 | 2
3 | 2 | 2012-01-03 | 3
4 | 2 | 2012-01-04 | 4
5 | 3 | 2012-01-05 | 5

Comment: Is the execution time for both queries are consistent?  Because it is possible that the results are cached when the first query was executed and used by second query.
Comment: If you could post the result of running `EXPLAIN` on those queries, it could be helpful.
Comment: Are you trying to get the `dt` and `idgps_unit` from the latest entry (assuming `dt` is a timestamp)? If so, you should rewrite the query; the way you're doing it now doesn't really make sense and an `ORDER BY...LIMIT` query would be faster and actually make sense.
Comment: @G-Nugget , `LIMIT` limits results. The `GROUP BY` statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
Comment: @Andrew I guess I should rephrase my question: What are you trying to get with the query?  They way you're using the `GROUP BY` is technically incorrect and can lead to inaccurate results.  Strictly, you can't select non-aggregate values from `GROUP BY` queries, but MySQL provides a work around that you're using here.
Comment: @Andrew So using your example, are you expecting to get `1, 2012-01-05`?
Comment: @G-Nugget, no it should contain 3 latest records with each `idgps_unit`
Comment: @andrew I see now, the `GROUP BY 1` is synonymous with `GROUP BY idgps_unit` and you're not just using it to group the entire table into one group.  I've never seen a `GROUP BY` written like that.
Comment: What is the definition of `fk_gps2`?
Answer: I would say your indexs are not set up properly, Your second query is kind of an inner query which is effectively creating its own inner index group if that makes sense !
Answer: First, I'm assuming gps_unit_location is really a table and not a view.  Second, I'm also assuming that you have run both queries multiple times, so caching is the not explanation.  (Caching would be that you run the first query, it loads the table into page cache and the second reads from memory rather than disk.)
Do you have an index on gps_unit_location(idgps_unit)?  Are the records very wide?  If the answers to these questions are "yes", then the following may be happening.
If so, you might have a curious problem with indexing.  You would think that an index would speed up such a query.  What it does, though, is to look up the values in idgps_id in order.  If the index does not contain the date, then the database needs to fetch the data from each page.  If the table does not fit into memory, then this will often result in a cache-miss -- that is, time to load the page.
By contrast, if the table is wide and the engine does a full table scan, then it can zip through the table and extract the two fields of interest.  It puts them on the side.  If they are small relative to the full table, then sorting them might take very little time.  Voila, the query finishes faster.
My guess would be that the second structure removes the use of an index.
By the way, you can fix this by changing the index to gps_unit_location(idgps_unit, dt).  By including the field in the index, the query does not have to load the data.
Comment: `gps_unit_location(idgps_unit, dt)` solved the issue! Thank you!


How do I handle two project variations with two Mercurial repositories?

Question: We have an application, which is open-source and published as GPLv2. We also have a slightly different version, with a commercial license. The differences between the two variations are very limited.
We have a main Mercurial repo for the GPL application.
I want to be able to keep a separate repo for the commercial application (the main one is public), but I also want to be able to regularly "push" changes to it (but not the other way round). Consider that these repos are hosted on a project hosting web service.
What I have done so far:

created a new comm repo
committed a first version of the commercial app (no history)
pushed comm to remote hosting
Modified open-source repo
tried to push from open-source to remote comm, hg says the repos are unrelated
tried to push from *open-source'*to comm with -f (force) option, hg now just shows a warning

The problem with step 6 is that I would push ALL changesets to the comm repo, which is not correct. I basically want to push changes since a given point in time (very much like merging two SVN branches).
I'm learning about the hg transplant extension, but that seems to be a bit complex to use on a regular basis.
I am new to Mercurial, so I might be doing it wrong, so please also suggest other ways of solving the same problem.
Comment: I think the main problem here is that you started with unrelated repositories. You should've created the commercial one as a clone of the open source one, and then pushed all your changes to it.
Comment: Well I can start over, no problem. Do you mean that I can clone starting from a specific revision (like the last one)?
Answer: With a distributed version control system like mercurial you would clone the source repository in step 1 having two repositories with the same content at the starting point, namely open-source and comm as you called them. You would do your initial changes in your comm repository. As development proceeds in the open-source repo you would regularly pull changes into the comm repository and merge these with the changes there. This will produce additional merge changesets in the comm repo. As long as you don't push them back to the open-source repo you won't see them there and they should not disturb there, but that's what I understood you wanted anyway.


Where are all the enemy labs located?

Question: So recently I found that in Advance Wars 2, there are secret missions you can go to by capturing some specific cities.
Which cities I should capture in order to unlock the secret missions?
Answer: There are four city need to be capture in order to play those mission. Below I will list down the city at need to be capture and also show you which mission the city located at.

Orange Star
On the Mission 4: Flak Attack, you need to capture the city (Red circle marked) in order to get the enemy lab map.

Blue Moon
On the Mission 10: Toy Box.

Yellow Comet
On the Mission 19: Show Stopper. Capture the this city will unlock the secret mission.

Green Earth
On the Mission 26: Sinking Feeling. Go to the island and capture the bottom city will unlock the secret mission.

Where are all the enemy labs located?


syntax error about SQLitedatabase ,When is select*from

Question: This is error

android.database.sqlite.SQLiteException: near "FROMfriendsWHERE":
  syntax error: , while compiling: SELECT*FROMfriendsWHERE id != ?

This is my code
Cursor cursor = db.rawQuery("SELECT * FROM "+FriendsDBHelper.TABLE_NAME+" WHERE id != ?",new String[]{Integer.toString(0)});

Comment: `!=`  is java , use `<>` instead..
Comment: Looks like your spacing is not being applied to the string
Comment: Clean your project and run..
Answer: Try
Cursor cursor = db.rawQuery("SELECT * FROM "+FriendsDBHelper.TABLE_NAME+" WHERE id NOT LIKE ?",new String[]{Integer.toString(0)});

NOT LIKE is used for do not have ? value in it
Or
Cursor cursor = db.rawQuery("SELECT * FROM "+FriendsDBHelper.TABLE_NAME+" WHERE id <> ?",new String[]{Integer.toString(0)});

<> is used for is not equal to ?
Comment: Did you meant to use `NOT IN` ?? B'coz, what you currently posted may not work


Import table and add incremental primary ID

Question: Is there a way to import a table and at that moment include an incremental primary key
I am importing a flat file, but I would like that SQL Server adds it an incremental primary key.
Is there a way, to avoid doing this:

CREATE TEMPORAL TABLE
INSERT ALL DATA TO A TEMPORAL TABLE
ALTER TEMPORAL TABLE AND ADD IT
PRIMARY KEY;

I guess doing this costs lots of time...
Comment: simply have an IDENTITY column on your target table.
Comment: so, Is this neccesary????: ALTER TABLE NAMEOFTABLE ADD id INT IDENTITY
CONSTRAINT id PRIMARY KEY; Other way you suggest?
Comment: This would be a **temporary** table that you're using - one that's in use for a temporary period of time. **Temporal** means that the table design takes the time dimension into account (e.g. by having "ValidFrom" / "ValidTo" columns).
Answer: Like this:
<code>SELECT IDENTITY(int,1,1) AS ID, *
INTO #newtable
FROM dbo.OldTable;
</code>
But I would recommend investigating your particular problem and probably solving it using the ranking functions.


errors while launching discord bot

Question: **`        throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit);
^
RangeError [BitFieldInvalid]: Invalid bitfield flag or number: undefined.

`**
const Discord = require('discord.js');
const { Client, GatewayIntentBits } = require('discord.js');
const ytdl = require('ytdl-core');
const ffmpeg = require('fluent-ffmpeg');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.VoiceStates,

  ],
});

so the GatewayIntentBits.VoiceStates, is creating error that i placed above code. i don't know why it's creating that error. can anyone help?
i tried to make music and warning discord bot. and i expected it ://
Answer: From this Discord API Types enum outline, there is a type named GuildVoiceStates instead of VoiceStates. I believe using GatewayIntentBits.GuildVoiceStates should resolve.
Comment: thanks. i will try using it. is there any way that i can message you for any help?

errors while launching discord bot


Checkout charity by default in an online cart

Question: John is responsible for designing an online shopping cart and checkout experience at a mid-size organization.
John goes to the grocery store, where a checkout clerk asks if he'd like to donate a few dollars to a good cause.  Let's suppose, for the sake of argument, that John and his community recognize it as a good cause.
John goes back to work, does some research, and finds that these "checkout charity" asks bring in hundreds of millions of dollars annually in just his country, which is the US.
John has an idea:
"Let's add this feature to our online shopping cart!  On the checkout page, we'll ask folks to donate a few dollars to a good cause."  Knowing the power of defaults, he even decides "Let's make that the default, for every checkout.  We'll also provide a link someone can click on to get a popup explaining what the donation is for, and allowing them to change the amount, increasing it up quite a bit or decreasing it, even down to zero if they want.  Because they have the option of setting the donation to zero, it's completely optional, but because we're making it easier to give, and a lot of the people who use our checkout are likely to be of the giving type and see this as a good cause, we'll be able to collect a lot more donations this way, compared to if we made the default zero.  We'll give folks a receipt they can use for a US tax deduction.   Since it's online and we provide more information about the charity than at the grocery store, it doesn't even have the 'public shaming' or non-transparency issues that some cheapskates grouse about online, plus we have customers' information to enable re-contact, and we'll pick a charity that aligns with what people are going through the checkout for.  Even if some Canadian public radio types don't like this, at least some polls suggest most Americans do. "
Suppose that once this change is made, donations per checkout do go up, quite significantly.
Are there any significant drawbacks John should be aware of?  If so, is there any evidence to suggest whether they are or aren't strong enough to outweigh the benefits?  Are there other benefits?  Are there studies that have been done about this, looking at long-term impacts or other effects?
Answer: Ethical Considerations
As far as I'm concerned, requiring opt-out for any charge not necessary for the purchase is a dark pattern and an ethical Bad Thing. Sites that do it know bloody well that many users won't have time to read a cluttered web page carefully, and end up including the purchase/donation when they wouldn't otherwise, and didn't really want to. They know that users are used to getting mandatory small amounts tacked on the purchase total (tax, shipping, handling), and won't think to question an added line item before clicking Purchase. It's trickery, so it's wrong.
Maybe this will give you an intuitive sense of it being wrong: consider your bricks-and-mortar grocery store where, instead the cashier of asking you for a  donation, there is a small easy-to-miss sign, amidst the clutter of the candy and gossip magazines, saying "We'll automatically add $X to your bill to donate to Worthy Charity. Press the yellow key on the credit card reader if you don't want to do this." How would you feel about that?
Now, can I dream up some hypothetical extreme example where the ends justifies the means? Sure, and like nearly all hypothetical extremes, it involves Nazis. I personally would think it's okay to include a default donation to the Holocaust Memorial Museum on a site for buying swag of the regional Nazi party. That would be a hoot.
But seriously, for any practical situation, it's ethically out.
Business Considerations
Opt-out of charity is probably out from a business standpoint too. There will be people who are offended and/or feel tricked. That they liked the charity (if they did) only softens the offense. There may be some who feel it's personally unethical to casually hand out money. They want to get the biggest bang for their donation buck, so they carefully select who they give too. As far as they're concerned, the site cheated a more worthy charity (in their opinion) out of a donation.
What would be the bottom-line impact on the brand? I don't have any research, but, analytically, users will think equally positively about the brand for supporting the charity whether the site uses explicit opt-in or opt-out. However, some perception of the brand will be diminished by using opt-out by those who feel tricked. Net effect: opt-out helps the charity (at least you say so in your scenario), but hurts the business.
User Self-Esteem Considerations
Opt-in is probably better than opt-out from a UX standpoint too. What would make you, as a user, feel better about yourself? That you weren't careful and, oops, made a donation without really noticing? Or that you actually made an effort (even if it's just some reading and making a click) to help someone? I'd hypothesize that making users more aware of their intentional charity boost their self-esteem more, and is thus a better UX.
That could even have a long-term upside for the charity. The user associates the charity with feeling good, not feeling stupid, so the user is more likely to donate again. It's a good research question to see if that's true*.
*Social psych geek corner: Dissonance Theory predicts tricking users into donating can actually make them more likely to donate in the future, but, I'd say the direct reward of explicit opt-in is a more certain and immediate benefit than dissonance reduction, and therefore I predict it to be stronger.
Comment: To be more specific this would fall under their [Sneak Into Basket](http://darkpatterns.org/sneak-into-basket/) patterns which [is now illegal in the UK](http://www.90percentofeverything.com/2014/08/26/some-dark-patterns-now-illegal-in-uk-interview-with-heather-burns/)
Comment: Here's the dark pattern shaming blog started by Harry Brignull (who coined the term 'dark pattern'): http://darkpatterns.org/
Answer: I just went through this experience as a customer. I unwittingly made a donation to a veteran's charity because the donation was set up opt-out at checkout. Even though the charity appears to be legit (upon doing some research after the fact), the experience makes you feel like you've been duped. An email to the business was followed by tremendous defensiveness about the practice and no apologies at all. This deepened my negative feelings about the experience with this online seller. Needless to say I will never do business with them again.


How to validate 2 inputs using form_validate that using 1 data field?

Question: I have this 2 form validation that validating 2 inputs that actually will go to 1 data field in db named kode_bthp like this :
<code>$this->form_validation->set_rules('kode_bthp', 'Kode Barang', 'required|trim');
$this->form_validation->set_rules('nup', 'NUP', 'required|trim');

$data = ['kode_bthp' => htmlspecialchars($this->input->post('kode_bthp', true) . $this->input->post('nup', true))];
</code>
the problem is I can't using is_unique feature because that 2 will be always unique (because not joined) and this data is not primary data so it will be inputted even it has same value.
then I tried something like this to join it first before get validated
<code>$kd_bthpjoined = $this->input->post('kode_bthp') . $this->input->post('nup');

$this->form_validation->set_rules($kd_bthpjoined, 'Kode Barang', 'required|trim|is_unique[bthp_master.kode_bthp]', ['is_unique' => 'Code Already Registered']);
</code>
question is, using variable <code>$kd_bthpjoined</code> can make it work ? because I tried to run it and didnt shows anything.
Answer: try make custom form validation using form validation callback, you can check on codeigniter documentation.
like this example :
<code>$ini = this->input->('kode_bthp'), true). $this->input->post('nup', true));

$this->load->model('model_name');
$query = $this->menu_model->getBthp($ini)

if(count($query)>0){
 //then . . . .
}else{
 return true;
}
</code>


What's the difference between next() and nextLine() methods from Scanner class?

Question: What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example).
Which one should I choose and why?
Comment: This may help you [Using scanner.nextLine()][1]: http://stackoverflow.com/questions/5032356/using-scanner-nextline
Answer: I always prefer to read input using nextLine() and then parse the string.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine() would be str.split("\\s+").
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Comment: @DavidConrad "What's the difference between next() and nextLine() methods from Scanner class?"
Comment: So, why not just use a `BufferedReader` to read line-by-line? I don't understand why `Scanner` is in such vogue.
Comment: Yes, I realize that's what the OP was asking about, I was just wondering since you say you "always prefer" to use nextLine.
Comment: You can safelly do a nextLine() and then create a new Scanner just for that line. The Scanner class can scan strings: new Scanner( new Scanner(System.in).nextLine() ).
Answer: next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
For reading the entire line you can use nextLine().
Comment: next() can read the input only till the **whitespace**. It can't read two words separated by a **whitespace**. **whitespace** includes space, tab and linefeed
Comment: @LuiggiMendoza you mean formatting, not formal writing?
Answer: From JavaDoc:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.

So in case of "small example<eol>text" next() should return "small" and nextLine() should return "small example"
Comment: This is a question to the Java API designers, or post a question on SO and maybe somebody knows why.
Comment: why doesn't `next()` include the `\n` in the returned token??
Answer: The key point is to find where the method will stop and where the cursor will be after calling the methods.
All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.

For example, consider the following illustration:
|23_24_25_26_27\n

| -> the current cursor position
_ -> whitespace
stream -> Bold (the information got by the calling method)
See what happens when you call these methods:
nextInt()

read 23|_24_25_26_27\n
nextDouble()

read 23_24|_25_26_27\n
next()

read 23_24_25|_26_27\n
nextLine()

read 23_24_25_26_27\n|

After this, the method should be called depending on your requirement.
Comment: such an underrated answer. everything else is slightly misleading
Answer: What I have noticed apart from  next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string
public class ScannerTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int cases = sc.nextInt();
        String []str = new String[cases];
        for(int i=0;i<cases;i++){
            str[i]=sc.next();
        }
     }

}

Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.
Comment: Very interesting example. Running the code I finally saw how `next()` works in practice, it does ignore the enter key, whereas `nexLine()` accepts it as complete input and it replicates it to console if you echo the value of what was captured. I just added `System.out.println(str[i]);` as a new line below `str[i]=sc.next();` or `str[i]=sc.nextLine();`
Comment: @PabloAdames appreciate if you can upvote if the answer if you like so
Answer: next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}

Output:
enter string for c
abc def
c is abc
enter string for d
d is  def
If you use nextLine() instead of next() then
Output:
enter string for c
ABC DEF
c is ABC DEF
enter string for d
GHI
d is GHI
Answer: In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.
Lets have a look at following snippet of code
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.next();
    }

when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as
Input as :- abcd abcd  or
Input as :-
abcd
abcd
Output will be like
abcd
abcd
But if in same code we replace next() method by nextLine()
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.nextLine();
    }

Then if you enter input on prompt as -
abcd abcd
Output is :-
abcd abcd
and if you enter the input on prompt as
abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)
Output is:-
abcd
Answer: From javadocs
next() Returns the next token if it matches the pattern constructed from the specified string.
nextLine() Advances this scanner past the current line and returns the input that was skipped.
Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.
Answer: From the documentation for Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

From the documentation for next():

A complete token is preceded and followed by input that matches the delimiter pattern.
Answer:
Just for another example of Scanner.next() and nextLine() is that  like below :
nextLine() does not let user type while next() makes Scanner wait and read the input.
 Scanner sc = new Scanner(System.in);

 do {
    System.out.println("The values on dice are :");
    for(int i = 0; i < n; i++) {
        System.out.println(ran.nextInt(6) + 1);
    }
    System.out.println("Continue : yes or no");
 } while(sc.next().equals("yes"));
// while(sc.nextLine().equals("yes"));

Answer: Both functions are used to move to the next Scanner token.
The difference lies in how the scanner token is generated

next() generates scanner tokens using delimiter as White Space
nextLine() generates scanner tokens using delimiter as '\n' (i.e Enter
  key presses)
Answer: A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.
Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position.
NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line.
so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().
 public static void main(String[] args) {
            // TODO code application logic here
           String str;
            Scanner input = new Scanner( System.in );
            str=input.nextLine();
            System.out.println(str);
       }

Answer: I also got a problem concerning a delimiter.
the question was all about inputs of

enter your name.
enter your age.
enter your email.
enter your address.

The problem

I finished successfully with name, age, and email.
When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

The solution
I used the delimiter for my scanner and went out successful.
Example
 public static void main (String args[]){
     //Initialize the Scanner this way so that it delimits input using a new line character.
    Scanner s = new Scanner(System.in).useDelimiter("\n");
    System.out.println("Enter Your Name: ");
    String name = s.next();
    System.out.println("Enter Your Age: ");
    int age = s.nextInt();
    System.out.println("Enter Your E-mail: ");
    String email = s.next();
    System.out.println("Enter Your Address: ");
    String address = s.next();

    System.out.println("Name: "+name);
    System.out.println("Age: "+age);
    System.out.println("E-mail: "+email);
    System.out.println("Address: "+address);
}

Answer: The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line.
   **
        Scanner sc=new Scanner(System.in);
        String s[]=new String[2];
        for(int i=0;i<2;i++){
            s[i]=sc.next();
        }
        for(int j=0;j<2;j++)
        {
            System.out.println("The string at position "+j+ " is "+s[j]);
        }

**
Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0].
We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.
Answer: The difference can be very clear with the code below and its output.
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        List<String> arrayList2 = new ArrayList<>();
        Scanner input = new Scanner(System.in);

        String product = input.next();

        while(!product.equalsIgnoreCase("q")) {
            arrayList.add(product);
            product = input.next();
        }

        System.out.println("You wrote the following products \n");
        for (String naam : arrayList) {
            System.out.println(naam);
        }

        product = input.nextLine();
        System.out.println("Enter a product");
        while (!product.equalsIgnoreCase("q")) {
            arrayList2.add(product);
            System.out.println("Enter a product");
            product = input.nextLine();
        }

        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();

        System.out.println("You wrote the following products \n");
        for (String naam : arrayList2) {
            System.out.println(naam);
        }
    }

Output:
Enter a product
aaa aaa
Enter a product
Enter a product
bb
Enter a product
ccc cccc ccccc
Enter a product
Enter a product
Enter a product
q
You wrote the following products

aaa
aaa
bb
ccc
cccc
ccccc
Enter a product
Enter a product
aaaa aaaa aaaa
Enter a product
bb
Enter a product
q

You wrote the following products

aaaa aaaa aaaa
bb

Quite clear that the default delimiter space is adding the products separated by space to the list when next is used, so each time space separated strings are entered on a line, they are different strings.
With nextLine, space has no significance and the whole line is one string.


Who first noted that entries in the powers of an adjacency matrix of a graph count the number of walks on the graph?

Question: The Wikipedia article on powers of an adjacency matrix presently (as of 2022) notes the neat combinatorial fact that, given an adjacency matrix $A$ of some graph, entries of the $n$th power of the adjacency matrix, $A^n_{ij}$, count the number of $n$-length walks from $i$ to $j$.  The Wikipedia article further relates this to the problem of counting the number of triangles in said graph by dividing the trace of $A^3$ by $6$, and determining the distance between two nodes in an undirected, unweighted graph.
The Wikipedia article does not name these as lemmas or theorems or corollaries, and states them with only the briefest outline of the proof.

Are these folk results, or is there any other interesting history behind who first formulated and proved them?

These are very nice and fun statements to prove, but I'm curious to know if there's anything else to say about their history.
(I am especially interested in how quantum computers could efficiently explore spectral properties of certain large adjacency matrices of certain large graphs, as, by linearity, exponentiation of the spectrum corresponds to exponentiation of the given adjacency matrix - which then corresponds to counting various walks on the graph.)
Comment: This idea might go back further than the definition of matrix product in its modern form, which makes it very hard to track down. (This is true, for example, of Kirchhoff's original version of the matrix-tree theorem, which - in 1847 - predates the modern notions of both matrices and trees.)
Comment: That being said, I did not encounter powers of the adjacency matrix in König's *Theorie der endlichen und unendlichen Graphen*, which in 1936 was the first textbook on graph theory. So it's possible that this fact is more recent.
Answer: In 1949, social psychologist Leon Festinger and mathematicians R. Duncan Luce and Albert Perry (all working together) published papers introducing the idea in application to social psychology.
They divide this into two papers. One, more sociological, is The analysis of sociograms using matrix algebra by Festinger. This one carefully explains how matrix multiplication works for $A^2$, then does the whole thing again for $A^3$, then finally remarks:

It is apparent that these matrices may also be raised to higher powers to obtain the four-step or five-step or even more indirect connections among the members of a group.

The second paper is A method of matrix analysis of group structure by Luce and Perry. This one presents the result more abstractly and gives a proof. Paragraph 3.01 states:

In $X^n$ the entry ${x_{ij}}^{(n)} = c$ if and only if there are $c$ distinct $n$-chains from $i$ to $j$ (for proof see §5.04). Thus, if in the fifth power of a matrix of data $X$ we find that the number of $9$ occurs in the third row of the seventh column, we may conclude that there are $9$ distinct $5$-chains from element $3$ to element $7$.

Some results later on in the paper also mention something about the diagonal entries of the cube of the matrix, which ought to count triangles, but the results are confusingly phrased.

It is, of course, possible that matrix powers of graphs were known to graph theorists before they were known to sociologists, but I don't have any evidence of this. Bracketing the time window above from both sides, we have:

König's 1936 textbook Theorie der endlichen und unendlichen Graphen, which does define adjacency matrix of graphs, and presents several results on the determinants of the adjacency matrix, but does not even consider products or powers of these matrices. I consider the result on counting walks simpler and more likely to appear in a textbook, so this is some evidence that it was not yet known to graph theorists in 1936.
Berge's Graphs and Hypergraphs (I read the 1973 translation of the French textbook published in 1970) gives the following in Chapter 4, Section 5 (Counting paths):

Corollary 1. If $G$ is a graph and $A$ is its associated matrix, the general coefficient $p^i_j$ of the matrix $P = A^k$ (the product of $A$ with itself $k$ times) equals the number of distinct paths of length $k$ from $x_i$ to $x_j$ in $G$.

It would be interesting to see if Berge's 1958 book Théorie des graphes et ses applications contains this result, but I've been unable to check.


How to change the title of a Button in a TableView (Swift)

Question: I am trying to make a button when pressed to call a phone number. In the TableView the button's title is supposed to be changed with the contact dictionary I added
Here is the Button:
<code>    @IBAction func phoneLabel(sender: UIButton) {

    let url:NSURL = NSURL(string: "tel://contacts.phone")!
    UIApplication.shared.openURL(url as URL)
}
</code>
and this is the tableview where I'm trying to set the button tile to the contact phone numbers
<code>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as! customCell
        let contact = contacts.contactWithIndex((indexPath as NSIndexPath).row)
        print(contact)
    cell.phoneLabel.setTitle("\(phone)", for:UIControlState)
   return cell
}
</code>
There is an error occurring saying that the button has no value of setTitle. Any help would be awesome!
Comment: It's a label not the button
Comment: if you look at the code phoneLabel is the name of the button
Comment: Did you create an IBOutlet for it?  IBAction is only for handling button presses, etc.
Comment: Thanks! that worked
Comment: @DoughnutMan You have a single cell? Why your button connected as an action mode?
Answer: Assuming it's a button and not a label (looking at your sender definition), you must specify UIControlState.normal, not UIControlState.
https://developer.apple.com/reference/uikit/uicontrolstate/1618233-normal
Comment: Also, you probably need to change `"\(phone)"` to `"\(contact.phone)"`.  Or maybe you have a global variable called `phone`, but that doesn't make sense.
Comment: That too, but that wouldn't explain the "no value of setTitle" issue.


No virtual display when using modesetting in Ubuntu 20.04(xrandr: Configure crtc 3 failed)

Question: I have two graphic cards in my laptop(os: Ubuntu 20.04).
$ lspci | grep VGA
>> 00:02.0 VGA compatible controller: Intel Corporation UHD Graphics (rev 05)
>> 01:00.0 VGA compatible controller: NVIDIA Corporation Device 1f95 (rev a1)

I have enabled Nvidia prime in NVIDIA on-demand mode.
The /etc/X11/xorg.conf file looks like this
section "Device"
    Identifier      "intel"
    Driver          "modesetting"
    BusID           "PCI:0:2:0"
EndSection

And I added 20-intel.conf in /usr/share/X11/xorg.conf.d/ with following contents.
Section "Device"
    Identifier "intelgpu0"
    Driver "intel"
    Option "VirtualHeads" "2"
    Option "TearFree" "true"
EndSection

After rebooting I ran the following commands
xrandr --addmode VIRTUAL1 1920x1080
xrandr --output VIRTUAL1 --mode 1920x1080 --left-of eDP1

After that I was able to create virtual display. But the graphics was fuzzy & videos in vlc wouldn't play or started lagging.
After changing the driver to modesetting in 20-intel.conf
Section "Device"
        Identifier "intelgpu0"
        Driver "modesetting"
        Option "VirtualHeads" "2"
        Option "TearFree" "true"
EndSection

The fuzzy graphics issue was solved. But I can't create the virtual display using the above xrandr commands
I get the following error
xrandr: Configure crtc 3 failed.

Answer: currently I am trying to get the VIRTUAL1 Runnung as well and I think I found your answer:
https://github.com/kbumsik/VirtScreen/issues/16
create: sudo vim /usr/share/X11/xorg.conf.d/30-virtscreen.conf
with the content:
`# nvidia/nouveau/amdgpu device should be configured first before Intel GPU
Section "Device"
    Identifier "nvidiagpu0"
    Driver     "nvidia" # Because you are using Nvidia proprietary driver. Change to "nouveau" if you are using open source nouveau driver
EndSection
# Then configure intel internal GPU
Section "Device"
    Identifier "intelgpu0"
    Driver     "intel"
    # You may put Option "VirtualHeads" "1" here but it seem you don't need to put this for Ubuntu 18.04.
EndSection`

if you delete your 20-intel.conf you should be golden.
CHEERS
Comment: I've already tried this solution before posting this question here. This doesn't work for me. I get a black screen after ubuntu boots up.
Comment: I think this is because your default graficsdriver is modesetting.
I had the same issue aswell.
If you disable it, or plug in a HDMI cable and restart your displaymanager it changes to intel and nvidia and then i could use it
Comment: You can verivy this by booting without hdmi or vga plugged in, just your laptop and then enter `inxi -G`
and compare the output with when it is plugged in.

The folowing is a link to configuration with modesetting:
I haven't tried it though. You could tell me if it worked, if you tried it.
https://unix.stackexchange.com/questions/585069/unable-to-add-a-virtual-display-to-xorg/585078#585078


Trouble Dual Booting Ubuntu 14.04.5 and OS X

Question: I was following this guide:
http://www.howtogeek.com/187410/how-to-install-and-dual-boot-linux-on-a-mac/
on how to dual boot ubuntu 14.04.5 on my Macbook Pro (2012) and got stuck just after the Ubuntu installation. I'm using rEFInd to recognize the Ubuntu partition and a bootable USB to hold the Ubuntu image for installation, prepared following this guide:
https://www.ubuntu.com/download/desktop/create-a-usb-stick-on-mac-osx
Ubuntu installs successfully, and after installing it says to restart the computer. However when I restart and select the Ubuntu partition (GRUB) and try to boot Ubuntu from there all I get is a black screen and Ubuntu never boots. Any idea what might be happening?
Comment: Sounds like you're missing kernel parameters from your grub config. What's your MBP model?
Comment: Wasn't sure what you were looking for so here's the hardware overview for my Macbook:

  Model Name: MacBook Pro
  Model Identifier: MacBookPro10,1
  Processor Name: Intel Core i7
  Processor Speed: 2.3 GHz
  Number of Processors: 1
  Total Number of Cores: 4
  L2 Cache (per Core): 256 KB
  L3 Cache: 6 MB
  Memory: 8 GB
  Boot ROM Version: MBP101.00EE.B0A
  SMC Version (system): 2.3f36
  Serial Number (system): C02HX34KDKQ1
  Hardware UUID: 967B66AF-E613-51C7-A120-EB009EAFA11F
Comment: I was looking for the MacBookPro10,1 part. I can't quite figure out why your setup wouldn't boot at this point. Have you tried passing 'nomodeset' to grub at boot? maybe its a video card driver issue? I usually install Ubuntu on my macs using refind as the bootloader and booting directly from the kernel stub instead of installing grub. There are a few guides out there on how to do this already. In case it helps, I'll try writing one up as an answer here as soon as I have the time.
Answer: Before proceeding further, you should understand that EFI-mode booting is not about booting partitions; it's about booting files. This fact doesn't alter the mechanics of day-to-day booting, but it's critical for debugging boot problems and doing manual boot loader and boot manager installations. In BIOS, boot loaders reside in the Master Boot Record (MBR; that is, the first sector) of the hard disk and in the first sector (sometimes called the Partition Boot Record, or PBR) of partitions. Thus, it's sensible to talk about "booting a partition" or something similar, on a BIOS-based computer. Under EFI, though, boot loaders are stored in ordinary files on a FAT partition called the EFI System Partition (ESP). (On Macs, boot loaders can also reside on various HFS+ volumes.) Thus, "booting a partition" is pretty much meaningless under EFI. (One partial exception relates to the fallback filename, which is EFI\BOOT\bootx64.efi on AMD64 systems; this filename is booted if no other registered boot loader can be found. It's most often used on removable media to make them bootable.) If you think your EFI-based computer, such as a Mac, is "booting a partition," you're likely to go on a wild goose chase when trying to debug boot problems. That said, I don't think your problem is fundamentally about the boot process, although it could be there's a tie-in somewhere....
For your specific problem, I have three suggestions:

Re-install rEFInd from OS X. Chances are your initial installation lacked an EFI filesystem driver for ext4fs (or whatever filesystem holds your Linux kernel). Re-installing now, after Ubuntu has been installed, should cause the refind-install script to set up the ext4fs driver, which will enable rEFInd to boot the Linux kernel directly. This may work better than going through GRUB. Note, however, that if you're using a filesystem other than ext4fs, you should instead install the appropriate filesystem driver manually. (See this page of the rEFInd documentation for details.)
See this question and its answers for information on "black screen" problems. These problems were rampant about two years ago, but have become much less common today. Causes were varied, so you may need to try multiple solutions.
Instead of installing the 2.5-year-old 14.04, install the 16.04.1 or 16.10 version of Ubuntu. These distributions include newer software and so may work around the problem you're encountering. (Of course, the 14.04.5 you're using includes updates to some critical components, such as the kernel; but it's still behind the times on other software, which might be the cause of your black-screen problem.)


Returning ad-hoc view models from ASP.NET MVC2 Controllers

Question: I'm porting an existing system to ASP.NET MVC2.  In the current legacy app, the user can select from dozens of available fields to customize CRUD forms for different entities in the domain model, similar to the way ERP systems allow customization of core modules.
My question: I'm looking for a good pattern or example for this kind of behavior in ASP.NET MVC2.  It seems to me it's rather like creating a ViewModel dynamically based upon user choices, or perhaps the right approach is data-driven view pages that aren't strongly-typed where I can reflect over the results client-side to determine field headings or something -- if that makes sense :).  Or maybe I can drive AutoMapper or similar dynamically @ runtime based on user choices?
The underlying domain model is EF4-based and I'm using a simple Repository pattern @ present for the ViewModel.
TIA for any input!  Michael
Comment: To clarify - customising CRUD forms and actually completing the CRUD form will be two distinct steps?
Comment: Hi Ahmad - Yes that is correct:  There's effectively a 'design time experience' for the end user to pick fields for forms, and then there is CRUD use of that form.  Two distinct steps, as you said.
Comment: It looks like ASP.NET MVC3 has some interesting ViewModel plumbing, and I'm looking at Dynamic Data and Expandos in .NET4 -- I should mention that I can assume .NET4 for this project, and we can consider MVC3 even though it is alpha right now.
Comment: In particular this article looks interesting: http://www.gregshackles.com/2010/09/anonymous-view-models-in-asp-net-mvc-using-dynamics/
Comment: that's a Dynamic Data scenario. I'm not sure if you could even use it in an asp.net MVC view, but its worth a shot looking at its support as a control.
Answer: If I didn't find anything else that matched the needs and went on to do it custom, I would:

Use the ViewModel with all the fields / not just the ones the user picked.
Pass both the ViewModel and the view configuration to the view
Call some html helper that for each item in the configuration adds a field with the corresponding property in the model
The configuration could be passed as either part of a containing ViewModel or in a separate entry in ViewData
Depending on what you need, building/passing the view configuration could be put in an Action Filter. Alternatively the helper could pull it directly.

A different approach is if you need completely custom fields. I mean user defined fields. If that's the scenario, that's not typed at the controller level already, so I'd pass the list of fields/values to the view. The view can do a foreach on those adding the fields. Again that could be moved to a HtmlHelper.
Comment: Thanks Eglasius.  I think your approach could work.  Right now all fields a user can present are predefined -- they can change the labels to match their terminology, this is also like an ERP system.  But I was hoping to avoid sending lots of data to the CRUD views unecessarily -- there are LOTS of optional fields.  For "design time" sending all fields sounds like the right thing to do though, probably in a manner as you describe.
Comment: +1 Just what I was thinking, I feel that the view configuration should be a distinct element of the view data. The main reason being is that if users can customise end CRUD form, these choices will need to be stored and in all likelihood there will be some further logic involved in maintaining the configuration.
Comment: Hi Ahmad - Yes we'd need to store each user's view configuration regardless.  But if I take this route and send all fields all the time, it's not really dynamic or 'ad hoc', it's just controlling visibility based on configuration, right?
Comment: @mcmSEA yes, it'd be controlling visibility. If its completely custom, I don't think building a model for it adds any value, I'd use lists of fields vs. values for it. In fact, I built a product that does it that way back in asp.net 1.0 / I don't think the forces involved for the particular challenge are any different.


Finding an upper bound of $ T(n) = \sqrt{n} T \left(\sqrt n \right) + n$

Question: $$T(n) = \sqrt{n} T \left(\sqrt n \right) + n, n>1$$
$$T(n) = k, n\le1$$
My book says for upper bound to simplify to
$$T(n) \le \sqrt{n}c\sqrt n\log\left(\sqrt n\right) + n$$
$$ = nc\log\left(\sqrt n\right) + n$$
$$ = \frac{1}{2}nc\log\left( n\right) + n$$
$$ \le cn\log\left(n\right)$$
A few questions here: how does $T(\sqrt n)$ simplify to $c\sqrt n\log\left(\sqrt n\right)$?
Or maybe I'm just asking: How do we know for sure that $T(\sqrt n)\le c\sqrt n\log\left(\sqrt n\right)$?
Also, how does $\frac{1}{2}nc\log\left( n\right) + n$ simplify to $ cn\log\left(n\right)$?
By the way, the book says that it assumes that $1\le\frac{1}{2}c\log{(n)}$.
Comment: The equation doesn't make sense when $n=1$
Comment: Alright. Edited, so it makes sense at $n=1$, but I don't think it matters when trying to find the upper bound?
Answer: We can use the change of variable $a_n=T(2^n)$ to get the recursion
$$
a_n=2^{n\over2}a_{n\over2}+2^n=2^{{n\over2}+{n\over2^2}}a_{n\over2^2}+2\times2^{n}=2^{{n\over2}+{n\over2^2}+{n\over2^3}}a_{n\over2^3}+3\times2^n
=\cdots=2^{n(1-{1\over2^m})}a_{n\over2^m}+m2^n\\
\implies a_{2^m}=2^{2^m-1}a_1+m2^{2^m}\implies a_m=a_{2^{\log_2m}}=2^{m-1}a_1+2^m\log_2m\\
\implies T(m)=a_{\log_2m}={ma_1\over2}+m\log_2\log_2m
$$
So a solution to the given recurrence is ($\alpha$ is a constant which equals $T(2)/2$)
$$
T(n)=\alpha n+n\log_2\log_2n
$$
which falls apart at $n\le1$ as pointed out in the comments. Suppose $n\ge2$. Then
 $\alpha n\le \alpha n\log_2 n$ and $n\log_2\log_2n\le n\log_2n$. Letting $c=1+\alpha$ we have
$$
T(n)\le cn\log_2n
$$
Comment: lol give me a while to understand your answer ^_^"
Comment: It seems to be a good answer... but I think that book wanted to find the answer in a different way. It seems to ask for a "guess and confirm" method.
Comment: @TakamaruTaihou You're right. But I couldn't have guessed that :)
Comment: Thanks for the answer though! I at least understand that the book is correct now :\


Kodak scaner i1150 and s3000 series scaning issue on dell optiplex 7040 65w using 22.04

Question: I am using dell optiplex 7040 (snap attached)
I have installed the drivers of the scanner it installed successfully after adding multiarch support
after lsusb it shows scanner and after xsane started it shows failed to open device
system information
scaner output
command output
Answer: Many device access problems are permission problems, and can be resolved through group membership changes.
You can find the device name by watching sudo journalctl --follow as you connect your device. OR ls -1 -l /dev >dev.before, connect the device, wait 10 seconds, ls -1 -l /dev >dev.after;diff dev.{before,after}.
Specifically, if ls -l  shows that the group permissions (the second "rwx" triplet) is "rw" (e.g."-rw-rw----"), then, adding oneself to the group that owns the device will grant rw access.
Here's how:
# change to your device name
device="/dev/YourDevice"
sudo adduser $USER $(stat -c "%G" $device)

This allows you membership in the group that can rw the device, but there is one more step.
To make all your processes members of the new group, logout and login. Group memberships are set up at login time.
To create a single process in the new group (for testing, prior to logout/login):
newgrp $(stat -c "%G" $device)

or, just type the group name. See man newgrp.


Pandas: remove duplicates from a Dataframe where lots of numbers are duplicated

Question: I'm trying to go:
From this --> to this
input

output

I am editing this to try and explain better. I have a dataframe with two columns (let's call themm A and B). The Column B has a number from 0-8, abut will often be repeated in succession with each entry of the dataframe. e.g. 0, 0, 0, 2, 2, 2, 8, 8, 6, 6. In this example I would like to drop most of the rows so that column B would only read 0, 2, 8, 6.
I thought I could use drop_duplicates. However because all the rows contain a number from 0-8 they are all duplicated, all the rows are dropped. I hope I have explained better this time.
Comment: try this--> df.drop_duplicates(keep='first', subset= ['column_name'])
Comment: Please, try building a better description of your problem so we can understanding it correctly. Here is a simple guide to take you through: https://stackoverflow.com/help/how-to-ask
Comment: I've rephrased it to try and explain it better
Answer: Try this:
df = df[df[1]!=df.shift(-1)[1]]

This will keep all rows where the value in the second column is different from the value from the previous row. Or in other words, it will drop all rows that have the same value in the second column as the row before
Answer: if I understood correctly you just want to use unique
newColA = df['colA'].unique()
newColB = df['colB'].unique()

new_df = pd.DataFrame([newColA, newColB]).T

there are better solutions, but I guess you're looking for something easy to understanding ;)


Is there a way to place a sign post?

Question: In Civ-4 you could place a sign post on the terrain.
I would place a sign post to say that a city was my naval building base.
Can you do this in Civ-5?
Answer: There is no way to do that in unmodded Civilization V. Additionally, I don't know of any mod which can enable something like this.
You can rename your cities, though, which might be a good idea to solve your problem; e.g. rename your city to be called "Naval Base".
Comment: or something more creative like "Newport News"

Is there a way to place a sign post?


java jsoup get text fail

Question: I am very new in java jsuop
I want to get the last price in follow line:
http://www.aastocks.com/en/forex/quote/quote.aspx?symbol=NZDHKD&process=y
and i have the follow code:
Elements answerers = document.select("div.content div.inline_block.vat.float_l div.boxForex div.font26 span.neg");
But it return an error:
java.net.SocketTimeoutException: Read timed out
I think i am wrong at the  "document.select" part, can someone help me?
Many thanks.
Comment: No, the exception has nothing to do with the doc.select. It's caused by the get method. Edit your question and add the relevant code.
Comment: Did my answer resolve your issue? Then please accept it or post a follow up question otherwise http://stackoverflow.com/help/someone-answers
Answer: The response from the server takes too long, so the default timeout is reached and an exception is thrown:

If a timeout occurs, an IOException will be thrown. The default
  timeout is 3 seconds (3000 millis).

So just set a higher timeout:
Example Code
String url = "http://www.aastocks.com/en/forex/quote/quote.aspx?symbol=NZDHKD&process=y";
String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36";

try {
    Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(5000).get();
    System.out.println(doc.select("div.content div.inline_block.vat.float_l div.boxForex div.font26 span.neg").first().text());
} catch (IOException e) {
    e.printStackTrace();
}

Output
5.6813

java jsoup get text fail


How do you get the new Kairos Dragon in Dragonvale?

Question: The new Kairos Dragon is a legendary dragon in Dragonvale.
What do I need to do in order to breed one?
Answer: You can't buy, sell or breed the Kairos Dragon.
You need to buy the perch of Kairos, which comes under habitats or buildings.
There are three parts to it and seven pieces to each part.
You must complete each of them before you can summon the dragon.
You can get pieces by racing on the dragon track. As far as I know, you can only get one per day.
Comment: Hi Bryan, welcome to Arqade.  FYI, I have tested, and can confirm that you can get more than one per day.  It is possible to land on the same one more than once though, which may result in you not getting a piece even though you landed on one.
Comment: Acually you can get more than a statue a day, in my case i just updated the game and i need one more piece for the first statue it only took 10 min
Answer: I found some good information here:
Dragonvale Kairos Dragon
"You cannot breed or buy Kairos, you have to summon him! First you have to buy the Perch of Kairos (750,000 coins). Then you need to gather three artifacts: the Chronolith, the Time Claw and the Statue of Kairos. The artifacts are built by collecting 21 time fragments. They can be won on the Dragon Races or bought for 2,700 gems total."
Answer: The Karios Dragon in Dragonvale is not breedable, but you can earn it by winning Dragonvale Races apparently.
You could check out this guide about Dragonvale Breeding it might help you with others too
Dragonvale Breeding Guide
Answer: It is possible to get more then one per day, just slowly tap the race button so then it works! But you cannot get the kiaros by breeding.


Bash script to compare ip addresses from web and local file

Question: I'm fairly new to bash and am still trying to figure some stuff out. Currently I'm writing a simple script to grab the ip address value from a website (via wget) and compare it with the address I already have stored on the machine to check for address changes. This is what I have so far:
#!/bin/bash
currentIp=$(cat /root/ip.log)
if "$currentIp" == $(wget -O - -q -nv --delete-after www.icanhazip.com)
then
    echo IP address is unchanged
else
    echo IP address has changed
fi

But, after running it, bash is replacing the variable currentIp with its value and then trying to run it as a command (I have replaced my ip address with x's in this example):
line 3: x.x.x.x: command not found
IP address has changed

Answer: You have a little syntax error in your expression. Use this instead:
if [ "$currentIp" == $(wget -O - -q -nv --delete-after www.icanhazip.com) ] ;


Should I have a table column with total price?

Question: I have the following SQL Scheme:
create table dbo.Baskets (
  Id int not null primary key clustered (Id),
  Name nvarchar (80) not null
)

create table dbo.Products (
  Id int not null primary key clustered (Id),
  BasketId int not null,
  Price decimal (10, 2) not null,
 Name nvarchar (80) not null
)

So one basket can have many products.
I often need to find baskets in a specific price range.
I know the basket price is the sum of its products prices.
QUESTIONS

Should I add a column to Baskets with TotalPrice?
Would this improve query performance a lot?
Can this be done automatically when Products are updated?
Should I index some column here?
Comment: Caching aggregate values is a valid optimization strategy, yes. The cost is increased efforts on keeping them current.
Comment: That is why I asked if that was an automatic way to update the basket total price when a product is updated.
Comment: use `trigger` to update it
Comment: it would depends on your runtime selecting how many records, and will the calculation logic change from time to time due to new business logic added in or not, like tax rate or etc
Comment: I will have not more than 80 baskets. Each basket will have only 4 to 6 products ... And the only calculation I am making is summing the prices not more. The most common query is: "Get a random basket with total price between 200 and 400".
Comment: When it comes to performance, it's always a good idea to specify the product you are working with. You cannot (should not) expect that every suggestion on performance improvement applies to every RDBMS.
Answer: Personal opinion, and I might actually get a lot of hate for this, but this sounds like a clear case of premature optimisation.
Is the JOIN required to compute the total cost of a basket a bottleneck?
If not, any effort you're spending here rather than optimising actual bottlenecks is ill-spent. If it takes, say, 1% of the whole process, but you speed it up by 100%, your process is going to go 1% faster.
If, on the other hand, you find some other part of the process takes 90% of the time and you speed it up by 10%, you've made your process 9% faster.
If this JOIN is a bottleneck, or at least slow enough that it impacts user experience, you have to weight the pros and cons.

Pros: it's faster.
Cons: you have to do a significant amount of work maintaining duplicated information in your database.

This con is, to me, rather large. From experience, on most real life projects, duplicating information in database is going to cause bugs - there will be a time when some refactoring, unforeseen / untested for edge case, tired co-worker fixing another issue, .... is going to cause your production service not to update the total price of the basket correctly, and you will display incorrect information to your end-user.
You just need to decide whether a rare incorrect total basket price (possibly never, more likely very rarely but still happening) is acceptable for the performance increase.
If you've not quantified that performance increase yet, why are we having this discussion? You're talking about duplicating database information (a BAD THING) because it might bring unknown and possibly null benefits.
Answer:
Having Total on Order is a common practice.
It will, as you don't have to calculate it on the fly which requires INNER JOIN and aggregation. If you list orders often in UI, you can display total without recalculating it.
This can be done with a trigger.
You can add an index, if you use that field often in WHERE clause.

Best solution in early stage will be to isolate your implementation from application by using a view for orders where total amount and other aggregated fields will be available. Once you hit the performance problem, you can add calculated field without affecting your code.
If you database allows window functions calculate total as:
SUM(amount) OVER (PARTITION BY OrderID) AS TotalAmount
Answer: As always...it all depends.
Pros of adding a calculated column (TotalPrice)
No need to recalculate every time especially if doing a retrieve based on totalPrice (less CPU time but more disk space and retrieval effort)
Cons
Possibility of introducing an error if another field changes such as price of one item. or if you decide to add another column such as qty, or discount.
The best way to determine which is the right way forward is to test.  One way is to normalise everything, that is not have a total price, and take metrics, and then after some time add the totla price as an optimisation and take further metrics and see if there is an improvement.
Same with the indexes although columns that you are doing a search on should be indexed.
Hope this helps


CodeIgniter form call to undefined function form_dropdown() error

Question: I want to create 2 dropdown list. First of them includes main categories, second one includes subcategories.
In codeigniter view i have this lines:

        Top Level Option
        <?php echo form_dropdown('options', $options, '#', 'id="options"'); ?>

        Sub Level Option
        <select name="suboptions" id="suboptions"><option value="#">-- Please Select Sub-option --</option></select>

But i have an error in echo form_dropdown() line:

Fatal error: Call to undefined function form_dropdown().

How can I use this form_dropdown()?
Answer: You need to load the form helper file at first.
Whether to use $this->load->helper('form') within the Controller (in which you load the view file)
Or to load the helper automatically by adding the name of the helper to $autoload array config:
application\config\autoload.php
$autoload['helper'] = array('form');


What are the bug and fish vendor spawn conditions? (CJ and Flick)

Question: CJ (fish purchaser) and Flick (bug purchaser) appear from time to time in my island town and offer better prices when selling fish/bugs.
What are their spawn conditions or do they appear randomly?
Answer: They appear randomly. Except CJ does appear once every season for the tourney (and you can sell him some fish that you caught outside the tourney)


Uniqueness of Smith normal form in Z (ring of integers)

Question: It is a very well known fact that Smith Normal Form has proven useful when dealing with the development of the structure theorem of finitely generated abelian groups. In this context, there is an approach that takes advantage of the next result, which indeed is a very particular case of a much more general theorem related with a special kind of rings.
If $A$ is a $m\times n$ matrix with integer coefficients, then there exist two matrices $P$ of size $m\times m$ and $Q$ of size $n\times n$, both having integer entries and $\det =\pm 1$, such that $PAQ$ is a diagonal matrix with diagonal entries $d_1,d_2,\ldots,d_k$ ($k<\min(m,n)$) such that $d_1\mid d_2\mid \ldots\mid d_k$, and each $d_i$ is a positive integer.
Furthermore, $d_1\mid \ldots\mid d_k$ are unique.
I have no problem with the proof of the "existence" part of the last theorem. However, I can't manage to give a proof of the "uniqueness" part; at most, I can only show that if $d'_1\mid\ldots\mid d'_{\ell}$ have the same property, then $d'_1 = d_1$ (they are both the gcd of the entries of $A$).
The idea is not to give a proof using structure theorems, but only any kind of "very elemental" proof (dealing, if possible, just with $\mathbb{Z}$ properties, and not talking about general rings/modules).
Comment: This is not research level. Look at the gcd of size $i$ minors.
Answer: See here (page 76).
The main idea is this:
For each k, the GCD of all the determinants of $k \times k$ submatrices of $A$ (with possibly different sets of indices for columns and rows) is preserved under multiplying by integer matrices with $\det =\pm 1$. These invariants equal $d_1 \cdot \ldots \cdot d_k$ in the smith form for each $k$, determining it uniquely.


No Galois Theory in Godement's Cours d'Algebre?

Question: I just procured an English translation of Godement's Cours d'Algebre and was interested in reading the treatment of Galois Theory. I started to look for the relevant chapter in the ToC, but to my surprise the name "Galois" was nowhere to be found. Then I checked the index and it couldnt be found there either. But the author claims that his book covers the whole undergraduate algebra curriculum for UK universities, and this definitely includes Galois Theory, so I'm slightly confused. Does this have anything to do with politics? Any explanation/clarification would be much appreciated!
Comment: I'm not sure if this question should be in math stack exchange. This seems to be outside of anything mathematical; especially when referring to politics or the authors way of thinking. Perhaps the History of Science and Mathematics Stack exchange is more appropriate.
Comment: "Galois Theory" of the english matematician Ian Stewart (London. Chapman  and Hall) is good for you. And if you accompany it with "Algebraic Number Theory" by the same author, better yet.
Comment: The translation says "Although designed to meet the needs of French undergraduates [i.e., years 1 and 2], [the book] covers [...] the average Honors mathematics course in a British university." Was Galois theory taught in most British undergraduate programs in 1968? I'm not sure. Or perhaps this is a mistake on the part of the author.
Answer: There are four references to Galois in the (English translation) of the book :

page 13 : general intro to Groups, rings, fields
page 121 : Historically, it was the study of these groups (when the set $X$ is finite) by Galois that led to the general and "abstract" notion of a group.
page 154 : The first detailed study of finite fields was made by Galois.
pages 198 (footnote) : The study of algebraic numbers in the 19th century, by Galois and by the great mathematicians of the German school (Gauss, Kummer, Jacobi, Lejeune-Dirichlet, Dedekind, Kronecker, Hilbert), is at the origin of all of modern algebra and leads to results which are undoubtedly the deepest in the whole of mathematics.

and three more in the Bibliography.
As you said, there is no entry for Galois in the Index of Terminology, that is not an Index of Name.

We can see that also Nicolas Bourbaki, Elements of Mathematics. Algebra I: Chapters 1-3 (1998 - French ed.1970) has many references to Galois but treats Ordered groups and fields and not "Galois theory".
Answer: The extraordinary book "Cours d'Algèbre", de Godement was written in French because the conjuncture, in 1966, "a rendu urgente la redaction, en français, d'un ouvrage de référence accesible aux débutants"........"on a donc fait en sorte que sa lecture ne demande pas d'autres connaissances que celles qu'on pourrait acquérir dans l"Enseignement Secondaire".
I never forget the great impression made me the end of the book: "In a triangle, the length of each side is less than the sum of the lengths of the other two sides" .... but in the context of Hermitian forms, i.e. on Hilbert spaces but without naming them (although Hilbert is appointed, for  the celebrate "Nullstellensatz" on the part of algebraically closed fields).
Is not uncommon for translation of a book, it has some variations or adaptations; I do not know the translation matter of this post but the original work in French has been always for me as a work of art.
Answer: You are correct, this book does not cover Galois theory, although it does have some basic facts about field extensions.
The book was intended to cover the first two years of the French university curriculum as it was in the 1960s (when students would have had to take physics and chemistry at the same time as math - hence the lower rate of progression in math). Galois theory was typically a third- or fourth year subject at the time.
The preface says that the book covers "the average Honors mathematics course in a British university." That may well have been the case in 1968 but not today. I'm not sure of this, but this could explain the discrepancy.


inputStream String is different from string literal

Question: After trying to compare the inputStream String to another String, no matter what I do (.equals, .compareTo), they aren't equal, even though they are.
String readString = "READ";
System.out.println(method + " =? " + readString);
if (method.trim().equalsIgnoreCase(readString)) {
    System.out.println("Is READ");
} else {
    System.out.println("Is not READ");
}

It prints out,
READ =? READ
Is not READ

even though the method variable is definitely READ.
Then I messaged one of my friends who was having the same problem, and he said it's because of the inputStream where I parsed the method variable.
BufferedReader inFromClient = new BufferedReader(
    new InputStreamReader(
        connectionSocket.getInputStream()
    ,   "UTF8"
    )
);
StringBuilder arrInput = new StringBuilder();
char[] cbuf = new char[DEFAULT_BUFFER_SIZE];
int bytesRead;

// Build client's input and parse it
while (true) {
    bytesRead = inFromClient.read(cbuf);

    arrInput.append(cbuf);
    ...
    // lots of parsing below and then a break
}

I've tried my friend's solution: String created from inputStream is not equal to its string literal
But I ended up only getting part of the input I'm reading, unlike he did.
Comment: You should only be appending `bytesRead` bytes from the `cbuf`.
Comment: please put the code for what `method` is on the first chunk
Answer:
even though the method variable is definitely READ.

Actually, it is definitely not "READ".  If it was, then you would get different output.  The computer is NOT wrong.  The real issue here is that there is something about this that you do not understand.
(There is a lesson there ... which you would be wise to learn.)
There are two possible explanations for what you are seeing:

There are "invisible" (aka "non-printing") characters in one of the strings you are trying to compare.  By calling trim() you are removing leading and trailing whitespace, but there are other invisible characters that trim() doesn't remove (e.g. ASCII NUL characters).
There are characters that look like other ones ... but aren't.  Google for the search term "homoglyphs".

Indeed, looking at the code where you put characters into a StringBuffer (which presumably then gives you the String that you are testing ...), it is pretty clear that the problem is the first one.  You are creating a string from the entire character array ... not from the part of the array that you read characters into.  This line is incorrect:
arrInput.append(cbuf);

'cos you are ignoring the number of characters that were actually read.
Comment: Whoops, it's true that it is definitely not read if I am having this problem. Anyway, I parsed arrInput into multiple strings and then I compare them to a literal string. But when you said I'm not using the part of the array that I read characters into, do you mean cbuf? I'm actually using arrInput to parse.
Comment: Ah, I changed that line you mention to `arrInput.append(cbuf, 0, bytesRead);` But after doing that, I'm missing a lot of the input data. The data I'm trying to read has newlines (\r\n).
Comment: I can't tell you why that is happening, but it is *probably* in the code that you are not showing us.  Whatever, `append(cbuf)` is indisputably wrong.  Read the javadocs.


Grounded outlet with load for ungrounded outlet

Question: Moved into a place, nearly every outlet is ungrounded with the exception of a couple GFCI in the kitchen and bath. Needed three prong for the fridge (and really didn't want the new appliance completely unprotected) so grabbed a GFCI and went to install it in the appropriate place.
There's a ground wire attached to the box, it's part of the two-wire line back to the panel. I am able to identify this line into the panel. Looks like about half a dozen or so grounds run into the panel in total.
This outlet also has a load. The two-wire cable for the load does not have a ground wire.
The house is a bit older (80s) and I expected no grounds at all given the outlets. I've only ever seen all grounded or all not (I'm not exactly an electrician but I'm fairly handy) and I'm wondering, before I throw a grounded outlet in here, is one grounded outlet with load connected ungrounded outlets okay?
There's no chance I'm going to be running grounds to the subsequent outlets if they're not already run.
Comment: By "okay" I assume you mean "in conformance with code?" I believe it is, but the National Electrical Code is difficult to interpret in that regard and I know nothing of Ohio code or your local code. If you have electrical building inspectors there, you could ask one. However that might raise questions about the need for a building permit. I would connect the extension to other loads from the load side of the GFI outlet, but I don't know if that is required. Questions about code interpretation for home wiring are often transferred to the home improvement stack exchange.
Comment: The original house wiring sounds more like 1960 than 1980.
Comment: @CharlesCowie I suppose I should check code but I'm more concerned I don't burn the place down
Comment: Can you run ground wires from the ungrounded outlets back to the main panel or the grounding electrode conductor system by any path at all?
Answer: If you install a GFCI the load side of the GFCI can power 3 prong Ungrounded outlets just use one of the stickers in the box the GFCI comes with that says "GFCI protected no equipment ground" this is a legal way to update to 3 prong ungrounded outlets.
The home having 2 wire no ground points to pre 60's era fwiw.
It is possible that it had some level of requiring or to just prior to 3 wire requirements.
The current code allows you to run a ground wire (not a new cable as past code required) to any convenient location as long as the circuit comes from the same panel. So if you only have 1 main panel you can tie into another circuit's ground to provide a true grounded outlet instead of GFCI only protection. Note a plug in outlet tester that has a GFCI test function won't work on a no ground socket but the test button on the outlet will work.


Would you consider this button to represent that the device is currently on or off?

Question: Would you consider this button to represent that the device is currently on or off? The opacity switches to the other button once it is tapped. I just want to make sure that the state is fairly clear.
Comment: Welcome to the site, @Romeo! This question appears to be off topic because it doesn't really use the expertise of the people on this site. **Instead of asking people who run usability tests to act as test participants, why not just create your own impromptu test at your office?**  You could flash the above in a meeting and have people raise their hands to say which state they think it's in.  If there's a difference in opinions, you know you need to redesign it.
Comment: If you are interested in the problem in general have a look at this question: http://ux.stackexchange.com/questions/1318/should-a-toggle-button-show-its-current-state-or-the-state-to-which-it-will-chan
Comment: @3nafish I tried getting opinions but I wanted a larger sample from different people so the sample is more conclusive. I think it relates to UX because that will be a switch in the app and I do not want users to be confused as to which the current state of the controlled appliance is.
Answer: It's not very clear to me. It doesn't tell me the state, or even that it's a button.
Comment: This is just a small part from a bigger page. It is very clear to the user that it is a button and what it does. The only thing that might be confusing is the current state, if it is currently on or off.
Answer: Is there a compelling reason to use English text rather than the ubiquitous power on/off symbol? This could be rendered in such a way as to indicate power on or off.

You've then reduced the button set to a single button with 2 states.
Comment: Just for design reasons.
Answer: When you use a button for make an action Its important define and show the context of this button and its consecuences if the user submit it. Buttons by itself not show anything, only the text in the box.
Asked youurself:

What is the option enabled or disabled this button? (on, off)
What is the action of these buttons and your consecuences? (turn on/off the application, the mobile, the 3g...)

You can see this image like example.
Switch buttons example
In that image you can see what is the meaning of submit every buttons, the context of this buttons, what it will happen if I touch something, etc
Your buttons not bad (maybe you could considere some shadow effect...)but its important define the context and the consecuences.


UIToolBar selected button state

Question: I have a UItableView with a toolbar in the bottom. The toolbar has two buttons say 'fruits','vegetables'. Clicking on them will display only the corresponding category.
I have managed to get the displaying feature working, but i do not know how to set the button in selectedState when chosen.
I created the toolbar as shown below
UIBarButtonItem *fruits = [[UIBarButtonItem alloc] initWithTitle:@"Fruits" style:UIBarButtonItemStyleBordered target:self action:@selector(fruitsClicked:)];
UIBarButtonItem *vegetables = [[UIBarButtonItem alloc] initWithTitle:@"Vegetables" style:UIBarButtonItemStyleBordered target:self action:@selector(vegetablesClicked:)];
NSArray *items = [NSArray arrayWithObjects: fruits,vegetables,nil];
[fruits release];
[vegetables release];
[self setToolBarItems:items];

and selectors like
-(void)fruitsClicked:(id)sender{
     //code here
}

Since i release the buttons earlier, i am not able to set
fruits.enabled=NO;

ANy help would be appreciated.
Answer: I think adding separate Buttons to do that is not a good design and strategy, you should use a UISegmentad control which is a component design for what you want: have one segment selected among X.
You can use it like this (to select the first item for example):
UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:array];
[segment setSelectedSegmentIndex:0];

And to get the selected item:
segment.selectedSegmentIndex

Comment: [toolBar setItems:[NSArray arrayWithObjects:segment, nil]];
Comment: how do i add the UISegementedControl to the toolbar ?
Comment: Sorry.I lost you somewhere.
Can you please show me how do i create the array.
Is it like
`NSArray *items=[NSArray arrayWithObjects:@"fruits",@"vegetables"];`

If so how do i set the selector methods ?
Comment: @Narayanan: You can drag and drop UISegmentedControl from the XIB onto the toolbar.
Answer: The sender argument passed to your fruitClicked handler will be a pointer to the UIBarButtonItem.  You can cast it like this:
[((UIBarButtonItem*)sender) setEnabled:NO];

However, once the button is disable it no longer accepts taps (i.e. you couldn't tap it again to re-enable it).  I would use a customView for the button and implement the enabled/disable appearance yourself.
Comment: If you really do just want to implement a set of buttons where only one at a time is selected though, you should follow Ludovic's suggestion and use a UISegmentedControl.
Comment: yes..agreed. How do i add the segmented control to the toolbar.?
Answer: I do not have any experience with UIToolBars, but from what i see, the selector gets the ID of the sender, right? You can use that to access the clicked button, and then set it selected.
Comment: There is no way to access a standard UIButton from a UIBarButtonItem, hence no way to `select` it, either.

UIToolBar selected button state


How to get all WebPart data / properties with PnP PowerShell?

Question: I'm trying to get all WebPart data/ properties on a SharePoint page using PnP PowerShell.
First I'm getting the page with:
<code>$page = Get-PnPClientSidePage "de/test2.aspx"
</code>
Then check the controls on the page:
<code>$page.Controls

InstanceId                           Type        Title          Section Column Position PropertiesJson
----------                           ----        -----          ------- ------ -------- --------------
0e3f7654-f18d-4df5-9401-ae7f47c9ad7d PageText                   1       1      1
3dea7c8a-3eec-4189-b96b-81b2474aa6a0 PageWebPart Image          1       2      1        {"imageSourceType":2,"altText":"Dies ist der alternative Text.","linkUrl":"","overlayText":"Dies ist der überlagerte …
8c4315ac-6803-4753-83ac-18c9eb00cbf0 PageText                   2       1      1
604b4f67-0a14-4174-9945-ac53f3c7c6c4 PageWebPart Quick links    2       1      2        {"items":[{"sourceItem":{"itemType":2,"fileExtension":"","progId":""},"thumbnailType":3,"id":2,"description":"","altT…
f2da7eff-d8f8-48a0-a667-e258023af088 PageWebPart Button         2       2      1        {"alignment":"Left"}
4fa743ae-5899-4f29-9647-3c6f86438050 PageWebPart Call to action 2       2      2        {"image":{"zoomRatio":1},"button":{"linkUrl":""},"overlayText":{},"alignment":"Left"}
cf321c08-0b57-4d2f-bdc4-f3d6cd90d157 PageWebPart Link           2       2      3        {"linkPreviewComponentMode":0,"displayLink":true,"cachedMetaDataUpdateTimeStamp":1657099833637,"listId":"","webId":""…
c04c7873-dd7a-4fca-bfb3-722b8e4da916 PageWebPart Hero           3       1      1        {"heroLayoutThreshold":640,"carouselLayoutMaxWidth":639,"layoutCategory":1,"layout":2,"content":[{"id":"baf0df3e-3fa1…
06c21f0a-159f-4a19-bdb2-3444250bda0a PageWebPart Image gallery  3       1      2        {"layout":1,"carouselSettings":{"autoplay":false,"autoplaySpeed":5,"dots":false,"lazyLoad":true,"metadata":true,"swip…
</code>
The problem is, that not all components include all information of the WebPart in die PropertiesJson. For example the Button WebPart properties only contain the alignment info, but of course the button also contains a label and a link. Same problem happens with the Quick Links, Call to action, Link, Hero and Image gallery WebPart.
Is there a way to get all properties from a WebPart?
Thanks in advance!
Regards
Alex
Comment: I am currently doing some research on this issue, will let you know as soon as possible.
Answer: You can use the following command to get Web Part property:
<code>Get-PnPWebPartProperty -ServerRelativePageUrl /sites/xxx/sitepages/xxx.aspx -Identity xxxxxx
</code>
For reference:
Get-PnPWebPartProperty
Comment: I am checking to see if the problem has been resolved. If you have any questions or progress, you can contact me in time.
Comment: The -Identity parameter is it the instanceId of the webpart on the page? for ex. I got the page through the Get-PnPClientSidePage command then got the webparts out with the controls property of the returned value in the prev. command. Is the InstanceId property of the control the value expected in the command you specified? if not where can I get this guid?


What is wrong with my code? (VB)

Question: Dim aryName As String() = Nothing
aryName = File.ReadAllLines(Application.StartupPath & "\Random\fnames.txt")

Dim randomWords As New List(Of String)
For i = 0 To aryName.Length - 1
If randomWords.Contains(aryName(i)) = False Then
    randomWords.Add(aryName(i))
End If
Next

Dim random As New Random
Label2.Text = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)

that code is supposed to take words from a txt file and then put them into a label, only problem is; the words are sometimes repeated. I only want each word to appear once but instead they appear multiple times.
Answer: You're using the entire array of words every time you check for a random word. My understanding of random.Next() isn't that it uses a different random number from 0-n each time it is called, but generates a new number from 0-n, which might repeat before n times has occurred.
To fix this, adjust your array each time you use a word - move the one it found to the end and adjust your range-1.
Answer: Remove the word from the array once is retrieved to avoid duplicates, I would use a List instead of an array to do that, good luck !

What is wrong with my code? (VB)