Configure a "hardened" user account that an attacker would have a hard time abusing

Question: Suppose you have a Windows Server machine running various sensitive services. Suppose that one of these services is pretty simple, maintaining a small amount of information in a text file, but as a result of being badly coded, has an (unknown) arbitrary code execution vulnerability.
Is it possible to set up a user account for that service such that if a hacker were to exploit this vulnerability successfully, the most damage they could do is read/write this text file, mess up this specific service, and possibly list the files out of C:\Windows, but nothing else?
A naive attempt at doing this immediately runs into a problem: anyone in "Users" can write to C:\Program Files, and removing "Users" from that directory's ACL results in a permission error, making me wonder if, perhaps, it is a very bad idea.
Or is the game already lost if the attacker can execute arbitrary code, regardless of which user account is used? I've always thought Windows NT descendants make it possible to contain this, but now that I've tried, I'm no longer so sure.
Comment: The first thing you need to do is harden (including your policies for handling anything on) the host itself.
Comment: I trust the users who log on legitimately. It's not super-sensitive stuff.
Comment: @romkyns - have you not heard of buffer overflow attacks? http://en.wikipedia.org/wiki/Buffer_overflow
Answer: By default, users can not write to C:\Program Files. They have Read, List Folder Contents, and Read & Execute. If that's not the case with you, then someone or something has modified those permissions.
A limited user can read much of the filesystem, but can only write to locations that it has explicitly been given access to, like its user profile.
If you grant Modify only to that one text file, the only thing that account will be able to write to on the filesystem is that file, plus things in its profile directory (My Documents, etc) which should be of no consequence.
If you have the built-in Users group having modify permissions all over your filesystem, then this is non-standard. Out of the box, limited user accounts can do very little damage.
By itself an arbitrary code execution bug is not especially harmless if the service account running its process is limited in privilege. The problem is that there are so many privilege escalation exploits out there that once you can arbitrarily execute code, you can just execute something that will allow you to break out of your privilege level. By itself, arbitrary code execution isn't a big deal, but in the real world it's almost always bundled with a privilege escalation exploit. So, yes, I'd be concerned.
Comment: You're right, the "Users" group does not have write access to Program Files. I'd still much rather prefer if the limited user could only read the locations it really has to be able to read, rather than having access to most of the disk.
Comment: @romkyns Same here. I'm still looking for a concrete solution. What was yours, if I may ask?
Comment: @dimitko I set up all sensitive data on a separate volume D:\, and removed the "Users" group from the ACL for the volume root. I then gave the service accounts access just to those parts of D: that they required. I left C:\ alone, so all service accounts have default access rights there. I don't consider this bullet-proof, just a part of "defense in depth".
Answer: Some quite interesting answers here.
Taking an empirical stance, with numerous post-penetration test "things to fix lists" under my belt, I would actually say that Microsoft have done a great job in recent years of providing the tools and options to harden a server very well.
Of course, MS still fuzz their code, and they and the community continue to find remote execution / privilege escalation exploits, but I've got to say, their patching is on-the-ball compared to some other vendors (SonicWall, Tivoli and Oracle spring to mind).
My recommendations would be:

Make sure User Account Control (UAC) is enabled
Ensure Data Execution Prevention (DEP) is enabled
Use managed service accounts (Windows 7 or Windows Server 2008 R2 and above)
Start with the absolute minimum privileges, and only add more if absolutely required.  I mean file system privs and User Rights Assignment (Local Security Policy or Group Policy)
Use Microsoft's Process Monitor to diagnose privilege issues (when experimenting ^^^)
Make sure the server is patched (Security patches at least, via WSUS)
If you have 3rd party software installed, keep that patched too.
Uninstall Java.  Unless you really need it.  Patch it.  Then patch it again 'cause the patch you applied didn't fix the fault that Oracle said it would.  Sorry, Oracle have ruined Sun Java!
Keep your hardware vendor's systems software up-to-date (BIOS, device drivers, Etc.)
Use Windows auditing to monitor activity of your new shiny account.
Forward events somewhere central.
Examine forwarded events daily or at least configure triggers to alert where necessary.
Enable the Windows Firewall (it's a shame, but so many people turn it off)
Ensure your server is backed up, so if the worst happens, you have your data.
Develop a plan for what you would do if the worst did happen.
Don't allow your server access to the Internet.  Again, I can't believe the number of data centres I've been to where there is open HTTP(S) access to the Internet for all servers.  Some people need to be taken aside for a chat.

It's important to remember, there is no such thing as a completely secure o/s, application or network.  It's all about layers of prevention, and identifying when things look different.  Don't get sold on Intrusion Detection either, unless of course, you a) are susceptible to hyped up sales pitches, b) have lots of free time on your hands and c) have plenty of spare $$$.
Finally, the most devious "attacks" these days aren't about disruption; quite the opposite.  The focus (and funding!) has switched to data exfiltration.
Comment: as a general principle then, is it wise to disable internet access for a server, even if the perimeter firewall won't allow any connections in to that server?
Comment: Yes, definitely.  Should the server be infected by a worm, (however unlikely) outbound access allows a reverse-proxy style command and control (C&C) channel to be established.  Essentially, your server can be controlled using response packets.  Also, unfettered outbound HTTP is an easy way to exfiltrate data.  Neither of these are theoretical risks.
Answer: In the Linux world, we would use SELinux or another mandatory access control mechanism to mitigate this sort of threat.
Windows doesn't have anything quite so robust, but since Vista/2008 it does have a basic integrity mechanism which you might be able to use. (Though, this has a rather high learning curve and explaining it fully would require more length than is permitted here.)
I think your best short-term mitigation would be to isolate the service in a virtual machine.
Comment: +1 For mentioning `SELinux`
Answer: If "execute arbitrary code" means the process can create directories, it may be possible for them to create directories either in the current directory, the service account's user profile directory, the root of the C:\ drive, or simply search for a directory where it can create directories.
Last time I checked, Windows usually conferred the permission to create directories in the root of C:.  You may not see this in the gui due to you would need to view the Advanced property page or use ICACLS to get a complete list of permissions.
Even if the C:\ root directory permission had been hardened, it is trivial to search all directories on C:\ and test for one where permissions allow the service account to create directories.  Chances are there will be one.
If the process exploit can create directories somewhere on C:, then it is fairly straightforward to disable the system by creating millions or billions of empty directories/subdirectories.
Empty directories are zero bytes, so are not subject to quotas.  These directories are also stored directly in the MFT (due to their small size), so even if the process could be stopped and the directories deleted, the MFT is effectively trashed - so large and/or fragmented that the system may need to be restored from backup.
Answer: Use DEP for all processes. It'll stop a majority, but there are a lot of exploits that can defeat DEP anyway.
Answer: Preventing abuse has to be done from the ground up - no point doing it to an account on an insecure server with a large attack surface
So;
1) Make sure the server is patched.
2) You can use SCW (Security Config Wizard) to harden the server.  It will do a faster and better job than most admins will do.
It allows you do undo the changes made, but it will only undo one-step.  So if you run it, lock stuff down and then run it again (i.e. if you missed something) and then you notice something is broken, if it broke that during the first lock down, you can't easily undo it (have to do it manually)
So, after running it and applying it, test functionality thoroughly.
3) Then, make sure you are using accounts which aren't admins, power-users etc and that they have only NTFS permissions to do the bare minimum of what they need to do - nothing else.
4) You can also use local security policy (or domain policy, if server is a domain member) to lock down other aspects of the GUI.
Answer: You could certainly try to create a secure user similar to the ones that come with windows that can't be logged into, and only have access to a certain files on the machine.  The con is that a privilege escalation exploit could work on that user depending on the situation.
With linux we chroot jail processes and services like this as part of a security mitigation strategy.  I'm not a Windows guy, but how would you do this in Windows?
One thing you could do to put the service in a sandbox is run it in a VM.  Virtualbox is my choice since you could even install it on the same box if you wanted to and make it start with the server, even headless, so it would almost run just like a service. It's free also. It's very difficult for an exploit to escape your VM.  The con to this approach is that you would run another whole instance of windows, which would itself need to be kept up to date and would consume resources.
Another thing that would work is using a dedicated sandbox program such as sandboxie that can sandbox any process to make it harder to escape if it gets compromised.


Entire functions $f,g,h$ with $e^f+e^g+e^h \equiv 0$ implies $f,g,h$ only differ by constant

Question: How to show complex entire functions $f,g,h$ with $e^f+e^g+e^h \equiv 0$ implies $f,g,h$ only differ by constant?
Progress
I tried using Picard's theorem. In the equation $e^{f−h}+e^{g−h}+1\equiv 0$, is it possible for  $e^{f−h}$ and $e^{g−h}$ to cancel each other out?
Comment: Have you already heard of Picard's (little) theorem?
Comment: @DanielFischer yes I know that. I tried using that theorem but still not work it out.. Could you give some more specific hints? Thank you!
Comment: Multiply with $e^{-h}$. See that $f-h$ and $g-h$ must leave out too many values to not be constant.
Comment: @DanielFischer can $e^{f-h}$ and $e^{g-h}$ cancel out each other?
Answer: After multiplying with $e^{-h}$ and renaming, we have the identity
$$e^{\tilde{f}} + e^{\tilde{g}} \equiv -1.$$
We know one value that neither $e^{\tilde{f}}$ nor $e^{\tilde{g}}$ ever attains. Therefore we know another value that these functions never attain. By Picard's (little) theorem, $e^{\tilde{f}}$ and $e^{\tilde{g}}$ are constant.


could not figure out how much is one extent?

Question: i got the homework from Devops school and one of LVM question below , i am confused with extents , teacher said that it should be calculated like this : 20x25 = 500 mb --> so the partition supposed to be made about 600 mb with extra space ! But from my google researches i found that 1 extent = 4 MB , 25x4 = 100 LVM=80MB ???
Create logical volume "datashare"  inside volume group called "datagroup"
Create  volume group "datagroup" from partition using 25M extents
Create logical volume with 20 extents /dev/datagroup/datashare
Answer: The disk I am using is 20GB in total size.
[root@centos7 ~]# lsblk /dev/sdb
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sdb    8:16   0  20G  0 disk

I create my first Physical Volume.
[root@centos7 ~]# pvcreate /dev/sdb
  Physical volume "/dev/sdb" successfully created.

I create my first Volume Group setting 32MG as the Physical Extentsize (PE) size, default 4MB, this defines how the space is being allocated (chunks of PE size).
[root@centos7 ~]# vgcreate -s 32M myvg /dev/sdb
  Volume group "myvg" successfully created

So my /dev/sdb disk size is 20GB, then I created the PV pvcreate, after this I created a new Volume Group with the Physical Extentsize (PE) size of 32MB.
Then I confirm this by the PE Size column.
[root@centos7 ~]# vgdisplay myvg
  --- Volume group ---
  VG Name               myvg
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  1
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                0
  Open LV               0
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               <19.97 GiB
  PE Size               32.00 MiB
  Total PE              639
  Alloc PE / Size       0 / 0
  Free  PE / Size       639 / <19.97 GiB
  VG UUID               m3wDvh-i0aH-5Zr2-0ya7-1GaA-mLb2-Umd9x3

SO here is the math disk 20GB to MB (20 * 1024 = 20480).
Then 20480 MB (Total disk 20GB) / 32 MB (The size I wanted my PE) = 640 (vgdisplay shows Total PE 639 because rounded values probably we did not have exactly 32 MB to have the last PE to have exactly 640 as expected.)
So if you need to create a new Logical Volume (LV):

You can use PE (which is 32MG and we have 639 available to use), so let say I want a new LV with 50 PE, 50 * 32 MB (PE size) = 1600 MB / 1.6 GB. (Please note Current LE 50 from PE it changes to Logical Extent)

   [root@centos7 ~]# lvcreate -l 50 -n mylv1 myvg
     Logical volume "mylv1" created.

   [root@centos7 ~]# lvdisplay /dev/myvg/mylv1
     --- Logical volume ---
     LV Path                /dev/myvg/mylv1
     LV Name                mylv1
     VG Name                myvg
     LV UUID                BuQsPK-UKWL-tdVv-bFkR-X2md-zG3o-xzQIKk
     LV Write Access        read/write
     LV Creation host, time centos7, 2021-10-10 20:38:33 +0000
     LV Status              available
     # open                 0
     LV Size                1.56 GiB
     Current LE             50
     Segments               1
     Allocation             inherit
     Read ahead sectors     auto
     - currently set to     8192
     Block device           253:0

or

You can ask LVM to create an LV with a specific size like 950 MB so 950 / 32 MB (PE) = 29.6875 but it can not use 29.6875 PE because it needs to be rounded up to use 30 PE (Current LE 30).

[root@centos7 ~]# lvcreate -L 950MB -n mylv2 myvg
  Rounding up size to full physical extent 960.00 MiB
  Logical volume "mylv2" created.

[root@centos7 ~]# lvdisplay /dev/myvg/mylv2
  --- Logical volume ---
  LV Path                /dev/myvg/mylv2
  LV Name                mylv2
  VG Name                myvg
  LV UUID                eJrAY2-Pb1x-VBbq-k8cI-vIlq-Tg3s-CsRFsB
  LV Write Access        read/write
  LV Creation host, time centos7, 2021-10-10 20:40:33 +0000
  LV Status              available
  # open                 0
  LV Size                960.00 MiB
  Current LE             30
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     8192
  Block device           253:1


Hermitian Matrix is complex matrix

Question: If M is an nxn complex matrix with $M^T = M^*$, then M is Hermitian.
So, I know that an nxn complex matrix is called hermitian iff $M^H$=M.
And $(M^T)^* = (M^*)^T = M^H$, so does this imply that the question above is true that $M^T = M^*$? No other proof to it?
Answer: Hint: Take the transpose of both sides of $$M^T = M^*.$$ (Caution: Sometimes $A^*$ itself is used to denote the conjugate transpose of $A$, in which case the conjugate of $A$ is usually denoted $\bar{A}$.)
Answer: Alternative hint: if $M$ is Hermitian, then $M^* = (M^H)^*$

Hermitian Matrix is complex matrix


Views joining/relating a custom table entity to users through a field?

Question: Using Drupal 7 and Views 3 - I have created a custom entity and can view it fine through Views using EntityDefaultViewsController. The Table is a view shared to the drupal database and is constructed like:
Table A
------------
id_key
data

I have a drupal user field - field_tableA_data that contains the same data type/items in the Table A data field (they are not linked in any way - two separate systems load this data - in TableA the data is generated by another system and the User field is loaded by the LDAP module)
I want to make it so that I can make a "View" such that when viewing Table A Items I can also make a relationship to the User entities such that:
Table A > field_tableA_data > User
Is this possible in code and if so how?
Here is some code I have tried and to no avail:
class TableAEntityViewsController extends EntityDefaultViewsController {

  /**
   * Edit or add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();
    $data['tableA']['data']['relationship'] = array(
      'handler' => 'views_handler_relationship',
      'base' => 'field_data_field_tablea_data',
      'base field' => 'field_tablea_data_value',
      'title' => t('TableA Data'),
      'label' => t('TableA Data'),
    );
    return $data;
  }
}

and in the module (table A entity I have a hook):
function (module)_views_data_alter(&$data) {
    $data['tableA']['table']['join'] = array(
    'field_data_field_tablea_data' => array(
      'left_field' => 'field_tableA_data_value',
      'field' => 'data',
    ),
    'user' => array(
      'left_field' => 'uid',
      'field' => 'field_data_tablea_data.entity_id',
    ),
  );
}

The best this gives me though is User:field_tableA data and no other fields from User - I'm trying to get uid and username.
Comment: Trying out:
https://www.drupal.org/project/relation
but not 100% certain it will work yet
Answer: I know this is not timely, but if someone else is looking for an answer:
Assumptions:
- Using Entity API
- Joining to another entity where the entity id is a field in your entity's base table
- It's a one-to-one relationship

Add the views controller class to your entity info file
function my_entity_entity_info() {
$info['my_entity'] = array(
  'views controller class' => 'MyEntityViewsController',
  ...
 );

2 Extend EntityDefaultMetadataController
class MyEntityMetadataController extends EntityDefaultMetadataController {

  public function entityPropertyInfo() {

    $info = parent::entityPropertyInfo();

    // This exposes the fields as references to views.
    $info['my_entity_base_table']['properties']['uid']['type'] = 'user';

   ....
  }
}


Working on a project on two computers at same time in Visual Studio

Question: My friend and I are working on an asp.net project and we want to work at same time, he is working on business classes and I want to use his methods. Is there any way to connect our computers, like local Team Foundation Server, and my computer gets latest changes from his computer?
I know git but the question is how can I run git on local and get the latest changes immediately?
Comment: Actually he should write methods in some classes and i should use them in other classes and as you know changes should be real time
Comment: I don't think this is a good idea, unless you're actually doing something like remote pairing (if you want more than just screen sharing, I've used https://floobits.com/ for this). If you're trying to consume classes at the same time they're trying to write them, what happens if they need to change the API? Why don't you try pairing until you've got enough surface area on the application to work independently?
Comment: I dont want to change his codes, just use his methods, for example he writes a method for adding item to some table and i want to use it,I have a local lan network.
Comment: You could start by agreeing *interfaces*, so you can test your code against mocks while he writes the implementation, then integration test the two together when you both finish.
Comment: how about sharing project folder in LAN network and open Visual Studio in each computer?
Comment: That seems like a recipe for conflicts and weird bugs. Why are you so determined to do this?
Comment: a simple reason: we have a project contains this files: MyLogic.cs and Default.aspx my friend should work on MyLogic.cs and write methods like AddMessage(string title, string message) and i want to use it in Default.aspx.cs, if we work same time i can not have his methods and i should wait to complete his codes and sync but if i had realtime access to MyLogic.cs i could write my codes, dont i?
Comment: http://stackoverflow.com/questions/43898731/working-on-a-project-on-two-computers-at-same-time-in-visual-studio?noredirect=1#comment74833846_43898731
Answer: If you want to use TFS, it has 2 version control methods for you: Git and TFVC. No matter which type of them, it needs to get down changes manually. When your customer commit and push the changes he made to Git repository, you need to pull down those changes to your local repository manually.
To know if there's some new changes submitted to TFS, you could use TFS alerts. Create an alert when commits push into TFS. Then you will get an email notification when your friend push his commits.
Answer: If both of your computers are on the same network, you can use git with his repo as a remote.  You will need to be able to access his repo over the network (SSH, file share, etc).  This allows you to pull directly from his git repo (after he commits; you can't pull his working copy).  It also gives you the freedom to not pull if he's making changes that would interrupt your workflow.
Otherwise, you could use a shared repository hosted somewhere (e.g. GitHub, Visual Studio Team Services, BitBucket, etc) and both push/pull as frequently as you agree to.  It also makes it easier to set up Continuous Integration so that you can make sure the repo is always in a buildable "clean" state before pulling changes locally.


Proving unit circle without y axis but with 0 is connected

Question: I'm doing Baby Rudin chapter 2 exercise 20 and trying to show that a set being connected doesn't imply that its interior is connected. The counter example I'd like to prove is the unit circle minus the y axis but plus the 0 point, ie
$$E = \{ x \in R^2 : dist(x,\textbf{0}) < 1 \land x_1 \neq 0 \} \cup \{ \textbf{0}\}$$
where $$x_1$$ is the x coordinate of the point in $$R^2$$
Intuitively E seems connected, as all the points on the left of the y axis touch each other, and likewise the points on the right, and the two sets are connected by the 0 point. Its interior isn't connected, as it will exclude the 0 point, and the sets
$$\{ x \in R^2 : dist(x,\textbf{0}) < 1 \land x_1 < 0 \} \qquad \{ x \in R^2 : dist(x,\textbf{0}) < 1 \land x_1 > 0 \}$$
are separated.
But I'm not sure how to prove that E is connected. For contradiction, assuming it isn't means that for some A and B whose union is E, they are disjoint and neither contains a limit point of the other, so each point x in A has a neighborhood without any points in B and vice versa. This feels like a promising road to go down but I'm not really sure where to go from there. Any advice?
Edit: Rudin's definition for E being connected is that no A and B whose union equals E are separated, where separated means that A union closure B is disjoint, and B union closure A is disjoint. I've seen that there are other definitions but would like to try to prove things with this one, or at least tie back other definitions to this one.
Comment: That seems correct to me. Another example would be a dumbell shape: two closed discs connected by a line between them.
Comment: Let $A$ be the left half plus origin. It is connected as $\textbf{0}$ is in the closure of the left half, which is connected (and if $A$ is connected and $A \subseteq C \subseteq \overline{A}$, $C$ is connected). Similarly for $B$ the right half plus $\textbf{0}$. Your set is their union which is connected as they intersect.
Answer: Do you have access to the concept of path-connectedness? Recall that a path-connected space is connected. Given this, we have a path between every two points $y_0$ and $y_1$ in $E$ by first passing from $y_0$ to $x_1$ using a line segment in time $\frac{1}{2}$, and then passing from $x_1$ to $y_1$ using another line segment again in time $\frac{1}{2}$.

If you aren't familiar with path-connected spaces, here are the relevant facts.
Definition 1. A space $X$ is path-connected if for each pair $y_0, y_1 \in X$ there exists a continuous function $f : [0, 1] \to X$ such that $f(0) = y_0$ and $f(1) = y_1$.
Lemma 2. A path-connected space $X$ is connected. (Exercise: show that the converse is not true.)
Proof. Suppose that $X$ is path-connected and also that $X = U \cup V$ for $U$ and $V$ disjoint open sets in $X$. Suppose for a contradiction that neither $U$ not $V$ is empty and let $y_0 \in U$ and $y_1 \in V$. Then by hypothesis there exists a continuous function $f : [0, 1] \to X$ such that $f(0) = y_0$ and $f(1) = y_1$. By the definition of a continuous function in particular the preimages $f^{-1}(U)$ and $f^{-1}(V)$ are both open subsets of $[0, 1]$, and because $X$ is the union of $U$ and $V$, the union $f^{-1}(U) \cup f^{-1}(V)$ is $[0, 1]$. But the preimages $f^{-1}(U)$ and $f^{-1}(V)$ are also disjoint subsets of $[0, 1]$! Because $[0, 1]$ is connected, one of the sets $f^{-1}(U)$ and $f^{-1}(V)$ must be empty, which is the desired contradiction (because $0 \in U$ and $1 \in V$). This completes the proof.
Comment: @TsviBenschar sure, I'll just write one down.
Comment: I haven't seen that definition, can you point me to a statement of the definition and a proof that it implies connectedness?
Comment: @TsviBenschar There you go: the notion of path-connectedness is very useful when you are dealing with most "reasonable" topological spaces.
Comment: Rudin hasn't defined function continuity yet lol, I know what it is intuitively from calc but not sure i could write rigorous proofs with it
Comment: @TsviBenschar I see---for your information so that what is going on isn't mysterious: a function $f : X \to Y$ is continuous if the preimage of every open set of $Y$ is open in $X$.
Answer: Kit-Wing Yu provides the following answer in A Complete Solution Guide to Principles of Mathematical Analysis.
Let $E$ be a connected set. Assume $\overline{E}=A \cup B$, where $\overline{A}\cap B = A \cap \overline{B}=\emptyset$. Since $A\cap E\subseteq A$ and $B\cap E \subseteq B$, we have $\overline{A\cap E} \subseteq \overline{A}$ and $\overline{B\cap E} \subseteq \overline{B}$. Since $A\subseteq \overline{A}$, we have $A\cap B\subseteq \overline{A}\cap B = \emptyset$. Since $E \subseteq \overline{E}=A\cup B$, we have
$$E=E\cap\overline{E}=E\cap (A\cup B)=(A\cap A)\cup (E\cap B).$$
Since $(\overline{A\cap E})\cap (B\cap E)\subseteq \overline{A}\cap B = \emptyset$ and $(\overline{B\cap E})\cap (A\cap E)\subseteq \overline{B}\cap A = \emptyset$, we have $E$ is disconnected, which is a contradiciton. Hence, $\overline{E}$ must be connected.
Now suppose that $A$ and $B$ are connected sets and $A\cap B \neq \emptyset$. Then the set $E=A\cup B$ is also connected.
Consider $A=\{x\in\mathbb{R}^{2}| |x|\leq 1\}$, $B=\{x\in\mathbb{R}^{2}| |x-(2,0)|\leq 1\}$ and $E=A\cup B$. $E$ is connected but $E^{\circ}$ is not.


Annotating Swift function declarations that support conformance to a protocol?

Question: Is there a standard mechanism for annotating function declarations in Swift to indicate that they are present because a class conforms to some protocol?
For instance, this declaration might be present because a class conforms to NSCoding. (Marking it with override would result in a syntax error, so it's not the kind of annotation I am looking for.) Ideally I am looking for a code-level annotation (e.g. override instead of /*! ... */).
// ... annotation such as "conform to NSCoding", if possible
func encodeWithCoder(encoder: NSCoder) {
   // ...
}

Comment: Annotating in a comment, or in the code?
Comment: @Aderstedt Annotating in the code would be best (see update to Q).
Comment: AFAIK there's no way to annotate protocol conformance in the code. Use comments.
Comment: @robertvojta Too bad. (I am using comments now but wish for an alternative.)
Answer: You can use extension. for example:
protocol SomeProtocol {
    func doIt() -> Int
}

class ConcreteClass {
    ....
}

extension ConcreteClass: SomeProtocol {
    func doIt() -> Int {
       // ...
       return 1
    }
}

But you cannot define required initializer in extension, for example:
// THIS DOES NOT WORK!!!

class Foo: NSObject {
}
extension Foo: NSCoding {
    required convenience init(coder aDecoder: NSCoder) {
        self.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ...
    }
}

emits an error:
error: 'required' initializer must be declared directly in class 'Foo' (not in an extension)
    required convenience init(coder aDecoder: NSCoder) {
    ~~~~~~~~             ^

In this case, you should use // MARK: comments:
class Foo: NSObject {

    // ...

    // MARK: NSCoding

    required init(coder aDecoder: NSCoder) {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ...
    }
}


Where do I programmatically create new roles?

Question: I want to programmatically create new roles in Drupal 8. I found this code in this post.
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

But I don't know where I should put it, in which file, which folder? And how do I run it?
Comment: when you need to create the roles?
Comment: You can do it when a module gets installed with hook_install, or you can choose to put it in a hook_update_n function. It's up to you. Don't "just" run code once that changes the db, because you will lose installability.
Comment: I have a list of roles and i want to create them, When ? Now
Comment: I don't want to do anything else, just create the roles
Answer: You have many place to create your roles, a simple way for you (As you says that you don't know nothing about Drupal) can be create a custom page (read the post) if you follow the example in the myPage() function you can go trough your list of roles and create each role in a loop, something like this;
public function myPage() {
...
  /* Read your roles
   * $my_roles[0]['id'] = 'client';
   * $my_roles[0]['label'] = 'My Client';
   */
  for ($i = 0; $i < count($my_roles); $i++) {
    //your data array
    $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
    //creating your role
    $role = \Drupal\user\Entity\Role::create($data);
    //saving your role
    $role->save();
  }
...
}

And if you go to your page you will create your roles.
EDIT: As Kevin says is better in other places like the hook_install()
Follow the steps to create a module and implement the hook_install() (Read at the end of the page how to do it)
Inside the hook implementation you will put the code:
/**
 * Implements hook_install().
 */
function YOUR_MODULE_install() {
    /* Read your roles
     * $my_roles[0]['id'] = 'client';
     * $my_roles[0]['label'] = 'My Client';
     */
    for ($i = 0; $i < count($my_roles); $i++) {
      //your data array
      $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
      //creating your role
      $role = \Drupal\user\Entity\Role::create($data);
      //saving your role
      $role->save();
    }
}

To create your roles you only need install your module.


If $Y$ is a locally compact topological subspace of $X$ then is $X$ also locally compact?

Question: If I have a topological space $X$ and a subspace $Y$ which is locally compact then does this mean that $X$ is also locally compact? For local compactness, I want to show that every point has a neighborhood base consisting of compact sets (I'm not assuming $X$ is Hausdorff).
Is it true that if $x\in X$ and $K$ is a compact neighbourhood of $x$ in $Y$ then is it also a neighbourhood of $x$ in $X$?
Many thanks!
Comment: Or take the disjoint union of a locally compact space and a space that isn't.
Comment: Consider a subspace consisting of a single point.
Comment: Or just $\emptyset \subset X$...
Answer: As people in the comments have pointed out, no this isn't necessarily true. In my experience in topology, a trait $T$ of a subspace $Y$ usually tells you nothing about the space $X$. Most typically you must first know that $X$ has the trait $T$ before even considering if $Y$ has $T$. If $Y$ has $T$ we call $Y$ "Hereditarily $T$". It is also very common that $Y$ has to be closed and or compact if it is to be hereditarily $T$.


R: calculating ICC across multiple columns in two dataframes

Question: I am calculating the ICC's for 301 variables of 2 readers. Results are saved in two files with 301 columns each. The first column of file1 (reader1$Var1) corresponds to the first column of file2 (reader2$Var302). I can perform the ICC manually (see below), but I need help to automate this process using apply or a loop. Thank you.
library(irr)
irr::icc()
a= data.frame(reader1$Var1)
b= data.frame(reader2$Var302)
X= data.frame (a,b)
function.ICC <- function (X) {irr::icc(X, model =c("oneway"), type = c("consistency"), unit =("single"), r0 = 0, conf.level = 0.95)}
Results <- function.ICC(X)
Results[7]

Answer: A combination of lapply and do.call could do for your case (although there's quite a few options). You don't provide a sample of your data, so I assume you first do a cbind of your 2 dataframes one after the other, so that in this toy example
> X = data.frame(cbind(1:10, 11:20, 21:30, 21:30))
> X
   X1 X2 X3 X4
1   1 11 21 21
2   2 12 22 22
3   3 13 23 23
4   4 14 24 24
5   5 15 25 25
6   6 16 26 26
7   7 17 27 27
8   8 18 28 28
9   9 19 29 29
10 10 20 30 30

you would like to run icc of X1 vs X3 and X2 versus X4. It would be something like the following, relying on function.ICC as you've defined it:
> do.call(cbind, lapply(1:2, function(i) function.ICC(X[,c(i, i+2)])))
           [,1]          [,2]
subjects   10            10
raters     2             2
model      "oneway"      "oneway"
type       "consistency" "consistency"
unit       "single"      "single"
icc.name   "ICC(1)"      "ICC(1)"
value      -0.8320611    -0.4634146
r0         0             0
Fvalue     0.09166667    0.3666667
df1        9             9
df2        10            10
p.value    0.9993158     0.926668
conf.level 0.95          0.95
lbound     -0.9526347    -0.8231069
ubound     -0.4669701    0.1848105

So, for your cbind'ed dataframes with 301 columns, omething similar to this should work:
do.call(cbind, lapply(1:301, function(i) function.ICC(X[,c(i, i+301)])))


Ordenar imagens pela altura de cada uma

Question: Tenho uma lista de imagens com dimensões diferentes. Queria que as imagens fossem ordenadas da menor para maior: a que tem height menor ficasse em primeiro e a de height maior ficasse por último. Utilizando apenas jQuery com HTML.
HTML:

Para gerar o código HTML utilizo Web Forms:
<%
 var parceiros = bdParceiros.ListarTodos();
 int i = 1;

 foreach (var parceiro in parceiros)
 {
 %>

            <%if(i==1){ %>

                <%} %>

                    <a href="<%=parceiro.Link %>" target="_blank">
                        <img class="well" style="background: none" src="http://ipupo.com.br/arquivos/Parceiro/<%=parceiro.Logo %>" title="<%=parceiro.Nome %>" />

                <%if(i==4){
                      i=0;%>

            <%}
                  i++; %>
            <%} %>

JSFiddle
Comment: Ok, mas seu problema não é no HTML. Poste o código que não consegue ordenar as imagens.
Comment: @user6492, eu nem sei como começar, não sei se é possível.
Answer: Aqui fica uma ideia, possivelmente daria para comprimir o código, mas é prático assim para ser perceptivel:
// colocar as imagens em cache
var imagens = $('img').get();
var row = $('.row');

// criar uma array de objetos, com a altura e o elemento que envolve cada imagem
var alturas = imagens.map(function (el) {
    var altura = el.getBoundingClientRect().height;
    return {
        altura: altura,
        elemento: $(el).closest('.col-lg-3')
    };
});

// arrumar a array de objetos por alturas
alturas = alturas.sort(function (a, b) {
    return a.altura - b.altura;
});

// apagar o conteudo original (atênção a possiveis event handlers)
row.html('');

// restaurar o conteudo, agora na ordem certa
$(alturas).each(function () {
    console.log(this.altura); // só para verificação
    $('.row').append(this.elemento);
});

Como o @bfavaretto indicou, nos comentários em baixo, lembre-se que este código deve correr somente depois de as imagens estarem carregadas, senão o cálculo de alturas não vai funcionar.
Exemplo: http://jsfiddle.net/mkm25zb4/
Comment: Só precisa garantir que isso rode após o carregamento de todas as imagens (por exemplo, no window.onload).
Comment: Só não entendi porque adicionou várias vezes as mesmas imagens.
Comment: @bfavaretto boa observação- Juntei esse detalhe.
Comment: @Sergio, no HTML existem 21 imagens, depois de rodar seu código ele replica, vira mais de 60. As imagens aparecem umas 3 vezes cada.
Comment: @DiegoZanardo, é assim que quer? http://jsfiddle.net/mkm25zb4/1/ - cada `.row` com as imagens ordenadas dentro de si?
Comment: @Sergio, na realidade é ter uma ordenação das imagens, igual sua resposta. Então para que o bootstrap não perca o alinhamento, é necessário que a cada 4 imagens esteja contida em uma linha.
Comment: @Sergio, mas acredito que não caiba nesta pergunta. Consegue ajustar aqui. Obrigado.
Answer: Você tem à disposição, via JQuery, a função sort(). Uma possível solução seria a seguinte:
$lista = $('div.row div.parceiros').sort(function (itm1, itm2) {
    return $('.well',itm1).height() > $('.well',itm2).height();
});

Após a ordenação, você pode modificar a lista original:
$('div.row').append($lista);

Veja aqui o exemplo no JSFiddle.
Comment: Bem visto, eu usei o `.sort()` nativo do javascript, você usou o do jQuery, que permite de facto re-posicionar os elementos. `+1`
Comment: @Sergio obrigado - de qualquer maneira, é sempre interessante saber como libraries como o JQuery manipulam elementos DOM. Neste caso, o seu post é mais completo.
Answer: $(function () {
var alturas = new Array();

var _height = 0;

$(".parceiros img").each(
    function () {
        alturas[$(this).height()] = $(this).height();
    }
);

alturas.sort(function (a, b) {
    return a - b
});

var _height = 0;
var print = "";
var j = 0;
$.each(alturas, function (index, value) {
    $(".parceiros").each(
        function () {
            if ($("img", this).height() == value) {
                if (j % 4 == 0) {
                    print += "
";
                }
                print += $(this)[0].outerHTML;
                if (j % 4 == 0) {
                    print += "
";
                }
                j++;
            }
        });
});

$("body").html(print);
});

Isso é uma possível solução.

Ordenar imagens pela altura de cada uma


Acessando os valores de uma lista 3D em Python

Question: Eu estou com uma questão que não estou encontrando uma resposta que não seja por uma estrutura de repetição: como acessar valores numa lista 3D.
Eu tenho uma lista que é uma pilha de 400 imagens de dimensão 2304x2304 pixel, (400, 2304, 2304).
Eu gostaria de selecionar um dado pixel, exemplo o 10x10 e acessar todos os valores desse pixel ao longo das 400 imagens. Eu havia tentado algo como vpixel = img[:][10][10]. Na minha ideia, a variável vpixel deveria ter 400 posições, porém está gerando uma variável com 2304 posições. Em uma estrutura de repetição eu consigo, pois eu fixo o pixel que eu quero e faço um for de 0 a 399 daí eu tenho todos os valores.
Mas eu queria uma maneira que não fosse necessário um for para tal, alguém poderia me ajudar?
Agradeço desde já.
Answer: Eu mesmo acabei encontrando a resposta. Eu transformei minha lista em um np.array(img) e acessei pelo método vpixel = img[:, 10, 10] e funcionou!!!!


keep linux subsystem service up and running forever

Question: I have created a subsystem file which runs java program I have created. The subsystem file resides in /etc/init.d and allows me to stop and start the service with a consistent interface (start and stop).  It is based off of this tutorial: http://www.tldp.org/HOWTO/HighQuality-Apps-HOWTO/boot.html
Here is what the script looks like:
<code>#!/bin/sh
#
# /etc/init.d/mysystem
# Subsystem file for "MySystem" server
#
# chkconfig: 2345 95 05
# description: MySystem server daemon
#
# processname: MySystem
# config: /etc/MySystem/mySystem.conf
# config: /etc/sysconfig/mySystem
# pidfile: /var/run/MySystem.pid

# source function library
. /etc/rc.d/init.d/functions

# pull in sysconfig settings
[ -f /etc/sysconfig/mySystem ] && . /etc/sysconfig/mySystem

RETVAL=0
prog="MySystem"
.
.
.

start() {
    echo -n $"Starting $prog:"
    java -jar /bin/app.jar
    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch /var/lock/subsys/$prog
    echo
}

stop() {
    echo -n $"Stopping $prog:"
    .
    .
    .
    killproc $prog -TERM
    RETVAL=$?
    [ "$RETVAL" = 0 ] && rm -f /var/lock/subsys/$prog
    echo
}

reload() {
    echo -n $"Reloading $prog:"
    killproc $prog -HUP
    RETVAL=$?
    echo
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    reload)
        reload
        ;;
    condrestart)
        if [ -f /var/lock/subsys/$prog ] ; then
            stop
            # avoid race
            sleep 3
            start
        fi
        ;;
    status)
        status $prog
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload|condrestart|status}"
        RETVAL=1
esac
exit $RETVAL
</code>
The problem is that this service stops running after I close my terminal session with the server.  How do I keep the service running forever in the background?
I do not want to use a screen or nohup because these time out after some time.
Thanks!
Answer: You need to background the process in your init script. In the line that executes the program, use an ampersand <code>&</code> after the process name.
Can you show us the script?
Comment: I have aded the script.  The part that calls my jar is in the start().  Are you saying in this script just add a & to my the process like this:  java -jar /bin/app.jar &.  Or do you mean call the service that runs this command with & like: service app start & ?
Comment: The first approach. Try it.
Comment: @JoeEstes Did it work?
Comment: yes it did.  but it seems from what @toppledwagon pointed out, this is only temporary.  I am exploring setting this up as a daemon.
Answer: You need to write your java app as a daemon.  Even backgrounded processes can die when you close your terminal.
Comment: How should the script be rewritten?
Comment: yes please let us know
Comment: This might help with your Java program: http://commons.apache.org/daemon/


How to restrict user posting a node in certain circumstances

Question: I've created a new user role (country_admin) and I have created a field for these users called user_country. This can be set when registering a user to UK or USA.
I have created a taxonomy 'Countries' and have added UK and USA as terms. I have also created a term reference on my articles so that articles can be assigned to a country.
The functionality I require is that only the user who has UK in the user_country field can post an article with the term set to UK.
I am looking at hook_node_access_records() and hook_node_grants() and have got the functionality working so UK users can only VIEW or UPDATE UK articles using this, however, in hook_node_grants() there doesn't seem to be an "ADD" operation.
How would I do this?
Current hook_node_grants() below
<code>/**
* Implements hook_node_grants().
*/
function curator_scraper_node_grants($account, $op) {
    if ($op == 'view') {
        if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {

            //Let's get the country id the user is linked with
            $uid = $account->uid;
            $user = user_load($uid);
            $country = $user->field_user_country['und'][0];

            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC, // Allow public data
                $country, // this should be users' country link
            );
        }
        else {
            // this is an anonymous user, give them the 'public' grant ID
            // that allows them access to public nodes
            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC,
            );
        }
    }
    if ($op == 'update'){
        //We can grant update permissions here similar to the above
        // but where is $op == "add"???
    }
    return $grants;

}
</code>
Comment: It sounds like you are trying to reinvent the Organic Groups module. Have you reviewed what it does before writing your own code?
Comment: In a nutshell, I would rather write my own code. I currently build WP plugins and am now learning Drupal module development. I'm not building a site - more of a learning exercise.
Comment: OK, then, in that case I would suggest you look at altering the form (to remove options that don't apply because not allowed). IIRC hook_node_grants() only applies to items already in the database, and doesn't affect saving.
Answer: You can use the Node access user reference module:

Gives content access permissions to users for content that references
  the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose
  additional authors, or choose who can view their content, as well as
  being able to display the list of authors or viewers within your
  content, or in views displays.


SquareSpace: Site Title WITH a logo ABOVE

Question: Is there any way I could place an image above my site title on my 'home' page? I would like a logo above the words "Bryson Price".
HOME PAGE example
I would also like my social media icons to be a little bit larger.  Thanks!
Comment: Welcome to Stack Overflow! Please [edit] your question to add meaningful code and a problem description here. Don't just link to the site that needs fixing - otherwise, this question will lose any value to future visitors once the problem is solved. Posting a [Minimal, Complete, Verifiable Example](http://stackoverflow.com/help/mcve) that demonstrates your problem would help you get better answers. For more info, see [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackexchange.com/questions/125997/) Thanks!
Answer: There's actually a lot to this.  First off you need to edit your HTML using code block http://help.squarespace.com/guides/using-the-code-block.  Then you'll need to edit your CSS using your css editor http://help.squarespace.com/guides/using-the-css-editor.  However, if you don't know how to edit html or css you have much more to learn first :)
Comment: Thanks for the response Jake!  Yes, that sounds really intense...theres no way I'll know what to do.  If someone can chime in and help, I will be EXTREMELY thankful
Comment: Sorry that it's not that simple.  You would have to upload your logo and then know the destination of that logo and then be able to add img html above your header redirecting to that logo.  As far as your social media icons are concerned...unfortunately they are icons and are set to a specific size.


xsd validation code problems

Question: I am trying to get the XML file to validate clearly I have some problems with my car file cane any one point me in the right direction on what I need to change?
xml code
<?xml version="1.0"?>

<employees> xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="employees.xsd">

<emp> <first>Bill</first> <last>Johnson</last> </emp> <emp> <first>April</first> <last>Jones</last> </emp> <emp> <first>Chad</first> <last>Becker</last> </emp> <emp> <first>David</first> <last>Jones</last> </emp> </employees>

xsd code
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="employees"> <xs:simpleType> <xs:restriction base="xs:string"> </xs:restriction> </xs:simpleType> </xs:element>

<xs:element name="emp"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="first|last" /> </xs:restriction> </xs:simpleType> </xs:element>

<xs:element name="first">

Answer: The XSD and XML code that you posted both have formatting problems. I'm not sure if they are problems with copying/pasting your code into SO, or problems with the code you're writing. I've taken the snippets you posted and created a schema and matching xml file that are both valid.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.w3schools.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"    targetNamespace="http://www.w3schools.com">
<xs:element name="last" type="xs:string"/>
<xs:element name="first" type="xs:string"/>
<xs:element name="employees">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="emp" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
<xs:element name="emp">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="first"/>
            <xs:element ref="last"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

...and the XML file:
<?xml version="1.0"?>
<employees xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com">
<emp>
    <first>Bill</first>
    <last>Johnson</last>
</emp>
<emp>
    <first>April</first>
    <last>Jones</last>
</emp>
<emp>
    <first>Chad</first>
    <last>Becker</last>
</emp>
<emp>
    <first>David</first>
    <last>Jones</last>
</emp>
</employees>

Comment: Thanks you so much for your help I have one other problem.  I get the below error when trying to validate. Validating "employees.xml" against "Internal DocType Declaration"
Ln 3 Col 2 - The value of attribute "xsi:schemaLocation" associated with an element type "employees" must not contain the '<' character.
1 Error
Comment: @Jon - At the end of the XML file I posted - there was a missing quote mark at the end of the `` tag. I fixed this in an edit.

xsd validation code problems


Show that $\ker f = \ker g \implies h\circ g=f$

Question:
Let $V,W$ be vector spaces over a field $\mathbb{F}$ and let $f,g:V\to W$ be two linear maps. Show that $\ker f= \ker g$ iff there exists a isomorphism $h:W\to W$, such that $h\circ g=f$.

Showing "$\Leftarrow$" can be done very quickly but I haven't been able to figure out the other side so far.

I wold very much appreciate help, thank you very much in advance.
Comment: I would take $W$ and write it as a sum of $f(V)$ and another space $U$, so $W=f(V)\oplus U$ and use the fact that $f(V)\simeq g(V)$ imply that a space $K$ such that $g(V)\oplus K=W$ must have the same dimension of $U$, so you define $h$ on $f(V)$ as the sequence i gave you, and on $W$ take any isomorphism $W\simeq K$. You only need to prove that $h$ defined this way is an iso
Comment: no problem, I had the idea that the question might be wrong. My suggestion is to use the fact that $f(V)\simeq V/\ker f$, so if $\ker f=\ker g\rightarrow f(V)\simeq V/\ker f\simeq V/\ker g\simeq g(V)$
Comment: You could define $h$ by that relation. You'd just have to show that it is well defined and invertible. This is pretty close to defining a map on the quotient by the kernel.
Comment: @Alessandro Thank you, that looks good, do you know if there is a particular theorem that I have to apply now in order to finish the proof?
Comment: @CameronWilliams Thanks, that's also a good idea, I will try it right away and see how that turns out.
Comment: @CameronWilliams The other two approaches work very well but I also find your approach to be a very good technique to know about. My proof that $h$ is well-defined didn't go well, especially showing that for $w\in W$ with $w\not\in g(V)$ the map is well-defined went very bad. Do you know how one can show well-definedness like that?
Answer: Suppose $\ker f=\ker g$. Then, by the rank-nullity theorem, $f$ and $g$ have the same rank. Take a basis $\{v_1,\dots,v_k\}$ of $\ker f=\ker g$ and extend it to a basis $\{v_1,\dots,v_k,v_{k+1},\dots,v_n\}$ of $V$.
Then it's not difficult to show that $\{f(v_{k+1}),\dots,f(v_n)\}$ is a basis for the image of $f$ and $\{g(v_{k+1}),\dots,g(v_n)\}$ is a basis for the image of $g$.
Extend the two sets to bases of $W$ (with the same number of vectors), say
$$
\{f(v_{k+1}),\dots,f(v_n),w_1,\dots,w_r\},\qquad
\{g(v_{k+1}),\dots,g(v_n),w'_1,\dots,w'_r\}
$$
Define $h\colon W\to W$ by
\begin{align}
&h(g(v_i))=f(v_i), && i=k+1,\dots,n\\
&h(w'_i)=w_i && i=1,\dots,r
\end{align}
Then $h$ is an isomorphism and
\begin{align}
h(g(v_i))&=f(v_i)=0 &&i=1,\dots,k \\
h(g(v_i))&=f(v_i)   &&i=k+1,\dots,n
\end{align}
so $h\circ g=f$.
If the spaces are not assumed to be finite dimensional, it's essentially the same, provided you accept existence of bases.


JavaScript: Change text color with a button, each time the button is clicked a different style should show up. Not working

Question:
I'm fairly new to JavaScript. I just made this simple script:
[HTML code]

This text will change style

<button type="button" onclick="changeStyle()">Click me</button>

[JS code]
function changeStyle() {

status = 1;
x = document.GetElementById("text");

if(status==1) {
    x.style.color = 'blue';
    status = 2;
}

if(status==2) {
    x.style.color = 'red';
    status = 3;
}

if(status==3) {
    x.style.color = 'yellow';
    status = 1;
}

}

I want it to change the text to a different style each time the button is clicked. However, this is not working. Could anyone explain a way to do this correctly?
Answer: Try this:
status = 1;
function changeStyle() {
//Note the lowercase first letter.
x = document.getElementById("text");

if(status==1) {
    x.style.background-color = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.background-color = 'red';
    status = 3;
}
else if(status==3) {
    x.style.background-color = 'yellow';
    status = 1;
}

}

You need to use 'else if' because otherwise the browser, after changing the color, immediately moves unto the next if block, and thinks "well that's true now", and then runs that code, all the way to the end of your current code. Using 'else if' tell the browser to ignore the other 'if blocks' once the first one is evaluated.
Hope this helps.
Answer: It is
getElementById("text")

not
GetElementById("text");

Also if i get what are you trying to achieve you should put status = 1; outside the function. Declare it as a global variable so that you cab change it inside each if.
Also you have to use else_if instead of if
DEMO
Comment: Glad to help. You didnt declare what are you trying to achieve so i made i quess. I will edited now that i know
Answer: You need to define variable status=1 outside the function,otherwise each time when button clicking it will set to 1.Also need to change GetElementById("text"); togetElementById("text");
status = 1;
function changeStyle() {

x = document.getElementById("text");

if(status==1) {
    x.style.backgroundColor = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.backgroundColor = 'red';
    status = 3;
}
else if(status==3) {
    x.style.backgroundColor = 'yellow';
    status = 1;
}

}

Answer: Try this code
 <!DOCTYPE html>

      <meta charset="UTF-8">
      <title>
         login page
      </title>

            Select the color for text

            <button onclick="green()" class="green">Green</buttton>
            <button onclick="blue()" class="blue">Blue</buttton>
            <button onclick="red()" class="red">Red</buttton>
            <button onclick="gray()" class="gray">Gray</buttton>
            <button onclick="black()" class="black">Black</buttton>

            Select the color for background

            <button onclick="document.body.style.backgroundColor = 'green';"

          class="green">Green</buttton>
                <button onclick="document.body.style.backgroundColor = 'blue';"
          class="blue">Blue</buttton>
                <button onclick="document.body.style.backgroundColor = 'red';"
          class="red">Red</buttton>
                <button onclick="document.body.style.backgroundColor = 'gray';"
          class="gray">Gray</buttton>
                <button onclick="document.body.style.backgroundColor = 'black';" `
         class="black">Black</buttton>`

            Lorem, ipsum dolor sit amet consectetur adipisicing
            elit. Incidunt ea non accusamus at iure illo quasi deserunt commodi
             magnam, quo optio illum nobis voluptas saepe, dolorem recusandae fuga
           modi ut.

Comment: Please add some explanation to your code, e.g. how it solves the problem


can support vector regression be used in large data?

Question: My aim is to predict a continous variable with a support vector regression. However, my dataset is large. My question is if it is possible to use SVR in this case.
Comment: What makes you doubt SVR in such a situation?
Comment: Because I need to use SVR with non linear kernels such as polynomial kernels.
Answer: It's not going to be ok since the kernel that needs to be present is quadratic in terms of number of samples. Of course, implementation details of the library do also matter. sklearn doc suggests kernel approximation in such large datasets.
Comment: It can be, for example because of the memory consumption (might not even fit-in) and swap-space etc. The computational complexity present in the convex opt problem has also quadratic terms regarding kernel multipliers. You can always early stop a neural net, but in SVM you won't have a choice other than sit and wait.
Comment: Would it be slower than training a neural network?
Answer: SVR with polynomial kernel would probably fail as it is computation and space costly. Check out the datascience stack exchange link here to understand more.
Empirical backing: I tried experimenting with 7008 samples of training data, and I initialized three regression models in scikit-learn:

SVR with a linearly separable hyperplane
SVR with rbf kernel parameters of C(penalty term) = 100, gamma=0.1, epsilon= 0.1
SVR with polynomial kernel with parameters C (penalty term) =100 and 1, gamma = auto, and epsilon = 0.1

The first and the second model were able to predict 1752 instances, but for the model with polynomial, my Google Colab Notebook crashed.


Mock IAuthSession.GetOAuthTokens

Question: I have a Service Stack Service that uses the following code
public MyResponse Get(MyRequest request){
    var authSession = GetSession();
    var tokens = authSession.GetOAuthTokens("somekey");

    var jwt = JwtPayload.Deserialize(tokens.AccessTokenSecret);
    var clientId = jwt.Claims.First(x => x.Type == "client_id").Value;

//...

I am creating a unit test around this service function, but it seems that GetOAuthTokens is a static extension method which cannot be Mocked by Moq (or by any Mocking framework for that example).
This is my current test function
    [Test]
    public void Get_ShouldReturnListOfApplications()
    {

        using (new BasicAppHost(typeof(ApplicationService).Assembly).Init())
        {
            var req = new MockHttpRequest();
            req.Items[SessionFeature.RequestItemsSessionKey] =
                new AuthUserSession
                {
                    UserName = "Mocked",
                    RequestTokenSecret="test",
                    ProviderOAuthAccess = new System.Collections.Generic.List<IAuthTokens>() { MockTokens.Object }
                };

            using (var service = HostContext.ResolveService<ApplicationService>(req))
            {
                service.Client = MockServiceClient.Object;
                service.Settings = MockSettingsProvider.Object;

                var response = service.Get(TestApplicationRequest);

            }
        }
    }

Is there anyway to mock the results of that "GetOAuthTokens" function?
Answer: Here's the implementation of the GetOAuthTokens() extension method:
public static IAuthTokens GetOAuthTokens(this IAuthSession session, string provider)
{
    foreach (var tokens in session.ProviderOAuthAccess)
    {
        if (string.Compare(tokens.Provider, provider, StringComparison.InvariantCultureIgnoreCase) == 0)
            return tokens;
    }
    return null;
}

So it should be returning all tokens in session.ProviderOAuthAccess where the provider == "somekey"

Mock IAuthSession.GetOAuthTokens


Create categorical variable based on time or index range/interval in R

Question: The following dataset contains multiple variables (e.g., x1.AI_mean) values measured per minute (x1.time) during one day. Making it 1440 observations per day. I want to create a categorical variable that gives first 1440 observations ID1, the next 1440 observations (so the second day) ID2 and so forth stored in a new variable. Is this possible by creating an interval range [1;1440] or based on the x1.time variable?
    X  x1.time x1.AI_mean x1.MAD_mean  x1.SD_mean x1.ENMO_t_mean ...
1   1 00:00:00  0.3233516 0.003415065 0.004775937     0.02392688 ...
2   2 00:01:00  0.2841591 0.003029287 0.004059719     0.02370636 ...
3   3 00:02:00  0.2397491 0.002784242 0.003544154     0.02370148 ...
4   4 00:03:00  0.2307666 0.002693856 0.003508254     0.02398960 ...
5   5 00:04:00  0.2444569 0.002704939 0.003618171     0.02434014 ...
6   6 00:05:00  0.2226963 0.002611358 0.003302321     0.02355491 ...
7   7 00:06:00  0.2238880 0.002650730 0.003380582     0.02341979 ...
8   8 00:07:00  0.3994381 0.004197095 0.009734539     0.02383396 ...
9   9 00:08:00  0.9210158 0.010238607 0.017880868     0.02517337 ...
10 10 00:09:00  0.2344564 0.002713301 0.003502785     0.02341302 ...
11 11 00:10:00  0.3451940 0.003814439 0.006974292     0.02412211 ...
......

Thanks in advance :)
Comment: Can you trim your example down to the minimal data we need?
Comment: And how many ID do you have?
Comment: 42 IDs in total
Answer: Try
paste0("ID", ceiling(1:nrow(df) / 1440))

or
paste0("ID", (1:nrow(df)-1) %/% 1440 + 1)


How to customize/ extend ootb components in spartacus

Question: I am new to Spartacus and I am trying to add more elements to the component AddedToCartDialogComponent. Not sure how I can customise/extend this component.
I need to extend the typescript and also the template which is the view for this component.
Comment: What is it that you are trying to achieve?
Comment: Suma -  Did you find anything regarding AddedToCartDialogComponent customization?
Answer: Probably, your best bet is reading through the Spartacus docs about customizing components here. Also try to find your answer in other places in our docs.
If your question was about extending components from Angular perspective, you should probably first read Angular docs


Why is (stiffness/speed of sound-travel of the wood) important for a bow?

Question: High-end violin bows have been made for centuries out of permanbouc (a now rare and endangered brasilian wood) or equivalent woods and now synthetic material. Permambouc wood is praised for is stiffness and therefore the high speed of sound/vibrations along it.
Why is it so important?
What does it bring to the sound and to the capabilities of control of the bow ?
Answer: When you draw a bow across the strings, you are imparting energy into the combined physical system of the violin and the bow.  What you want is for as much of that energy as possible to be transmitted to the strings, which transmit it to the bridge, which transmit it into the violin and then out to the air.
Like anything else, a bow isn't 100% efficient; inevitably, it will absorb some of the energy and reflect some of the energy.  The stiffer the bow, the less energy it absorbs and the more it reflects back into the string.  So a stiffer bow is preferable because more of your energy goes into producing sound.
This is the same principle as with graphite tennis rackets and baseball bats.  The stiffer the material, the more the energy is transmitted where you want it.
Comment: @feetwet - yep.  In addition to tone color, another reason for not wanting a bow that's too stiff is that attacks become harder: if a bow doesn't give, then it's hard to start a tone without scratching.
Comment: That is true up to a point.  But it's not the whole story, because otherwise no one would use a wooden bow but rather one of graphite, or steel, or glass, all of which exist and all of which make a more brilliant, some would say harsher, sound than wood, because they have less hysteresis or internal friction and thus damp the higher frequencies less.  So it's a matter of what kind of sound you want too.
Comment: Agree with @ScottWallace: This is definitely not the whole story.  Last time I was shopping for a violin bow I ended up buying the most rigid, or "stiff," one I tested, but I am not a remarkable violinist.  For amusement I tried some bows priced in the high-five-figure range and found them all astonishingly flexible – I might characterize them as "flaccid" or "weak."  I was told that those are the ones preferred by many virtuoso/professional violinists.


React + Rails with Redux Persist Gate

Question: I am new to everything as specially to react_on_rails and I am trying to figure out how to use redux-persist with my project so that when I changing the page, I am not losing any redux store. I have figure out the redux setup but I cannot get Redux Persist to work right and it still fails to Uncaught Error: Could not find store registered with name 'rootStore'. Registered store names include [  ]. Maybe you forgot to register the store? I just wondering if anyone can help with it to fix a problem. I tried to go over the documentation several times and did really helped me with the option that I have.
my application view
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

<%= notice %>
<%= alert %>
    <%= redux_store('rootStore', props: {}) %>
    <%= react_component('ProductDetailPage', props: {product: @product.id}) %>
    <%=  yield %>
    <%= redux_store_hydration_data %>

My entry point to register ProductDetailPage
import ReactOnRails from 'react-on-rails';
import ProductDetailPage from '../pages/ProductDetailPage';
import { registerRootStore } from '../utils/ReactOnRails';
ReactOnRails.setOptions({
  traceTurbolinks: true,
});
ReactOnRails.register({ProductDetailPage});
registerRootStore();

utils/ReactOnRails
import { configureStore } from '../store/rootStore';
export default function getReactOnRails() {
  window.ReactOnRails = window.ReactOnRails || require('react-on-rails').default;
  return window.ReactOnRails;
}

export const registerRootStore = function () {
  if (getReactOnRails().storeGenerators().has('rootStore')) {
    return;
  }
  getReactOnRails().registerStore({rootStore: configureStore });
};

store/rootStore
import { createStore } from 'redux';
import reducerIndex from '../reducers/index';
import { persistReducer} from 'redux-persist';

let _store;
let _persistor;
export const configureStore = function (props) {
  if (_store) return _store;

  const initialState = (props) ? {...props} : {};
  _store = createStore(reducerIndex, initialState);
  _persistor = persistReducer(_store);

  return _store;
};

export const getPersistor = function () {
  return _persistor;
};

reducers/index
import { combineReducers } from 'redux';
import { persistReducer} from 'redux-persist';
import cartReducer from './cartReducer';

const rootReducer = combineReducers({
  cart: cartReducer,
});

const reducer = persistReducer(
  {
    key: 'root',
    storage: require('localforage'),
  },
  rootReducer
);

export default reducer;

And the last file which handles all other components that will be later injected with.
// @flow

import * as React from 'react';
import { Provider } from 'react-redux';
import getReactOnRails from '../utils/ReactOnRails';
import { PersistGate } from 'redux-persist/es/integration/react';
import { getPersistor } from '../store/rootStore';

type Props = {
  children: React.Node,
  loading?: React.Node,
}
const rootStore = getReactOnRails.getStore('rootStore'); // another error that happening for me, it says that getStore is not a function.

export default class ProviderGate extends React.Component<Props> {
  render() {
    const persistor = getPersistor();

    if (!persistor) return this.props.children;

    return <Provider store={rootStore}>
      <PersistGate persistor={persistor} loading={this.props.loading}>
        {this.props.children}
      </PersistGate>
    </Provider>;
  }
}

Answer: After a couple hours of debuging I actually find why my persistStore was not working. Here the things I did in my code.
store/rootStore
_persistor = persistReducer(_store); => _persistor = persistStore(_store);

Main Entry file
ReactOnRails.register({ProductDetailPage});
registerRootStore();

Should be
registerRootStore();
getReactOnRails().register({ProductDetailPage});

and finally a component that responds to PersistGate and redux Provider it should be rendered in the component, not outside of the class and it should be like this
const rootStore = getReactOnRails.getStore('rootStore');

React + Rails with Redux Persist Gate


How to include spaces in mount points for automount?

Question: On macOS I am attempting to set up an automount for a mount point with spaces.
/etc/auto_master contains:
#
# Automounter master map
#
+auto_master            # Use directory service
/net                    -hosts          -nobrowse,hidefromfinder,nosuid
/home                   auto_home       -nobrowse,hidefromfinder
/Network/Servers        -fstab
/-                      -static
/-                      auto_afp        -nosuid

and /etc/auto_afp contains:
'/mnt/mount point'    -fstype=afp    'afp://username:passwd@hostname/share%20name`

When I execute: sudo automount -vc, I get the error noted:
automount: dir '/mnt/mount point' must start with '/'
automount: /net updated
automount: /home updated
automount: /Network/Servers updated
automount: no unmounts

It has also failed if I use %20 without quoting (in that case it includes %20 in the mount point name).
How does one properly add spaces in a mount point?
Comment: It doesn't start with a `/`.
Comment: @MichaelHampton okay, I understand now, I edited this as the mount point and share both have a ' ' (space) in them and so I had quoted that in an attempt to include it.  When I use `%20` it doesn't seem to work either. I will edit my question to reflect this...
Comment: Try `0/040` instead of `%20` for a space. This works on Linux, but unsure if this works on Mac OS as it's BSD-based. If it works, I'll post it as an answer.
Comment: @CraigWatson unfortunately that created the path: `/mnt/mount0/040point` with `mount0` being a child in `/mnt` and `040Machine` being a child of `mount0`.
Comment: @ylluminate apologies, try `\040` instead
Comment: @ylluminate just to be clear, you're trying these suggestions _without_ quotes?
Comment: @CraigWatson yes.  and I tried `\040` as well.
Answer: You can escape with a backslash '\' character.
    /mnt/mount\ point    -fstype=afp    'afp://username:passwd@hostname/share_name'
How about "/mnt/mount point" or /mnt/"mount point"?
Another option is to use a name without a space.
Further research led me to this page about mounting folders another way.
The key here is that in Posix systems, the mount table is space delimited.  So if your path includes spaces, they have to be escaped.  Author of that page thinks \040 may be the escape character in OSX.  If so, the syntax would be /mnt/mount\040point.  He also noted that the solution was only tested in Leopard.  Also, Craig Watson was pointing you here as well in the comments above.
Comment: Unfortunately that did not work. It only create `/mnt/mount\\ `.
Comment: Now I suspect you're only guessing.
Comment: @MichaelHampton I want to say the escape sequence worked in Linux.  I may be thinking of mount and /etc/fstab instead of automount.  The ask osx exchange site has one or more questions like this, unanswered.  But yes, my subsequent attempts are guesses.
Comment: @ylluminate My suggestion was based on Linux, where '\' is not an allowed character in path names because the \ is an escape character.
Comment: Yes, \ is an escape character.  The rest of your statement is false.  You can put a \ in a filename quite easily if you escape it (you already know the escape character, it would be '\\' to include one).
Comment: A simple test proves you're right.  Another difference that sets Posix apart.


Pyspark transfrom list of array to list of strings

Question: Given a dataframe with a list of arrays
Schema
|-- items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- quantity: string (nullable = true)

+-------------------------------+
|items                          |
+-------------------------------+
|[[A, 1], [B, 1], [C, 2]]       |
---------------------------------

How do i get a string:
+-------------------------------+
|items                          |
+-------------------------------+
|A, 1, B, 1, C, 2               |
---------------------------------

Tried:
df.withColumn('item_str', concat_ws(" ", col("items"))).select("item_str").show(truncate = False)

Error:
: org.apache.spark.sql.AnalysisException: cannot resolve 'concat_ws(' ', `items`)' due to data type mismatch: argument 2 requires (array<string> or string) type, however, '`items`' is of array<struct<name:string,quantity:string>> type.;;

Comment: The error tells you that you must first transform items array into a array and then call concat on it
Comment: how can i convert the sub element (quantity) to string?
Comment: try using `pyspark.sql.functions.flatten`
Comment: @Bitswazsky i tried flatten: `df.withColumn("items_flat",flatten("items")).show(False)` and got error: `The argument should be an array of arrays, but 'items' is of array> type.;;`
Answer: You can achive that using a combination of transform and array_join build-in functions:
from pyspark.sql.functions import expr

df.withColumn("items", expr("array_join(transform(items, \
                                i -> concat_ws(',', i.name, i.quantity)), ',')"))

We use transform to iterate among items and transform each of them into a string of name,quantity. Then we use array_join to concatenate all the items, returned by transform, seperated by comma.
Answer: Explode might be useful here
import org.apache.spark.sql.functions._
df.select(explode("items")).select("col.*")


Debugging Spring Code in STS (Eclipse)

Question: I am used to working in Netbeans, where I can start a project in debug mode, alter some code, and hit the "Apply Code changes" button.
at the moment I am working in Eclipse (Spring Tools Suite) and I would like to do something similar.
I found This article which suggests that Eclipse does it automagically if Project -> Build automatically is set, but that is not my experience. (regarding Spring Boot projects, which is what I am currently working with)
Any help is much appreciated.
Comment: Are your break points working? Does the debugger find your source files when stopping at a break point? Could be a build path setup problem.
Comment: Break points are working fine. it's the ability to modify code running in the JVM I am missing - ie when you are debugging, and you inspect your code to find an error, fix he item in code, apply the settings and step through to find the next (no stopping the debugging session needed)
Answer: In Eclipse and in combination with the Spring Boot Devtools, you have two options to deal with this situation.
One if the ability of the JVM to swap-in code changes while you are debugging without loosing the state of the application. This works in Eclipse out-of-the-box when you have "Build Automatically" enabled and do a code change after you hit a breakpoint. Usually the JVM drops the current execution frame and continues the execution at the beginning of the current method invocation.
BUT: This works for minor code changes only (changing the implementation of a method, for example). Most changes to the source code can't be hot-swapped by the JVM. If the IDE tries to do that, you will get an error message that this is not possible with the question whether you want to restart the JVM, stop it, or continue without the code changes. This is a limitation of the JVM, not directly of the IDE.
The other option is to go with the Spring Boot Devtools. Once they are on the classpath of the app and you change a class on the classpath of the project (which happens automatically if you have the "Build Automatically" enabled), the Boot Devtools will detect those changes and re-start the boot app automatically. This doesn't cause the JVM to be restarted, just the boot app part of it. Therefore it is much faster than starting the full JVM. BUT: you are loosing the state of the application. From the debugging perspective, it is the same as if you would restart the app, it is just faster. But you can't do what while sitting on a breakpoint and expecting the app to continue with the same stack frame.
There are other tools like JRebel that allow for more sophisticated code changes to be hot-swapped into the running app and there are also plugins for Eclipse to use JRebel, for example, but that is another story.

Debugging Spring Code in STS (Eclipse)


API PLATFORM CUSTUM OPERATION Provide Value for Data Argument

Question: Good Afternoon.
I'm using Symfony 4.1.1 and APIPlatorm to create an API.
I'm trying to create a custum Post Operation to Create a user in DataBase with a crypted Password.
I've follow the procedure describe in https://api-platform.com/docs/core/operations
But i've to following Error:

Controller \"App\Controller\UtilisateurSpecial\" requires that you
  provide a value for the \"$data\" argument. Either the argument is
  nullable and no null value has been provided, no default value has
  been provided or because there is a non optional argument after this
  one.

That is my configuration. Can You please Help me to solve this problem?
src\Entity\Utilisateur.php
 <?php

   namespace App\Entity;

   use ApiPlatform\Core\Annotation\ApiResource;
   use Doctrine\ORM\Mapping as ORM;
   use Symfony\Component\Security\Core\User\UserInterface;
   use Symfony\Component\Validator\Constraints as Assert;
   use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

   /**
    * @ApiResource(
    *     collectionOperations={
    *     "post",
    *     "special"={
    *         "method"="POST",
    *         "path"="/utilisateurs/special.{_format}",
    *          "requirements"={
    *              "_format": "\s+"
    *           },
    *         "controller"=App\Controller\UtilisateurSpecial::class,
    *         "defaults"={"_api_receive"=false}
    *     }
    * })
    * @ORM\Entity(repositoryClass="App\Repository\UtilisateurRepository")
    * @UniqueEntity(fields="email", message="Cet email est déjà enregistré en base.")
    * @UniqueEntity(fields="username", message="Cet identifiant est déjà enregistré en base")
    *
    */
   class Utilisateur implements UserInterface, \Serializable
   {
       /**
        * @ORM\Column(type="integer")
        * @ORM\Id
        * @ORM\GeneratedValue(strategy="AUTO")
        */
       private $id;

       /**
        * @ORM\Column(type="string", length=25, unique=true)
        * @Assert\NotBlank()
        * @Assert\Length(max=25)
        */
       private $username;

       /**
        * @ORM\Column(type="string")
        */
       private $password;

       /**
        * @ORM\Column(type="string", length=60, unique=true)
        * @Assert\NotBlank()
        * @Assert\Length(max=60)
        * @Assert\Email()
        */
       private $email;

       /**
        * @ORM\Column(name="is_active", type="boolean")
        */
       private $isActive;

        /**
        * @var array
        * @ORM\Column(type="array")
        */
       private $roles;

       public function __construct()
       {
           $this->isActive = true;
           $this->roles = ['ROLE_USER'];
       }

       /*
        * Get id
        */
       public function getId()
       {
           return $this->id;
       }

       public function getUsername()
       {
           return $this->username;
       }

       public function setUsername($username)
       {
           $this->username = $username;
           return $this;
       }

       public function getPassword()
       {
           return $this->password;
       }

       public function setPassword($password)
       {
           $this->password = $password;
           return $this;
       }

       /*
        * Get email
        */
       public function getEmail()
       {
           return $this->email;
       }

       /*
        * Set email
        */
       public function setEmail($email)
       {
           $this->email = $email;
           return $this;
       }

       /*
        * Get isActive
        */
       public function getIsActive()
       {
           return $this->isActive;
       }

       /*
        * Set isActive
        */
       public function setIsActive($isActive)
       {
           $this->isActive = $isActive;
           return $this;
       }

        // modifier la méthode getRoles
        public function getRoles()
        {
            return $this->roles;
        }

        public function setRoles(array $roles)
        {
            if (!in_array('ROLE_USER', $roles))
            {
                $roles[] = 'ROLE_USER';
            }
            foreach ($roles as $role)
            {
                if(substr($role, 0, 5) !== 'ROLE_') {
                    throw new InvalidArgumentException("Chaque rôle doit commencer par 'ROLE_'");
                }
            }
            $this->roles = $roles;
            return $this;
        }

       public function getSalt()
       {
           // pas besoin de salt puisque nous allons utiliser bcrypt
           // attention si vous utilisez une méthode d'encodage différente !
           // il faudra décommenter les lignes concernant le salt, créer la propriété correspondante, et renvoyer sa valeur dans cette méthode
           return null;
       }

       public function eraseCredentials()
       {
       }

       /** @see \Serializable::serialize() */
       public function serialize()
       {
           return serialize(array(
               $this->id,
               $this->username,
               $this->password,
               $this->isActive,
               // voir remarques sur salt plus haut
               // $this->salt,
           ));
       }

       /** @see \Serializable::unserialize() */
       public function unserialize($serialized)
       {
           list (
               $this->id,
               $this->username,
               $this->password,
               $this->isActive,
               // voir remarques sur salt plus haut
               // $this->salt
           ) = unserialize($serialized);
       }

   }

src/controller/UtilisateurSpecial
<?php
namespace App\Controller;

use App\Entity\Utilisateur;
use App\Service\UtilisateurService;

class UtilisateurSpecial
{
   private $utilisateurService;

   public function __construct(UtilisateurService $utilisateurService)
   {
       $this->utilisateurService = $utilisateurService;
   }

   public function __invoke( $data): Utilisateur
   {
       $this->utilisateurService->addUtilisateur($data->getUsername, $data->getPassword);

       return $data;
   }
}

Can you please help me to solve my problem?
Comment: What do you mean with "API PLATFORM CUSTUM OPERATION"? Please reread [ask], then rephrase that a bit. Chances are you intendet those as keywords, for which you should use tags. Make sure you read the tags' descriptions though before applying them!
Answer: Let's take a look at your config:
  /**
    * @ApiResource(
    *     collectionOperations={
    *     "post",
    *     "special"={
    *         "method"="POST",
    *         "path"="/utilisateurs/special.{_format}",
    *          "requirements"={
    *              "_format": "\s+"
    *           },
    *         "controller"=App\Controller\UtilisateurSpecial::class,
    *         "defaults"={"_api_receive"=false}
    *     }
    * })
    * @ORM\Entity(repositoryClass="App\Repository\UtilisateurRepository")
    * @UniqueEntity(fields="email", message="Cet email est déjà enregistré en base.")
    * @UniqueEntity(fields="username", message="Cet identifiant est déjà enregistré en base")
    *
    */

By default, API Platform would pass the resource to your custom operation, in your case the object of class Utilisateur. Since it's a POST operation, it'll be an Utilisateur instance created based on your input in the request body.
See what API Platform documentation says on this:

If you want to bypass the automatic retrieval of the entity, you can
  set the parameter _api_receive to false.  This way, it will skip
  the Read, Deserialize and Validate listeners (see the event
  system for more information).

If you set _api_receive = true there's nothing API Platform can pass to your custom operation. You've disabled automatic deserialization. So, you should not have a $data argument on __invoke() at all in this case.
Instead, you should define your __invoke() as:
public function __invoke(Request $request) {
}

This way you get access to the current Request object for anything you might need it.
Answer: If $data is an user object... You should do three things.
First, import the class controller (use) on the entity.
Second, remove
"defaults"={"_api_receive"=false}

from the api resource annotation in the user entity.
Third, $data should be:
public function __invoke(User $data): Utilisateur {
}


Android Sorting Json data

Question: I am new. I'm trying to sorting the data that I get from json parse,but nothing work.
Not even an error.
I try How to Sort JSON Array from JSON Objects in Android?
I don't know what's wrong with my code, because there's no error.
But there's a warning "Implicitly using the default locale is common source of bugs: Use toLowerCase(Locale) instead" on here
return (lhs.getString("item_name").toLowerCase().compareTo(rhs.getString("item_name").toLowerCase()));

Is there anyone can help me to solve this problem?
Here's my java code
    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                ArrayList<JSONObject> array = new ArrayList<JSONObject>();
                JSONArray jsonArray = new JSONArray();

                // looping through All Contacts
                for (int i = 0; i < foods.length(); i++) {
                    try {
                    JSONObject c = foods.getJSONObject(i);

                    if(c.getString("category_id").equals("1")) {
                        // Adding to array. Only items with category_id = 1 will be sorted.
                        array.add(foods.getJSONObject(i));  // This line is important

                        String item_id = c.getString(TAG_ITEM_ID);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ITEM_ID, item_id);

                        // adding contact to contact list
                        foodslist.add(contact);

                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
                Collections.sort(array, new Comparator<JSONObject>() {

                    @Override
                    public int compare(JSONObject lhs, JSONObject rhs) {
                        // TODO Auto-generated method stub

                        try {
                            return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return 0;
                        }
                    }
                });
            }
          }
        else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

And here's my Json data
[{"id":"201","category_id":"0","category_name":null,"item_name":"","description":"","address":"","area":""}

Thanks before.
Comment: That is just a warning. You can use @suppresswarnings to avoid it if you feel uncomfortable, provided your app is not meant for multi languages
Answer: That is just a warning.

You can use @SuppressWarnings to avoid it if you feel uncomfortable, provided your app is not meant for multi languages
OR
You can use : toLowerCase(Locale.getDefault()); to avoid this warning. Make sure to import import java.util.Locale;

EDIT
Hope below code will help you:
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
    try {
     JSONObject c = jsonArray.getJSONObject(i);
    if(c.getString("category_id").equals("1")
    {
         // Adding to array. Only items with category_id = 1 will be sorted.
         array.add(jsonArray.getJSONObject(i));  // This line is important

         // All other stuff here.....
          String item_id = c.getString(TAG_ITEM_ID);
                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ITEM_ID, item_id);
                        // adding contact to contact list
                        foodslist.add(contact);
    }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Collections.sort(array, new Comparator<JSONObject>() {

    @Override
    public int compare(JSONObject lhs, JSONObject rhs) {
        // TODO Auto-generated method stub

        try {
            return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
});

EDIT AGAIN
if (jsonStr != null) {
                try {
                    ArrayList<JSONObject> array = new ArrayList<JSONObject>();
                    JSONArray jsonArray = new JSONArray();

                    // looping through All Contacts
                    for (int i = 0; i < foods.length(); i++)
                    {
                        try {
                        JSONObject c = foods.getJSONObject(i);

                        if(c.getString("category_id").equals("1")) {
                            // Adding to array. Only items with category_id = 1 will be sorted.
                            array.add(foods.getJSONObject(i));  // This line is important

                            String item_id = c.getString(TAG_ITEM_ID);

                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            contact.put(TAG_ITEM_ID, item_id);

                            // adding contact to contact list
                            foodslist.add(contact);
                        } // End of if c.getstring

                        } // End of inner try
                        catch (JSONException e) {
                            e.printStackTrace();
                        } // End of inner catch
                     } // End of for loop
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                    Collections.sort(array, new Comparator<JSONObject>() {

                        @Override
                        public int compare(JSONObject lhs, JSONObject rhs) {
                            // TODO Auto-generated method stub

                            try {
                                return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                return 0;
                            }
                        }
                    });

            } // End  of if jsonstr
            else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;

Comment: thanks, but do you know why the sorting is not working?
Comment: Its because your code is not the same as the source you are trying with. You have declared `array`, but not assigned any value to it anywhere in your code.
Comment: In the original post, note the line `array.add(jsonArray.getJSONObject(i));` This is necessary for sorting. In your code, this line is missing.
Comment: i'm trying to do what you said, but there's an error "array cannot be resolved to a variable.
Comment: Sorry, I forget to add add try { on my code :D
But the ask me to add "finally" to complete blockstatements.
Comment: What finally? The usual construct for finally is `try - catch - finally`. But in your case, I don't think it is necessary! Finally related docs are here :
Comment: You can check it on my question.I already edit my code.
The error is on "}" right before the last else
Comment: @Matthew: Refer edit again section. The braces are not closed properly. I have commented against each close brace for your understanding.
Comment: Ok, I try the code that you gave. and there's a new error "array cannot be resolved" in this line                     Collections.sort(array, new Comparator() {. I think because its not in if statement
Comment: i am trying to add catch before else statement.
}
                catch (JSONException e)
                {
                    e.printStackTrace();
                }

            }

            else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

And I got error "Unreachable catch block for JSONException.
It suggest to remove it, but when I remove it, I got an error on log cat.
Comment: Did you try the code i have provided in EDIT AGAIN section? The open and close braces are correct in that section. If you want, try changing the `JSONException e` to only `Exception e`
Comment: Yes, i already try it and I got two errors.
First on this line                  Collections.sort(array, new Comparator() {. It said "array cannot be resolved to a variable".
Second on else line. "Sintax error, { expected"
Comment: @Matthew: I get it, the collections.sort should be inside the if part. I have re-edited my answer in the edit again part. Check now.
Comment: I don't get it why, Its looks perfect but still there is an error about that array variable.
Its gone if I put the collection.sort inside the outer try part. But it'll show another error on JSONException.
Comment: @Matthew: You seem to have a very basic issue. Note: Any if should have a corresponding else and any try should have a corresponding catch. Please go thru basic java documentations to sort this error!
Comment: Once solved, accept as answer for the time spent and answer provided!
Answer: Instead of using
.toLowerCase().

change it like this
.toLowerCase(Locale.getDefault())

It will help.
and also check for Null in variables and >0 check for arrays.

Android Sorting Json data


I have to show no proper intermediate fields exist between $Z_2$ and $GF(2^3)$

Question: I have to show no proper intermediate fields
exist between $Z_2$ and its overfield $GF(2^3)$, Can any one help?
Comment: Have you tried computing the degree of the extension?
Comment: Hint: 3 is prime.
Answer: It is a theorem on finite fields that for any prime $p$, and any positive natural numbers,
$$\mathbf F_{p^{\scriptstyle r}}\subset \mathbf F_{p^{\scriptstyle s}}\iff r\mid s.$$