Spring security AntMatcher is not working

Question: This is the way I have configured spring security, in controller I'm getting ROLE_ANONYMOUS as authority. Looks like security is not intercepting the request and checking for JWT.
How to configure antmatcher..?
<code>@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter
{

   @Override
   public void configure(HttpSecurity http) throws Exception
   {
      http.authorizeRequests()
            .antMatchers("/actuator/**", "/api-docs/**").permitAll()
            .antMatchers("/notes/**").hasAnyAuthority("USER").anyRequest().authenticated();
   }

}
</code>
Below is my controller code
<code>@RestController
@RequestMapping("/notes")
public class NoteController
{
   @Autowired
   private IUserService userService;

   @Autowired
   private INoteService noteService;

   static MessageSourceAccessor messageAccesser =  ApplicationConfiguration.getMessageAccessor();

   private final Logger logger = LoggerFactory.getLogger(NoteController.class);

   @RequestMapping(value = "/addnote", method = RequestMethod.POST)
   public ResponseEntity<Response> addNote(@RequestBody NoteDto note, HttpSession session)
   {
      Authentication ath = SecurityContextHolder.getContext().getAuthentication();
      int userId = 5;
      logger.debug("Adding note :-", note);
      Response response = new Response();
      try {
         User user = userService.getUserById(userId);
         if (user == null) {
            response.setStatus(111);
            response.setResponseMessage(ApplicationConfiguration.getMessageAccessor().getMessage("111"));
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
         }
         noteService.saveNote(note, user);

      } catch (Exception e) {
         logger.error(e.getMessage());
         FNException fn = new FNException(101, new Object[] { "Adding Note - " + e.getMessage() }, e);
         return new ResponseEntity<>(fn.getErrorResponse(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
      response.setStatus(200);
      response.setResponseMessage(messageAccesser.getMessage("200"));
      return new ResponseEntity<>(response, HttpStatus.OK);
   }
</code>
UPDATE
Looks like antmatchers are not working. Here is the log when I hit the api.
<code>DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.u.matcher.OrRequestMatcher.matches line: 72 - No matches found
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 5 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 6 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 7 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 8 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.a.AnonymousAuthenticationFilter.doFilter line: 100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 9 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.s.SessionManagementFilter.doFilter line: 124 - Requested session ID DE97FB345788E4AB200B922552573A31 is invalid.
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 10 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 310 - /notes/addnote reached end of additional filter chain; proceeding with original chain
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.web.servlet.DispatcherServlet.doService line: 869 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/notes/addnote]
</code>
Comment: Do you have any other Spring Security configuration with a lower order?  The best way to solve your problem is, that you add Spring Security logs with `DEBUG` level to your question. It will show the reason.
Comment: Looks like antmatcher is not working. I have added the log in question. Please do check.
Comment: Unfortunatly you have to provide more logs. It isn't clear which filter chain is executed. Spring Boot has a lot of filter chains (static resources, authorization server, resource server, Spring Boot default, Actuator, ...)
Comment: Is there a reason you specifically need to be using `ResourceServerConfigurerAdapter` over `WebSecurityConfigurerAdapter`?
Answer: Try WebSecurityConfigurerAdapter, you can refer to my demo below. I have customed some filters for validation, If you don't need just remove it.
<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterBefore(new CaptchaAuthenticationFilter("/login", "/login?error2"), UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
                .antMatchers("/").hasRole("USER")
                .antMatchers("/index").hasRole("USER")
                .antMatchers("/message/*").hasRole("USER")
                .anyRequest().permitAll()
                .and().formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/login?error1").permitAll()
                .and().rememberMe().tokenValiditySeconds(60*60*7).key("message")
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider authenticationProvider=new CustomAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        return authenticationProvider;
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return new CustomUserDetailService();
    }

}
</code>
Answer: What version of spring-boot and spring-security are you using?
The @EnableResourceServer annotation adds a filter of type OAuth2AuthenticationProcessingFilter automatically to the Spring Security filter chain.
So to your "extends ResourceServerConfigurerAdapter" be applyed before the OAuth2AuthenticationProcessingFilter, you'll need to annotate it with @Order (-1)
<code>@Configuration
@EnableResourceServer
@Order(-1)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
[...]
</code>
Comment: I'm using spring boot 1.5.9.RELEASE. And it's still not working with @Order(-1)


How is the LRU deleted in this LRUCache implementation?

Question: I'm going over the optimal Leetcode solution for LRU Cache LeetCode Medium question.  The original problem can be found here: https://leetcode.com/problems/lru-cache/description/
I'm confused by a specific portion of the solution code.
class Node:
    def __init__(self, key, val):
        self.key, self.val = key, val
        self.prev = self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.cap = capacity
        self.cache = {}  # map key to node

        self.left, self.right = Node(0, 0), Node(0, 0)
        self.left.next, self.right.prev = self.right, self.left

    # remove node from list
    def remove(self, node):
        prev, nxt = node.prev, node.next
        prev.next, nxt.prev = nxt, prev

    # insert node at right
    def insert(self, node):
        prev, nxt = self.right.prev, self.right
        prev.next = nxt.prev = node
        node.next, node.prev = nxt, prev

    def get(self, key: int) -> int:
        if key in self.cache:
            self.remove(self.cache[key])
            self.insert(self.cache[key])
            return self.cache[key].val
        return -1

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            self.remove(self.cache[key])
        self.cache[key] = Node(key, value)
        self.insert(self.cache[key])

        if len(self.cache) > self.cap:
            # remove from the list and delete the LRU from hashmap
            **lru = self.left.next
            self.remove(lru)**
            del self.cache[lru.key]

Why am I deleting the lru?  In other words why is self.left.next represent the least recently used key?
To illustrate this let's say your capacity param is 2.  And you currently have two nodes comprising your doubly linked list:  [1,1] and [2,2]
Now you put a 3rd node [3,3] so the linked list looks like this: [2,2] [1,1] [3,3].  But you have exceeded the capacity constraint of two so you need to remove the LRU (least recently used) node which is [2,2].  For lru = self.left.next ... why does it equal [2,2] and not [1,1]?
Comment: Let me turn that question around - *why* do you believe that the result would be [1,1]?  That's the middle element of the linked list at the moment, you cannot possibly reach it via one step from the dummy end nodes.
Answer: code is simple, it's just a double linked list with self.head and self.tail  (two pointer)define initially , and node info is stored in dictionary
 Node(0, 0)) <->(DO node insertion delete here) <-> (Node(0,0)
  ^                                                     ^
  head                                                tail

all deletion and updation happenining in above space between these two node.
in simple terms:
for addition -> element is added at tail (as second last element)
for deletion -> element after head is deleted.
addition and deletion is same as what happen at double linked list.No need to explain.
accessing of node is done via dictionary by mapping key to node.
work flow:
when you read a node having a key:

if key present -> delete the key from dictionary and node
correspoinding to it from LruCache and add that node at tail
part(second last)
if key not present -> add the key and node created at last(tail part). check if size of dict exceed the self.capacity or
not. if yes then remove the first element (After head) from lrucache
double linked list.

in your example [[2,2], [1,1]]
here is double linked list in diagram
start ->
head (node(0, 0))  <-> tail (node(0,0)) # lru cache created
[2,2] added put operation
head (node(0, 0))  <-> Node(2,2) <-> tail (node(0,0))
[1,1] added put operation
head (node(0, 0))  <-> Node(2,2) <-> Node(1, 1) <-> tail (node(0,0))
[3,3] added put operation
head (node(0, 0))  <-> Node(2,2) <-> Node(1, 1) <->  Node(3,3) <->tail  <->(node(0,0))
here size increase. since Node(2,2) used once and no get operation happen on it , it will be removed and cache become
head (node(0, 0)) <-> Node(1, 1) <->  Node(3,3) <->tail(node(0,0))
now suppose [1,3] put operation, having key present happen then this is how list will be changed
head (node(0, 0))   <-> Node(3,3) <->  Node(1,3) <->tail (node(0,0))
you can see for each operation if element is accessed ie get used and is found then element is added at right and remove from his present location
in case of put it is added at right, if capacity increases then first element after head is removed.
Hope this help
Comment: thank you!  really appreciate your detailed response


Weird border while playing fullscreen

Question: I have the following problem while playing some (Bethesda) games, if i set the game to fullscreen (non-windowed).
In the upper right corner of the screen, it looks like there is the regular " windows-window" border quickly blinking. Its's always the upper right corner  (the three buttons your normally see in a window plus some extra empty space) and it annoys me to no end. It looks as if the game is trying to switch between fullscreen and windowed mode. I have only encountered the problem with bethesda games so far. I find it very hard to explain what exactly happens, but I hope some of you have encountered the same and know a solution

The card I am using is a Sapphire hd 7850
As far as I know, I am running the latest drivers for this card.
I do have some Rainmeter widgets on my desktop
Comment: press alt + enter keys may fix it.
Comment: can you be more specific? what is your video card? are your drivers updated? Skyrim is known to glitch in some drivers. Also do you have some gadget on screen that tells you your CPU,RAM,GPU,etc usage?
Comment: I got that too with Skyrim and other Bethesda Games, I know what you mean. But I don't think that is fixable. One could try to set a different windows style for the game window by sending some WinAPI messages, but that would require further examination and I don't have Skyrim installed atm.
Comment: you could also try alt - tab out and back in to your game. This fixed the problem a few times for me.
Answer: Yea...this happens when you possibly play the game on the lowest resolution it can be easily solved be pressing alt + tab, or windows key + tab, then it take you off the game screen to your home destop.Once there click on the skyrim icon to go to the game again,of this doesn't work alt+enter will surely solve it.
Comment: Well, I play on 1920x1080..
Comment: What's your full resolution
Comment: i believe i have a 1920x1080 monitor, or i might be misunderstanding the question
Comment: Ok....when you launch skyrim,with the laucher, what resolution do you pick,to start the game
Comment: i pick 1920x1080
Comment: Try to increase a little but of everything on the launcher
Comment: If you pc can handle it
Comment: Im already running everything on the highest setting possible
Comment: has this been going on since you bought the game or after recent updates
Comment: Ever since i have bought the game ( skyrim AND fallout )
Comment: but it doesn't affect your game play?
Comment: Well it is mighty annoying. It doesnt make it impossible for me to play, but it significantly diminishes my will to even start the game. I might even get a seizure due to the flickering corner  :(
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8966/discussion-between-ian-escobar-and-gutanoth)

Weird border while playing fullscreen


Installing Ubuntu 17 but it goes to live session all time

Question: Installing Ubuntu 17.04 on Lenovo Y520. From bootable USB. It gives me 4 option. I'm selecting 2nd option to install ubuntu. (I have already partitioned the HDD)
It prompts to select language. But continue button is not highlighted. Then within 4-5 seconds it change the screen and take me to the live session user.
Am I missing something?
Comment: Try booting into a Live USB first. Ubuntu distros should have an installer icon on the desktop.
Comment: When I try this, it says System problem detected. Crash. I think it may be because i'm installing on intel machine while ubuntu 17.04 is only for amd64 available. However live cd is working fine
Comment: As per other posts it seems that amd64 can be installed on intel 64. So now I don't know what is the issue
Comment: This is already reported as bug [here](https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1637899?comments=all)
Answer: I have finally installed it. First I have changed the BIOS to ACPI mode. Then installed 16.04.2 which failed due to i/o error. But it had done the partition and all initial work. Then I tried the same steps with 17.04 and it got installed.
Comment: I guess the reason I was getting I/O error because I was using memory card instead of USB.


Is it possible to fetch Records from CoreStore using offset/paging?

Question: I want to implement paging kind of ui using UITableview so that once user is at last record while scrolling, I want to fetch next set of records from Local db using CoreStore.
Does CoreStore support this kind of feature while querying?
Answer: That depends on your persistent store, because fetchLimit is simply ignored when using SQLiteStore. That is a CoreData restriction (or bug, depends how you want to call it).
In CoreStore you can use tweak on the querychainbuilder, like
<code>CoreStore.fetchAll(From<YourEntity>().tweak({ $0.fetchLimit = 50 }))
</code>
That modifies the NSFetchRequest that offers fetchLimit and fetchOffset.
So to solve the CoreData restriction you would need to do something else, such as pre-defining your paging using a page attribute and extend your where clause whenever your endless loading triggers.


A more elegant solution to this linear algebra problem?

Question: Consider the following problem.

Let $V$ be a $\mathbb{K}$-vector space of dimension $n$ and $U \subset V$ a subspace of dimension $n - 1$. Prove the following propositions:

If $v \not\in U$ then $V = U \oplus \langle v\rangle $, where $\langle v \rangle$ denotes the span of $v$.

The way I set out to show this is the following. Assume $v \not\in U$. Then the $n$th component of $v$ is non-null. Then $cv \not\in U$ for every non-null $c \in \mathbb{K}$. Then $U \cap \langle v\rangle = \{0\}$.
We must now only show $U + \langle v\rangle = V$. Every vector $u \in U$ may be expressed as $(x_1, \ldots, x_{n-1}, 0)$; this is, as an $n$-dimensional vector with the $n$th component null. Now observe $v = (y_1, \ldots, y_{n-1}, y_n)$. Then
\begin{align*}
    U + \langle v\rangle  &= \begin{pmatrix}
        u_1 \\ \vdots \\ u_{n-1} \\ 0
    \end{pmatrix} + \begin{pmatrix}
    v_1 \\ \vdots \\ v_{n-1} \\ v_n
\end{pmatrix} \\ &= \begin{pmatrix}
u_1 + v_1 \\ \vdots \\ u_{n-1} + v_{n-1} \\ v_n
\end{pmatrix} \\
            &= (u_1 + v_1)b_1 + \ldots + (u_{n-1}+ v_{n-1})b_{n-1} + v_nb_n
.\end{align*}
where $b_i$ is the $i$th vector in the basis of $V$. Since $u_i + v_i$ might be any element in $\mathbb{K}$ (for we are taking $u_i, v_i$ to be arbitrary scalars in $\mathbb{K}$ and any scalar can be represented as the sum of other two), then we have found $U + \langle v\rangle  = V$. $\blacksquare$
Fair enough. However, in attempting my proof I had to appeal to the interpretation of $U$ as the subspace of $n$th dimensional vectors $v \in V$ whose $n$th component is $0$. This allowed me to compute the sum $U + \langle v\rangle$ explicitly, as shown above. From the sum it readily follows that the resulting set of vectors was only $V$.
However, I find it rather unpleasant to perform this explicit sum. My intuition tells me that there must be some formal property that allows me to show $U + \langle v\rangle = V$ without actually observing the result of $(u_1, ..., u_{n-1}, 0) + (y_1, ..., y_{n-1}, y_n)$ and so on. What would be a more abstract or formal way to address this problem?
Comment: "Then the $n$th component of $v$ is nonzero". First, vector don't necessarily have components. Second, if they do, it's with respect to some fixed basis, which you haven't provided. And third, there's no reason why the $n$th component of $v$ should be nonzero, unless you are very careful about the basis you have chosen.
Comment: I'd let $\{\,b_1,b_2,\dots,b_{n-1}\,\}$ be a basis for $U$, then show $\{\,b_1,b_2,\dots,b_{n-1},v\,\}$ is a linearly independent set, hence, a basis for $V$.
Comment: I've approved a recent edit suggestion to replace each `` with `\langle v \rangle`, but it won't take effect until someone else approves it. Any takers?
Comment: @GerryMyerson that was my first thought as well since it uses the definition of dimension directly.
Comment: Notice: you prove a result, but you *solve* a problem.
Answer: Just use dimensions: For two subvector spaces $U,W \subset V$, we have
$$ \mathrm{dim}(U+V)=\mathrm{dim}(U)+\mathrm{dim}(W)-\mathrm{dim}(U\cap W).$$
Setting $W:=\langle v \rangle,$ we can easily see that $W\cap U= 0$ and therefore
$$\dim(U+\langle v)\rangle= \mathrm{dim}(U)+\mathrm{dim}(\langle v \rangle)=n-1+1=n. $$
Therefore we must have $U+\langle v \rangle =U  \oplus \langle v \rangle =V $.
The takeaway should be that when dealing with finite-dimensional vector spaces, the dimension is an important tool, which often can simplify arguments.
Comment: This is quite clear, thanks! To be sure, the conclusion follows from the fact that $U + W \subseteq V$ and that for any subset $T$ of $V$, $\dim(T) = \dim(V) \implies T = V$?
Comment: @lafinur Yes, every subspace (not just any set) $T\subset V$, which satisfies $\mathrm{dim}(T)=\mathrm{dim}(V)$ must be equal to $V$.
Answer: Your proof is vague and most likely wrong (maybe it can be fix). You're assigning component to vectors without defining a basis for $V$. If $\{b_1,…,b_n\}$ is arbitrary basis of $V$. Then $u\in U$ may not be expressed as $(x_1,…,x_{n-1},0)$.
Proof: Since $v\notin U$, we have $U\cap \text{span}(v)=\{0\}$. So $U, \text{span}(v)$ are independent. Let $B'=\{\alpha_1,…,\alpha_{n-1}\}$ be basis of $U$. We show $B=\{\alpha_1,…,\alpha_{n-1},v\}$ is basis of $V$. If $c_1 \alpha_1+…+c_{n-1}\alpha_{n-1}+c_nv=0$, for some $c_i\in F$. Then $c_1 \alpha_1+…+c_{n-1}\alpha_{n-1}=-c_nv\in U\cap \text{span}(v)$. Since $v\neq 0$, we have $c_n=0$. By linear independence of $B'$, $c_i=0$, $\forall i\in J_{n-1}$. So $B$ is independent. Since $|B|=n=\dim (V)$, we have $B$ is basis of $V$. In particular, $\text{span}(B)=V$. Thus $V=U+\text{span}(v)$. Hence $V=U\oplus \text{span}(v)$.


Is it possible to divide a file in blocks and transfer using a library like OkHttp or Volley?

Question: Wanted to know what would be the most efficient way of doing this. The reason I want to divide the file is so that I dont send the same blocks of data again if the network becomes unavailable while the transfer is going on. This is especially usefule for bigger files.
Comment: Use multipart request approach.
Comment: Yes, but that isn't supported by Volley or OkHttp. Wanted to know if it was supported by default. There are extension libraries though which help you use that. Also, I wanted to control the blocks I have sent and the ones I haven't. Is that possible with this approach?
Comment: @dhuma1981 And I also want to control the chunk size of each block.
Comment: where have you reached with this ?
Answer: What you want is an HTTP Multipart Request, which is provided by the Apache HTTP Library, by Retrofit and by Ion. Volley does not let you perform such a request currently.
Comment: Do these libraries let you control the size of chunks dynamically?
Comment: The part size and network availability are managed internally in these libraries using optimum algorithms.
Comment: The reason I asked this was I want to be able to control the chunk size for what I'm trying to accomplish.
Comment: Yes I understood that. What I have seen is that the chunk size is normally controlled internally, so you don't really need to optimize it yourself. If you still need to do this for some other reason, I shall do some research on this and get back to you.
Comment: Would "http.socket.buffer-size" in the DefaultHttpClient class help me achieve that?
Comment: I am not sure that `SOCKET_BUFFER_SIZE` is the same as file part size, but kudos for locating that so quickly!


Progress bar is not displayed when using addFooterView

Question: I try to display a progress bar at the bottom of a list view.
When I scroll to the bottom of the list, more items are load and the progress bar is displayed, the progress bar is hidden when loading is done.
But at the moment I am stuck at displaying the progress bar (not caring about displaying or hiding it yet as they are easy to handle). I applied many solutions on StackOverflow but they just didn't work.
This is how I add the footer view in my list fragment:
public class ItemListFragment extends ListFragment {
    protected View footerView;

    public ItemListFragment() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.footerView = li.inflate(R.layout.progress_bar, null);
        getListView().addFooterView(this.footerView);
    }
}

My progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

My fragment_item_list.xml is the default file created by Android Studio (I post just in case you need it)
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

If you have a solution please post your answer. Thanks!
Answer: Well, I solved the problem by switching to use Fragment instead of ListFragment.
My fragment:
public class TestFragment extends Fragment {
    static final String[] numbers = new String[] { "one", "two", "three",
            "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
            "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
            "seventeen", "eighteen", "nineteen", "twenty", "twenty one",
            "twenty two" };

    public TestFragment() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.test_list_view, container, false);

        ListView listView = (ListView) rootView.findViewById(R.id.test_list_view);

        View footer = View.inflate(getActivity().getApplicationContext(), R.layout.test_footer, null);
        listView.addFooterView(footer);

        ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, numbers);

        listView.setAdapter(adapter);

        return rootView;
    }
}

test_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/test_list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

test_footer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <ProgressBar
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

</LinearLayout>


How to group air void air and cave air

Question: execute unless air ~ ~ ~ doesn't work when you're in the void or in a cave.
Is there something like #air that joins all air blocks together, like #wool?
Comment: the void doesnt have blocks. That's why its the void! Maybe check if they're below 0?
Answer: Unfortunately, there doesn't seem to an #air tag available in vanilla Minecraft.
One possible workaround is to simply duplicate the condition:
execute unless block ~ ~ ~ minecraft:air unless block ~ ~ ~ minecraft:cave_air run <...>

Note that you do not need to explicitly test for void_air as of Minecraft 1.16, as execute unless block will always fail in the void.
In theory, it should also be possible to create a predicate in a datapack that tests for the relevant criteria.
Answer: You can add your own tags to blocks.
If you know datapacks you can add your own tag in .minecraft/saves/(worldname)/datapacks/(datapackname)/data/(datapacksubname)/tags/blocks (stuff between brackets isn't specific text). You have to create a .json file named whatever you want the name of the tag to be. In the file you write the following:
{
 "values":[
  "air",
  "cave_air",
  "void_air"
 ]
}

That should do it, then you can use #(tagname) in game.
Even if you don't know datapacks, you can just follow the file order I gave you, for example:
.minecraft/saves/(worldname)/datapacks/airgrouping/data/airgrouping/tags/blocks/air.json

How to group air void air and cave air


Should generated SPIR-V code be optimized?

Question: I'm currently considering porting some code that I have from OpenGL/GLSL to Vulkan/SPIR-V, and part of that code generates GLSL at runtime, so I'll have to generate SPIR-V instead. What I'm wondering is how I should relate to optimizations in the generated SPIR-V.
Particularly, I can't really find any information on what kind of expectations I should have on the driver's compiler. Should I expect it to do aggressive optimizations on its own and thus try to keep the SPIR-V code clean and keep as much "original intent" as possible in it for the compiler to look at? Or should I expect it to do fairly simplistic code generation, and try to do as aggressive optimization as possible when generating SPIR-V?
Just perhaps for particular examples, which of these kinds of things should I do when generating SPIR-V?

Eliminate redundant stores-then-loads of local variables?
Loop unrolling or peeling / function inlining?
Constant propagation / common subexpression elimination?
Keep as much as possible in SSA form instead of loads and stores to local variables?

My very naïve expectation is that the compiler will want to adapt its optimization passes to the particulars of the hardware and that I should therefore try and keep my SPIR-V code clean and high-level, where such things as loop unrolling would destroy information and keep the driver from deciding on its own unrolling, but I'm really just guessing without any real information.
Comment: @NicolBolas: Well, that is why I was hoping for an answer from someone who known what the implementations actually do.
Comment: "*so I'll have to generate SPIR-V instead*" Is there some problem with using the existing GLSL-to-SPIR-V compiler?
Comment: @NicolBolas: Yes, the fact that I'm generating the code at runtime, so I wouldn't want to rely on external tools.
Comment: Are you unable to include the compiler in your code at runtime? Because it comes in a library form too.
Comment: @NicolBolas: For one thing, my code is in Java, and I don't think there's an existing JNI wrapper, at least. Also, I do have all the information available to generate SPIR-V directly, so since it's possible to keep the code clean of external dependencies, I don't see why not.
Comment: I would suggest looking at the quality of the SPIR-V code generated by glslang. If it does lots of complex constant expression folding and such, dead-code elimination, loop unrolling, and so forth, then your code should do likewise. If it doesn't, then you probably don't need to either.
Comment: @NicolBolas: Actually, one of the reasons I asked this question was because I found a number of places on the web where people complained that glslang wasn't doing enough optimization, but I couldn't tell whether glslang is simply underdeveloped, or if these people were looking for optimizations that it shouldn't do.
Comment: "Shouldn't" is ultimately going to be based on the quality of the implementation *consuming* SPIR-V, so on that score your question is essentially unanswerable. Since lots of people use glslang, it stands to reason that implementers will build their SPIR-V optimizing code to handle the kinds of stuff it emits.
Answer: You can generally expect the runtime compiler (in the driver, consumes SPIR-V) to do a lot of standard optimizations. In many implementations it's the same backend as the one in the GL driver, and does most of the same optimizations. But the process of parsing the SPIR-V and translating it to the driver's internal representation is going to be faster if there's not a lot of unnecessary junk in there. So if you're writing your own generator, it's worth putting a bit of effort into generating "clean" SPIR-V.
You might take a look at shaderc, which is meant to be an easy-to-integrate library that uses glslang for GLSL-to-SPIR-V translation, and also can run spirv-opt to do some of the optimizations you named. As spirv-opt gets additional optimizations (under active development) shaderc will pick those up.


How can I show a clear label on this start page without pushing the content vertically?

Question: I'm working on a web app which shows a bunch of charts for how the sales are going. This screenshot is from my startpage.

The label I've marked with a red arrow is a label indicating who the sales target charts are for and it's taking too much vertical space, pushing everything down more than I would like, but I have no idea how to show a clear label anywhere else
Any ideas?
Comment: too much vertical space? I barely see it and wouldn't notice it without the red arrow! If you're convinced this really is *too much vertical space* (for any reason), just test with users. As I see it, I'd recommend to increase it to at least double of what it is now
Answer: I'd even increase the vertical space for your label. It needs a bit more breathing room. If you do this, you can move your filter options (or are they action buttons?) to the top. This will clean up your UI, position labels and buttons in a more logical position and also shorten the overall height of your application. See the images below.

Current situation (left)
Improvement as said above (right)
Comment: very nice indeed :)
Comment: I like this option a lot.
Answer: Great question, Weblurk. There are an infinite number of solutions if this app allows custom coding. But if you can only slide blocks around, then perhaps a UX solution should be less design change and more text change. If you truly want that headline gone, then simply reword the card titles to include the word "office."

Yes, it may be redundant to repeat the word "office" four times, but technically, that is what you get if you wish to reverse engineer the purpose of a headline.
Would you like to see custom coding design options (UI) or does this UX shuffling of words satisfy your need?
Comment: I ended up using this approach. A bit reduntant perhaps but it makes it really clear what each box contains AND it solves the vertical space issue. Thanks!
Answer: In the mockup above how about moving the label to the left and then moving the action button at the bottom (To Do, More Business Opportunities and Latest Actions) to the top right. Now your vertical space has been utilised more effectively and you can use the label space as a heading indicator?
I'm not entirely sure what the action buttons below are for but that would be one solution if its possible.
Answer: Move the text to the red block, and change it to:
"Office Sales Targets"
For the hard of thinking:
Comment: If they move the text to the red block, the whole section moves up. I know the difference between a comment and an answer.
Comment: could you elaborate? Right now this is more of a comment than an answer.


Codeigniter single same query with limit and without limit for pagination database with single query?

Question: Codeigniter single query with limit and without limit?
I am try to pagination database with single query: I need total number of records with where condition and without limit, data get with limit with same query.

$this->db->select( '*' );
if ( ! empty( $id ) ) {
    $this->db->where( "id", $id );
}
if ( ! empty( $to ) ) {
    $this->db->where( "to", $to );
}
if ( $is_deleted !="" ) {
    $this->db->where( "is_deleted", $is_deleted );
}
if ( ! empty( $from ) ) {
    $this->db->where( "from", $from );
}
if ( ! empty( $priority ) ) {
    $this->db->where( "priority", $priority );
}
$this->db->order_by( $orderby, $order );
$total_records = $this->db->get( $this->Table )->num_rows();
if ( $page < 1 ) {
    $page = 1;
}
if ( $pagesize < 1 ) {
    $pagesize = 1;
}
$offset = ( $page - 1 ) * $pagesize;
$rows = $this->db->get( $this->Table, $pagesize, $offset )->result_array();

Answer: The problem is you execute the querybuilder method get twice without defining anything in the 2nd query
in your case i would prefer the SQL_CALC_FOUND_ROWS option
$this->db->select( 'SQL_CALC_FOUND_ROWS *' );

$arrCheckEmptyFields = ['id' = > $id, 'to' => $to, 'from' => $from, 'priority' => $priority, 'is_deleted' => $is_deleted];

foreach($arrCheckEmptyFields AS $key => $val)
{
    if (!empty($val))
    {
        $this->db->where($key, $val);
    }
}

if ( $page < 1 )
{
    $page = 1;
}
if ( $pagesize < 1 )
{
    $pagesize = 1;
}

$offset = ( $page - 1 ) * $pagesize;

$row = $this->db
    ->order_by( $orderby, $order)
    ->limit($pagesize, $offset)
    ->get($this->Table)
    ->result_array();

$total_records = intval($this->db->query('SELECT FOUND_ROWS() AS `Count`')->row(0)->Count);

Answer: function get_data($params = "" ){
      $this->db->start_cache();
                $this->db->select( '*' );
                if ( ! empty( $id ) ) {
                    $this->db->where( "id", $id );
                }
                if ( ! empty( $to ) ) {
                    $this->db->where( "to", $to );
                }
                if ( $is_deleted !="" ) {
                    $this->db->where( "is_deleted", $is_deleted );
                }
                if ( ! empty( $from ) ) {
                    $this->db->where( "from", $from );
                }
                if ( ! empty( $priority ) ) {
                    $this->db->where( "priority", $priority );
                }

                $this->db->stop_cache();
            $this->db->order_by( $orderby, $order );
                        $total_records = $this->db->count_all_results( $this->Table );
                if ( $page < 1 ) {
                    $page = 1;
                }
                if ( $pagesize < 1 ) {
                    $pagesize = 1;
                }
                $offset = ( $page - 1 ) * $pagesize;
                $rows = $this->db->get( $this->Table, $pagesize, $offset )->result_array();
        $this->db->flush_cache();
    return $rows;
}

Answer: In CodeIgniter 3.16 I need the total number products & the page=1 products
$this->db->start_cache();

$this->db->select("p.*");
$this->db->from('product p');

$this->db->where("p.cat_id", "12");
$this->db->group_by("p.id");

$this->db->stop_cache();

# Get total number of products
# It will show products except limit
$total_product = $this->db->count_all_results();

# show only 5 products
# It will show products including LIMIT
$this->db->limit(5, 0);

$query = $this->db->get();
$this->db->flush_cache();

$result       = $query->result_array();
$result_count = $query->num_rows();

CodeIgniter Document


Issue with getting batch script to print keeps given a error about set was unexpected at this time

Question: Okay I am trying to get the script to print the day of the week and after the test would like to get the script to go more advanced once i get it working correctly
<code>@echo off
SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    if "!count!" GTR "0" GOTO next
    set dow=%%D
    IF %dow%==1 set dowday=Monday
    IF %dow%==2 set dowday=Tuesday
    IF %dow%==3 set dowday=Wednesday
    IF %dow%==4 set dowday=Thursday
    IF %dow%==5 set dowday=Friday
    IF %dow%==6 set dowday=Saturday
    IF %dow%==7 set dowday=Sunday
    SET /a count+=1
)
:next
echo %dowday%
pause
</code>
Comment: In addition to the delayed expansion thing, Sundays will have %dow%==0, not 7.
Answer: You enable delayed expansion, but then fail to use it. You need delayed expansion because you are setting a variable within a loop, and then trying to reference the value of the variable within the same loop. Normal expansion occurs when the statement (or block) is parsed (before the loop is iterated). Delayed expansion gives you the value when the statement is executed during the iteration.
<code>@echo off
SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    if "!count!" GTR "0" GOTO next
    set dow=%%D
    IF !dow!==0 set dowday=Sunday
    IF !dow!==1 set dowday=Monday
    IF !dow!==2 set dowday=Tuesday
    IF !dow!==3 set dowday=Wednesday
    IF !dow!==4 set dowday=Thursday
    IF !dow!==5 set dowday=Friday
    IF !dow!==6 set dowday=Saturday
    SET /a count+=1
)
:next
echo %dowday%
pause
</code>
In your case, you could avoid delayed expansion by using %%D in the IF statements, and unconditionally GOTO :next at the end of the loop since count will always be greater than 0.
<code>@echo off
SETLOCAL
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    set dow=%%D
    IF %%D==0 set dowday=Sunday
    IF %%D==1 set dowday=Monday
    IF %%D==2 set dowday=Tuesday
    IF %%D==3 set dowday=Wednesday
    IF %%D==4 set dowday=Thursday
    IF %%D==5 set dowday=Friday
    IF %%D==6 set dowday=Saturday
    SET /a count+=1
    goto next
)
:next
echo %dowday%
pause
</code>
Comment: thanks this fixed my issue with the log rotation script i was working on for my DAYZ Epoch server to have a daily log backup
Answer: thanks for the help now the final script is completed
<code>@echo off
:: Based off of Server Launch Script by r4z0r49
:: Script Modified and fixed by Sykotix - http://dayz.sykotix.com
:: Day of the week Added By Raziel23x - http://adkgamers.com
::
:: Usage: dayzsrv-log-rotater.bat servername
:: Example 1 - Will update using default profile: dayzsrv-log-rotater.bat
:: Example 2 - Will update using profile for US6: dayzsrv-log-rotater.bat US6

:::::::::::::: CONFIG ::::::::::::::::::

:: Set your Arma2AO Base installation directory. LEAVE OFF THE ENDING \
set arma2srvpath=C:\Program Files (x86)\Steam\SteamApps\common\Arma 2 Operation Arrowhead

:: Set your Default server profile name. This is the name of the directory that stores your server.cfg
:: This will be used in the case that you don't launch this script without the server param.
:: Example: cfgdayz, US6, Chicago13, ect
:: DEFAULTPROFILE
set srvname=instance_11_chernarus

:: Delete Original log files after they have been rotated? This keeps your logs more organized and saves space.
:: This will not work unless the server is stopped first. This option works best set to 1 when using FireDaemon's Pre/Post Service tab
set deloriglogs=1

::::::::::: ADVANCED CONFIG ::::::::::::
:: Don't touch anything below this point unless you know what your doing.

:: Setting Server Profile to Use
IF "%1"=="" (
set servername=%srvname%
) else (
set servername=%1
)

TITLE  DayZ %servername% Server Log Rotater

:: Set Debug Mode
set debug=0
:: Set Debug Timeout in seconds
set dbsecs=10

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::  STOP EDITING ::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: Display Debug output
if %debug% == 1 (
echo Server Name = %servername%
echo ArmaII Server Path = "%arma2srvpath%"
timeout %dbsecs%
)

:: Set Time and Date
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%_%time:~6,2%
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%_%time:~6,2%
::Make Date Stamp
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO Todays Date and time (%date%)(%time%) / %dtStamp%
if %debug% == 1 (
timeout %dbsecs%
)
:: Set Day of the Week --Raziel23x
SETLOCAL
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (

    IF %%D==0 set weekday=Sunday
    IF %%D==1 set weekday=Monday
    IF %%D==2 set weekday=Tuesday
    IF %%D==3 set weekday=Wednesday
    IF %%D==4 set weekday=Thursday
    IF %%D==5 set weekday=Friday
    IF %%D==6 set weekday=Saturday
)

echo (%weekday%) (%date%) (%time%) Starting Log Rotation.

:: Make the Rotated Log Directorys
if exist "%arma2srvpath%\%servername%\RotatedLogs" goto maketsdir
mkdir "%arma2srvpath%\%servername%\RotatedLogs"
:maketsdir
if exist "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%" goto makebedir
mkdir "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%"
:makebedir
if exist "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye" goto rotatelogs
mkdir "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye"

:rotatelogs
:: Starting Log Rotation. If there are any other logs, just follow the format below, and make sure to NOT touch any of the varibles.
copy "%arma2srvpath%\%servername%\arma2oaserver.RPT" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\arma2oaserver.RPT"
copy "%arma2srvpath%\%servername%\arma2oaserver.mdmp" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\arma2oaserver.mdmp"
copy "%arma2srvpath%\%servername%\arma2oaserver.bidmp" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\arma2oaserver.bidmp"
copy "%arma2srvpath%\%servername%\server_log.txt" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\server_log.txt"
copy "%arma2srvpath%\%servername%\HiveExt.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\HiveExt.log"
copy "%arma2srvpath%\%servername%\BattlEye\scripts.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\scripts.log"
copy "%arma2srvpath%\%servername%\BattlEye\createvehicle.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\createvehicle.log"
copy "%arma2srvpath%\%servername%\BattlEye\mpeventhandler.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\mpeventhandler.log"
copy "%arma2srvpath%\%servername%\BattlEye\publicvariable.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\publicvariable.log"
copy "%arma2srvpath%\%servername%\BattlEye\publicvariableval.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\publicvariableval.log"
copy "%arma2srvpath%\%servername%\BattlEye\remoteexec.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\remoteexec.log"
copy "%arma2srvpath%\%servername%\BattlEye\setdamage.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\setdamage.log"
copy "%arma2srvpath%\%servername%\BattlEye\setpos.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\setpos.log"
copy "%arma2srvpath%\%servername%\BattlEye\setvariable.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\setvariable.log"
copy "%arma2srvpath%\%servername%\BattlEye\addmagazinecargo.log" "%arma2srvpath%\%servername%\RotatedLogs\%weekday%\%dtStamp%\BattlEye\addmagazinecargo.log"

echo (%date%) (%time%) Logs are backed up now...
echo (%date%) (%time%) Removing original log files.
del /Q /F "%arma2srvpath%\%servername%\arma2oaserver.RPT"
del /Q /F "%arma2srvpath%\%servername%\arma2oaserver.mdmp"
del /Q /F "%arma2srvpath%\%servername%\arma2oaserver.bidmp"
del /Q /F "%arma2srvpath%\%servername%\server_console.log"
del /Q /F "%arma2srvpath%\%servername%\runtime.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\scripts.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\createvehicle.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\mpeventhandler.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\publicvariable.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\publicvariableval.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\remoteexec.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\setdamage.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\setpos.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\setvariable.log"
del /Q /F "%arma2srvpath%\%servername%\BattlEye\addmagazinecargo.log"

if %debug% == 1 (
timeout %dbsecs%
)

:: We're done here.
exit
</code>
Comment: Using the date and time variables is unreliable as they change from `region to region` and also by `user preferences`.  As you are using `WMIC` then it is better to also use that for the date and time information. See here: http://stackoverflow.com/search?q=%22The+first+four+lines+of+this+code%22+user%3Afoxidrive


Introducing your pro-tem moderators

Question: Throughout the beta, we need members from the site whose focus is to engage the community, both in community-building issues and site management. That's why we select a few members from each community to act as temporary, provisional Moderators. You can read about the program here: Moderators Pro Tempore.
I am pleased to announce, at long last, that these members have stepped up and generously volunteered their time to help us assure that each community's issues are properly addressed:

We want to make this site a huge success, and these members are great examples of exactly the type of people we need to make this site succeed. Please welcome them for the hard work and time they contribute.
Did I overlook anyone?
Almost certainly. There are members who are actively involved and very deserving of recognition. My failure to account for everyone this early on is in no way a slight against them. Ideally, Moderators are elected by the community and that's why we eventually hold elections.
Most of all, be respectful and understanding of the Moderators Pro Tem. Members of your community are volunteering their time and learning on the job. It's a learning experience for everyone.
Comment: Thank you, and congrats to Adarain and Sparksbet!
Comment: @curiousdannii congrats to you too :) Let's make this a good place!
Comment: I'm a bit late, but congratulations to you guys too! I'm excited to mod with y'all.
Answer: Gratulojn! Eglerio! SaHoy'!
It's great to have you all as moderators here. You've already shown your passion for this site and its topic; all that remains to say is good luck in your modly endeavours. And since you're all new to Stack Exchange moderation, do come and join the Teachers' Lounge if you ever need assistance :-)

Introducing your pro-tem moderators


Is there a way to load an excel file in openpyxl ignoring the data type?

Question: I have an excel file that has the value 20220831 on cell C2, and the cell format is set as date.
When I try to load the file with openpyxl I get this warning:
C:\Users\joaquim.MASCARELL\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\worksheet\_reader.py:211: UserWarning: Cell C2 is marked as a date but the serial value 20220831 is outside the limits for dates. The cell will be treated as an error.
  warn(msg)

And trying to get the cell value results in "#VALUE!":
wb = xl.load_workbook(file)
sheet = wb["Sheet1"]
print(sheet["C2"].value)

>>#VALUE!

I would like to get the integer value "20220831".
Is there any parameter that I can pass in order to ignore the type mark and simply return the value that is stored in the xml?
Comment: is the correct datatype a date? I think ```.text``` gets the string representation of a value in excel, but it's probably worth trying
Comment: The correct datatime is not date. The Cell object doesn't have a text atribute.
Comment: It looks like `#VALUE!` is the value in the cell.
Comment: Check [here](https://foss.heptapod.net/openpyxl/openpyxl/-/issues/1670). Looks like it was a bug and fixed by Charlie Clark an year back. Probably upgrade to latest version of openpyxl
Comment: My openpyxl version is 3.0.10 (the last version, in theory).
Answer: a trick way, just delete this row
value = "#VALUE!"

in C:\Users\joaquim.MASCARELL\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\worksheet_reader.py
                    except (OverflowError, ValueError):
                        msg = f"""Cell {coordinate} is marked as a date but the serial value {value} is outside the limits for dates. The cell will be treated as an error."""
                        warn(msg)
                        data_type = "e"
                        #value = "#VALUE!"


Textblock not retrieving new style on property changed

Question: I am using Silverlight 5 and trying to do some style binding to a viewmodel. I'm running into an issue with my binding not setting the new value when the property changes. But this only happens with the default style, if I use a key then it works correctly. Here are some examples.
This works:

This Doesn't work:

In the first example when the PropertyChanged event is called it rebinds the foreground color to the correct value. In the second example it doesn't rebind.
Any Ideas?
Answer: As I can remember, Style is always declared with x:Key property, and if you want to set some style as default for TargetType, use BasedOn property. Like...


How do I import modules in the Factor interpreter?

Question: I'm following the Sam's decipher tutorial. When he does 8 group, on my computer Factor gripes that it doesn't know the group function.
( scratchpad ) "01101001001000000110011001110101011000110110101101100101011001000010000001111001011011110111010101110010001000000110110101101111011011010000110100001010011000010110111001100100001000000110111001101111011101110010000001100110011011110111001000100000011110010110111101110101"

--- Data stack:
"0110100100100000011001100111010101100011011010110110010101100..."
( scratchpad ) 8 group
1: 8 group
          ^
No word named "group" found in current vocabulary search path

The following restarts are available:

:1      Use the grouping vocabulary
:2      Use the unix.ffi vocabulary
:3      Use the unix.groups vocabulary
4 :res  Defer word in current vocabulary

Type :help for debugging help.

Apparently group is located in the grouping module, but I don't know how to import the module in the interpreter (something like +m module in Haskell's GHCi).
Answer: In the interpreter, type USE: grouping ; to add a single vocabulary to the search path, or USING: a b c ; to add a list of vocabularies.
Documentation: USE: USING:.


What's the best approach for header/footer in responsive web design?

Question: I'm an IA doing a responsive site, as part of a much larger scale e-commerce site. Our pages are the only responsive parts of the overall site, so 90% of our site will not yet be responsive. Part of this is a test case, the other part is groundwork for a much larger effort.
My question has to do with header/footer.
We also have a mobile-optimized site, done by a 3rd party provider. Being that the overwhelming majority of our header/footer links will go to non-responsive and non-mobile-optimized, does it make sense to filter those out of our responsive site for mobile view?
What I've done thus far is devised a header/footer IA that includes only links to our mobile site. This way, the user stays in the mobile context and does not get bounced to a page that does not offer a good UX on the mobile.
Is this the right way to approach it?
Just not sure if the right decision is to include the same exact header/footer content on the mobile as we have for desktop/tablet.
Answer: I've read evidence for both sides:
NO, you should not create a separate mobile navigation.
Research by Sujan Shrestha (see page 189) showed that omitting part of the desktop navigation on mobile can be disorienting to users who are familiar with the desktop site, reducing their task completion times, so you're right to think twice before changing the navigation for mobile.
Also, by hiding some of the pages from mobile, you're implicitly assuming a separate mobile context.  Roughly 70% of mobile device access occurs in a stationary context (Heimonen found 67% in 2009; Church & Oliver found 71.4% in 2011, p. 71).  People in these stationary contexts (and potentially even mobile users in mobile contexts) will have the same information needs as desktop users, so hiding the relevant part of your navigation will make it difficult for them to find the information they seek.

YES, you should create a separate mobile navigation
The authors of "Improving Web Search on Small Screen Devices" found that users of mobile devices accessing desktop sites often failed to complete tasks on desktop-optimized websites:

"the main reason for failure, and the associated large task timings, was the great difficulties they had in navigating the site selected from the search result.  Most of their wasted time and effort was spent in becoming
  increasingly lost within the small window" (488)

Unless the content is essential, by providing links to it, you'll only cause your users frustration as they struggle to use an oversized interface in an undersized screen.  By removing that part of the navigation, you'll improve the experience for all users who are just browsing casually and don't really need to complete tasks on those pages.
A caveat: some other researchers found that (at least in the context of mobile apps) browsing accounted for only 10-12% of the total usage (p. 186), which means that users will often be using the internet with a purpose in mind.  Even if that purpose is just finding information or checking a status, you will prevent them from doing so if you hide the pages on mobile.  For this reason, if I were to pick one side personally, I would choose not to hide the desktop pages from the mobile navigation.  Being frustrated by bad access is not as bad as being frustrated by having no access at all.

NEITHER (the unrealistic ideal)
Ideally, the navigation for the two should eventually be the same because ideally the content should be the same, with both desktop and mobile sites pulling their content from the same database, but just formatting it differently.  In her book Content Strategy for Mobile, Karen McGrane shows how cross-platform content publishing should work.  It sounds like your company's forked their content for the time being, so this probably isn't a viable solution at the moment, but it's something to keep in mind for the future.

A WARNING. If you do choose to hide pages from the navigation...
...then consider a mobile navigation pitfall that McGrane warns about:
Mobile users entering your site from Google could get redirected to the mobile homepage if the page doesn't exist on mobile, then have to go to the desktop version of the homepage, and then have to search laboriously through the desktop version's internal navigation to find the page they're looking for.
If a user can find a page on Google, they should be able to access it on mobile, even if it's only the desktop version of the site.  If you decide to omit the content from the header and footer, be sure that you do not also redirect search results from Google that would have gone to those pages.

One last note...McGrane also recommends looking at competitor's sites to help determine your mobile strategy:

 how do they handle global navigation? Does it include the same
  major categories as the desktop site, or just a subset? Are
  navigation categories prioritized differently for mobile? How does
  the user access the global navigation from the homepage and other site
  pages?

...so doing a competitive audit might help you to answer your question.
Comment: Thanks to both of you for your answers and response. It's going to be a difficult decision as I have a very unique situation where user will potentially navigate back and forth between the mobile site and our full HTML site.

Have a strategy meeting next week to discuss this issue, and your comments certainly help me prep for that.
Answer: I think there are at least three areas to look at:

UX - while desktop and mobile versions are different due to UX and technology aspects, these should be kept similar as much as it does not conflict with user experience. Limiting access to features that are simply not accessible on mobile and thus gracefully degrading the experience is understandable and it's in general a proper direction. Regarding footer links especially, I would choose a middle way: upon tapping the footer offsite link, you could display an alert modal saying that he is now leaving the mobile optimized version and the further experience can be severely affected due to no mobile friendliness. This way you could keep all the links and still avoid confusion, so it would be having the best of two worlds. Depending on the scale of lack of mobile adjustments this may be, however, quite nasty to the users, especially when used for header navigation. If so, I would indicate somehow which links lead to mobile friendly sites and which ones lead to just desktop versions (by grouping and/or some graphical representation).
link migration - it's in the middle between first and second as it touches both UX and SEO. This topic has been widely described by 3nafish in his answer. In short, there should be a 1:1 relation between mobile and desktop links, so if someone enters a desktop link from mobile, he gets redirected to the same content but in mobile version of the site (considering that you have separate mobile site, not responsive layout, where it is dealt with already) AND in the same time, following a mobile link from desktop should lead to the same content in desktop version.
SEO - including/excluding links from mobile version may affect SEO, I think you should also ask http://webmasters.stackexchange.com for opinion.
Answer: Navigation process should follow the task flows based on user needs in specific context. Develop your task flows keeping in mind the user context, and needs. If it is tested to be the same for Desktop and Mobile users, stick to similar navigation pattern, otherwise, I suggest you to change, as both Desktop and Mobile user needs and context tend to differ.


What delegate cant do than Reactive?

Question: in the last two years I build app with MVVM pattern, and every tutorial always says that MVVM use Reactive library, example: RXSwift or ReactiveCocoa because I am iOS programmer. I just realize

Why we need use Reactive, why we dont use just delegate ?
What delegate cant do over Reactive ?
Pros and Cons each pattern ?

I just know that Reactive is Functional programming that mean declarative programming.
Comment: You do not need to use any reactive library to build an app with mvvm pattern. I would also recommend NOT to use any of them only for that. 90% of projects that use RxSwift shouldn't really use it and RxSwift only complicates them. And if you just want an observable then just search on google for observable property wrapper and you will find something that has less than 100 lines of codes for sure.
Answer: For me using delegate alone seems to be the longest way to implement your app logic. Going reactive is much more cleaner, requires less code and is a very powerful way of doing things.
Take for example, let say you want to create a Reactive ButtonTap system using RxSwift/RxCocoa with swift 4:
1) you create a protocol which is implemented the same way as you would when creating a normal delegate abstract class. Note that we are conforming to @objc
import RxSwift
import RxCocoa

// MARK: - ButtonTap Delegate protocol
@objc public protocol ButtonTapDelegate: NSObjectProtocol {
    @objc func button(didSelect view: UIView, at index: Int)
}

2) the DelegateProxyType class is where the reactive stuff happens. Just as you would have a class derive from your delegate (ButtonTapDelegate), this class not only does that but also handles your delegate messages using a PublishSubject.
// MARK: - ButtonTap DelegateProxy
open class ButtonTapDelegateProxy: DelegateProxy<UIView, ButtonTapDelegate>,
DelegateProxyType, ButtonTapDelegate {

    /// Typed parent object.
    public weak private(set) var buttonView: UIView?

    internal var didSelectSubject = PublishSubject<(view: UIView, index: Int)>()

    // MARK: - parent object for delegate proxy.
    public init(parentObject: UIView) {
        self.buttonView = parentObject
        super.init(parentObject: parentObject, delegateProxy: ButtonTapDelegateProxy.self)
    }

    // MARK: - Register known implementationss. (from DelegateProxyType)
    public static func registerKnownImplementations() {
        self.register { ButtonTapDelegateProxy(parentObject: $0) }
    }

    // MARK: - read the current delegate. (from DelegateProxyType)
    public class func currentDelegate(for object: UIView) -> ButtonTapDelegate? {
        return object.delegate
    }

    // MARK: - set the current delegate. (from DelegateProxyType)
    public class func setCurrentDelegate(_ delegate: ButtonTapDelegate?, to object: UIView) {
        object.delegate = delegate as? ButtonTapDelegateProxy
    }

    // MARK: delegate method
    public func button(didSelect view: UIView, at index: Int) {
        didSelectSubject.onNext((view, index))
    }

    // MARK: - dispose the publish subject
    deinit {
        didSelectSubject.on(.completed)
    }
}

3) then, simply create your custom button class where you have the delegate property. You can simply pass a message to your delegate by calling its abstract method.
// MARK: - create Custom ButtonView class with the delegate property
open class ButtonView: UIView {
    @IBOutlet weak open var delegate: ButtonTapDelegate?

    func tapButtonAction() {
        let view = UIView()
        let index = 2
        delegate.button(didSelect: view, at: index)
    }

}

// MARK: - ButtonView must have delegate property
extension ButtonView: HasDelegate {
    public typealias Delegate = ButtonTapDelegate
}

4) you can capture that message sent by your delegate using RxCocoa. You would simply need to refer back to your PublishSubject from your DelegateProxy class using this extension of your view (ButtonView). Note that the extension is Reactive
// MARK: - Custom ButtonView with the Reactive delegate and its protocol function
 public extension Reactive where Base: ButtonView {

    /// Reactive wrapper for `delegate`.
    /// For more information take a look at `DelegateProxyType` protocol documentation.
    fileprivate var delegate: ButtonTapDelegateProxy {
        return ButtonTapDelegateProxy.proxy(for: base)
    }

    public func setDelegate(_ delegate: ButtonTapDelegate) -> Disposable {
        return ButtonTapDelegateProxy
        .installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
    }

    public var didSelect: ControlEvent<(view: UIView, index: Int)> {
        return ControlEvent(events: delegate.didSelectSubject)
    }
}

5) in your ViewController, you would listen to any button tap using RxSwift and capture those events sent by the PublishSubject in your DelegateProxy class.
this is not different from the RxSwift gestures examples: https://github.com/RxSwiftCommunity/RxGesture
class myViewController: UIViewController {

    @IBOutlet weak var buttonView: ButtonView!

    override func viewDidLoad() {
         super.viewDidLoad

         buttonView.rx.didSelect.asObservable()
            .subscribe(onNext: { view, index in
             // button tapped in view at index
        }).disposed(by: bag)
    }

}

This process is very similar to how all the RxSwift and RxCocoa Reactive delegates work, which they have implemented on many UIKit elements like so: https://github.com/ReactiveX/RxSwift/tree/master/RxCocoa/iOS
Going reactive is just very flexible and powerful, there is no need to call delegate methods and set delegates all the time. This only happens once and just imagine the different combinations of how to handle your CustomViews inside your viewController.

What delegate cant do than Reactive?


Differential Equations first order

Question: Anyone who can help me on this equation, $y' = (\frac{y}{x + y^3})$  I've already tried to make a substitution which is: $h(x,y) = x+y^{3}$ and did the derivatives but still no solution, so if anyone knows something, a simple lead. Thanks
Comment: Any own thoughts?
Answer: Notice, we have $$\frac{dy}{dx}=\frac{y}{x+y^3}$$ $$ydx-(x+y^3)dy=0$$ Compare with $Mdx+Ndy=0$, we get $$M=y\iff \frac{\partial M}{\partial y}=1$$ $$N=-(x+y^3)\iff \frac{\partial N}{\partial x}=-1$$ We find that $$\frac{\frac{\partial N}{\partial x}-\frac{\partial M}{\partial y}}{M}=\frac{-1-1}{y}=\frac{-2}{y}=f(y)$$ Hence, the integration factor is $$I.F.=e^{\int f(y)dy}=e^{\int \frac{-2}{y}dy}=e^{-2\ln y}=\frac{1}{y^2}$$ Now, multiplying I.F. on both the sides, we get
$$\frac{1}{y^2}ydx-\frac{1}{y^2}(x+y^3)dy=0$$
$$\frac{1}{y}dx-\left(\frac{x}{y^2}+y\right)dy=0$$
$$\color{}{\frac{1}{y}}dx+\left(-\frac{x}{y^2}\color{}{-y}\right)dy=0$$
Above is the exact differential equation of form $Mdx+Ndy=0$
By comparison, we get $$M=\color{red}{\frac{1}{y}}, \ N=-\frac{x}{y^2}\color{blue}{-y}$$
Now, its solution is given as
$$\int_{y=\text{constant}} Mdx+\int(\text{terms of N not containing x}) dy=c$$
$$\int \color{red}{\frac{1}{y}}dx+\int (\color{blue}{-y}) dy=c$$
$$\frac{1}{y}\int dx-\int y dy=c$$
$$\frac{x}{y}-\frac{y^2}{2}=c$$
Hence, the solution of ODE
$$\bbox[5px, border:2px solid #C0A000]{\color{red}{\frac{x}{y}-\frac{y^2}{2}=c}}$$

Differential Equations first order


How does the piercing modifier affect a Laser Glaive?

Question: I found a Laser Glaive with the the modifier "Shots pierce the first target". The Laser Glaive's description says "bounces on nearby targets", which in practice means it will bounce back and forth between enemies if any are nearby.
How does the piercing modifier work on Laser Glaive? Is there any benefit when the weapon already bounces between enemies?
Comment: I'm wondering if pierce could allow the Glavie to hit shielded enemies.
Answer: There's a similar post on Reddit asking if it's a bug:
Comment: The glaive will bounce forwards without the pierce.
Comment: Ok then it's not supposed to have that feature, so it's likely a bug


XSLT including unwanted elements from outside select criteria

Question: I have an XSLT to transform HTML to XML that's causing me headaches. Superficially, it works as expected but includes unwanted nodes from what I see as outside the select criteria.
To cut a long story short, there are some HTML elements that, if they end with the string 'if:' seem to break the transformToXML parsing using my XSLT.
I assume this is due to the fact that in XSL, the colon character is used as a namespace separator?
The behavior that I see, when there is an if: at the end of the text in a
 element is that other later elements, which should not be selected by by XSLT:and are not selected if the 'if:' is not present, are selected and moved up the returned XML document.
Here's a sample of the html:

    Subpart138.B—Certification

138.075 Key personnel cannot carry out responsibilities

 (1) An aerial work operator contravenes this subregulationif:

 (a) the operator becomes aware that any of its key personnel cannot carry out, or is likely to be unable to carry out, the person's responsibilities for a period of longer than 30 days; and

 (b) the operator does not tell CASA of the matter mentioned in paragraph(a) within the time mentioned in subregulation(2).

 (2) For paragraph(1)(b), the time is:

 (a) if there is not another person authorised to carry out the responsibilities for all or part of the period—24 hours after the operator becomes aware of the matter; or

 (b) if there is another person authorised to carry out the responsibilities for all or part of the period—3 days after the operator becomes aware of the matter.

 (3) A person commits an offence if the person contravenes subregulation(1).

Penalty: 50 penalty units.

138.165 Providing personnel with operations manual

 (1) An aerial work operator contravenes this subregulationif:

 (a) the operator's operations manual relates to a duty or responsibility of a person who is a member of the operator's personnel; and

 (b) the operator does not make the part of the operations manual that relates to the duty or responsibility available to the person before the person first begins carrying out the duty or responsibility.

 (2) A person commits an offence of strict liability if the person contravenes subregulation(1).

Penalty: 50 penalty units.

Division138.B.9—Records and documents

138.170 Personnel training and checking records

 (1) An aerial work operator contravenes this subregulationif:

 (a) a person who is a member of the operator's personnel undertakes a training activity, obtains a qualification or certificate relating to aerial work operations or gains flying experience; and

 (b) the following records are not made within 21 days after the person undertakes the activity, obtains the qualification or certificate or gains the flying experience:

 (i) the date the activity was undertaken, the qualification or certificate obtained or the flying experience gained;

 (ii) if the activity was training or a check, flight test, flight review or assessment of competency—whether the training, check, flight test, flight review or assessment was successfully completed.

 (2) A person commits an offence of strict liability if the person contravenes subregulation(1).

Penalty: 50 penalty units.

If the colon after an if: is removed, then the offending section either does not move up, if it is below the target tag, or the issue resolves for all lines below if the text in the target tag is fixed:
With 'if:' (just first part to illustrate the issue)

        <paragraph text="(a) the operator becomes aware that any of its key personnel cannot carry out, or is likely to be unable to carry out, the person’s responsibilities for a period of longer than 30 days; and"/>
        <paragraph text="(b) the operator does not tell CASA of the matter mentioned in paragraph(a) within the time mentioned in subregulation(2)."/>
        <paragraph text="(a) the operator’s operations manual relates to a duty or responsibility of a person who is a member of the operator’s personnel; and"/>
        <paragraph text="(b) the operator does not make the part of the operations manual that relates to the duty or responsibility available to the person before the person first begins carrying out the duty or responsibility."/>
        <paragraph text="(a) a person who is a member of the operator’s personnel undertakes a training activity, obtains a qualification or certificate relating to aerial work operations or gains flying experience; and"/>
        <paragraph text="(b) the following records are not made within 21 days after the person undertakes the activity, obtains the qualification or certificate or gains the flying experience:">
          <paragraphsub text="(i) the date the activity was undertaken, the qualification or certificate obtained or the flying experience gained;"/>
          <paragraphsub text="(ii) if the activity was training or a check, flight test, flight review or assessment of competency-whether the training, check, flight test, flight review or assessment was successfully completed."/>
        </paragraph>

        <paragraph text="(a) if there is not another person authorised to carry out the responsibilities for all or part of the period-24 hours after the operator becomes aware of the matter; or"/>
        <paragraph text="(b) if there is another person authorised to carry out the responsibilities for all or part of the period-3 days after the operator becomes aware of the matter."/>

With 'if:' changed to 'if', which is the desired result:

        <paragraph text="(a) the operator becomes aware that any of its key personnel cannot carry out, or is likely to be unable to carry out, the person’s responsibilities for a period of longer than 30 days; and"/>
        <paragraph text="(b) the operator does not tell CASA of the matter mentioned in paragraph(a) within the time mentioned in subregulation(2)."/>

        <paragraph text="(a) if there is not another person authorised to carry out the responsibilities for all or part of the period-24 hours after the operator becomes aware of the matter; or"/>
        <paragraph text="(b) if there is another person authorised to carry out the responsibilities for all or part of the period-3 days after the operator becomes aware of the matter."/>

Here's my xslt:
  <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:html="http://www.w3.org/1999/xhtml">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <Part>
      <xsl:apply-templates select="//html:p[@class='SubPartCASA']"/>

    </Part>
  </xsl:template>

  <xsl:template match="//html:p[@class='SubPartCASA']" priority="1">

    <subpart>

      <xsl:attribute name="id">
        <xsl:call-template name="get-leading-number">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>
      <xsl:attribute name="title">
        <xsl:call-template name="remove-whitespace">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>
      <xsl:apply-templates select="following-sibling::html:p[@class='ActHead5'][preceding-sibling::html:p[@class='SubPartCASA'][1] = current()]"/>

    </subpart>
  </xsl:template>

  <xsl:template match="//html:p[@class='ActHead5']" priority="2">

    <regulation>

      <xsl:attribute name="id">
        <xsl:call-template name="get-decimal-number">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>
      <xsl:attribute name="title">
        <xsl:call-template name="remove-whitespace">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>

      <xsl:apply-templates select="following-sibling::html:p[@class='subsection'][preceding-sibling::html:p[@class='ActHead5'][1] = current()]"/>

    </regulation>
  </xsl:template>

  <xsl:template match="//html:p[@class='subsection']" priority="3" disable-output-escaping="yes">

      <xsl:attribute name="text">
        <xsl:call-template name="remove-whitespace">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>

      <xsl:apply-templates select="following-sibling::html:p[@class='paragraph'][preceding-sibling::html:p[@class='subsection'][1] = current()]"/>

  </xsl:template>

  <xsl:template match="//html:p[@class='paragraph']" priority="4" disable-output-escaping="yes">

    <paragraph>

      <xsl:attribute name="text">
        <xsl:call-template name="remove-whitespace">
          <xsl:with-param name="string" select="."/>
        </xsl:call-template>
      </xsl:attribute>

      <xsl:apply-templates select="following-sibling::html:p[@class='paragraphsub'][preceding-sibling::html:p[@class='paragraph'][1] = current()]"/>

    </paragraph>
  </xsl:template>

  <xsl:template match="//html:p[@class='paragraphsub']" priority="5">

    <paragraphsub>

      <xsl:attribute name="text" >
       <xsl:value-of select="."/>
      </xsl:attribute>

    </paragraphsub>
  </xsl:template>

  <xsl:template name="remove-whitespace">
    <xsl:param name="text" />
    <xsl:value-of select="normalize-space(translate(., '

', ''))" />
  </xsl:template>
  <xsl:template name="get-decimal-number">
    <xsl:param name="string" />
    <xsl:value-of select="substring-before(., ' ')" />
  </xsl:template>
  <xsl:template name="get-leading-number">
    <xsl:param name="string" />
    <xsl:value-of select="substring-before(., '-')" />
  </xsl:template>

</xsl:stylesheet>

Here's the PHP Code:
<?php
$html = html_entity_decode(file_get_contents(htmlfile));
$input = new DOMDocument();
$input->loadXML($html);
$stylesheet = new DOMDocument();
$stylesheet->load('xsltemplate');

$processor = new XSLTProcessor();
$processor->importStylesheet($stylesheet);

$output = $processor->transformToXML($input);

file_put_contents('out.xml', $output);

Comment: it would be helpful if you would provide an example of the document these elements that end with 'if:' and it's really hard to help you debug your XSLT if you don't post it for us to see. One snippet of an apply-templates isn't enough to know how it's being processed.
Comment: I suggest you use `DOMDocument::loadHTML` to load the HTML file, rather than treat it as well-formed XML, which it sounds like it isn't (though since you didn't post it, we've no way to know). An HTML parser will likely do a better job of interpreting the content. It may not solve your problem, but it's likely to be a better starting point
Comment: By the way, the special role of the `:` character in the names of elements and attributes is not merely a feature of XSLT but is actually an independent XML specification which is used throughout the XML ecosystem ; it is not strictly part of the core XML spec but effectively it might as well be.
Comment: Thank you for the feedback. I have amended the question with the additional information. I was trying to keep it short as there is a lot of code!
Comment: Please reduce the example to the minimum required to demonstrate the problem - see: [mcve].
Comment: P.S. The colon is used as a special character in element and attributes **names**. When it appears inside a **text node** or in an attribute's **value** it's just another character and has absolutely  nothing to do with namespaces.
Comment: The HTML, XSL Template and PHP now represent a minimal reproducible example.
Comment: It is nowhere near minimal.
Comment: If you change al `if:` to `if` you have the same problem again. It is nothing to do with namespaces.
See answer of Martin Honnen for the solution.
Answer: As far as I grasp the current input, it has at least two e.g.

 (1) An aerial work operator contravenes this subregulationif:

 (1) An aerial work operator contravenes this subregulationif:

Therefore, if you process the first such p class="subsection", the <xsl:apply-templates select="following-sibling::html:p[@class='paragraph'][preceding-sibling::html:p[@class='subsection'][1] = current()]"/> selects not only the immediately following p[@class = 'paragraph'] elements but also those following the p[class = 'subsection'] elements with the same string contents.
Perhaps you want e.g.
  <xsl:apply-templates select="following-sibling::html:p[@class='paragraph'][generate-id(preceding-sibling::html:p[@class='subsection'][1]) = generate-id(current())]"/>


Error: `com.android.Volley.ServerError` when calling local REST service from Android

Question: I tried to call a REST service on local server from Android but I get com.android.Volley.ServerError.
The server works correctly when tested on Java WebFrontEnd

I have permission to access server using my mobile phone. And, http://ipadress:8080/myproject/rest/test works correctly on mobile phone's browser.
Code of Android function:
public void register ()
{
    String url ="http://ipadress:8080/FaceHub/rest/signup";
    StringRequest stringRequest =new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
        }
    })
    {

        @Override
        public String getBodyContentType() {
            return "application/json;charset=utf-8";
        }
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("name", "testname");
            params.put("email", "testmail");
            params.put("pass", "testpass");
            params.put("phone", "testphone");
            params.put("address", "testaddress");

            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(stringRequest);
}

Comment: Please can you put full error message?
public void onErrorResponse(VolleyError error) {
    System.out.println(error.getMessage());
}
Answer: Just add request.setShouldCache(false) before requestQueue.add(stringRequest);.
By default, volley saves the response in its cache and this behavior may cause some strange problem.


Getting data from WCF using Ext.js "Network Error 400 Bad Request"

Question: I am trying to get data from a WCF using Ext.js. I want to click a button and get all the data. Here is what i tried so far:
This is my JavaScript function:
buttonClick: function () {
        var myparams = { 'name': 'baris' };

        Ext.Ajax.request({
            url: 'http://localhost:57044/www/HelloWorldService.svc/GetMessage',//replace with ajax call
            //params: Ext.encode(myparams),
            method: 'GET',
            type: 'ajax',
            success: function (response, opts) {
                if (response.responseText) {
                    Ext.MessageBox.alert('Success', response.responseText);
                }
                else {
                    Ext.MessageBox.alert('Failed', 'Unable to get');
                }
            },
            failure: function (response, opts) {
                alert("failure="+response.responseText);
            }
        });
    }

This is my web service interface code:
namespace Mobile.Service.Maintenance
{
    [ServiceContract]
    interface IHelloWorldService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped,
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json)]
        String GetMessage();
    }
}

This is web service class code:
namespace Mobile.Service.Maintenance
{
    public class HelloWorldService : IHelloWorldService
    {

        public String GetMessage()
        {
            return "Hello world from " +  "baris" + "!";
        }
    }
}

I implemented the WCF service using this tutorial. I created a console application and consumed the WCF,however i failed to do the same thing using Ext.js and Ajax. If i click the button, it always returns to the failure function. In failure function response.responseText outputs an empty string.
I am getting this error in Firebug:
NetworkError: 400 Bad Request - http : //localhost:57044/www/HelloWorldService.svc/GetMessage?_dc=1399642562150
(Yanıt Başlıkları = Response Headers, İstem Başlıkları = Request Headers sorry for Turkish localization)
Thanks, in advance.
This is a screenshot from the firebug.
Answer: Lets understand the concept for services provided by WCF services. WCF services provided two kind of services.
1) SOAP based services.
2) Rest based services - Replaced by Web API now (but still supported by WCF, if you want to develop rest based services use Web API instead)
First time when you followed the tutorial, you built SOAP based services and you are able to consume the service from your console application as console based application that are .net based does have necessary tools that support SOAP based services.
Second time when you are trying to consume services you are trying to consume services that are rest based as Javascript (ExtJs in this case) doesn't support consuming SOAP based services. At least I haven't came across any javascript framework that is capable of consuming SOAP based services from browser to its full extent.
So you should be developing REST based services, if you want to consume those services from web browser (Ext js in this case)
There are few things you need to change within your code to accomplish so
namespace Mobile.Service.Maintenance
{
    [ServiceContract]
    interface IHelloWorldService
    {
        [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Wrapped,
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json
               )]
        String GetMessage();
    }
}

Change your web.config so that it you are trying to provide WCF Restful services
Add following endpoint behavior under behavior section in web.config
 <endpointBehaviors>
        <behavior name="restfulbehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>

Add following endpoint behavior
<services>
      <service name="Mobile.Service.Maintenance.HelloWorldService">
        <endpoint address="" behaviorConfiguration="restfulbehavior"
                  binding="webHttpBinding"
                  bindingConfiguration=""
contract="Mobile.Service.Maintenance.IHelloWorldService"/>

      </service>
    </services>

Trying running the service using your browser first.
localhost:57044/www/HelloWorldService.svc/GetMessage
if it browser display hello world from bars, congratulation you have your first restful web based services.
stackoverflow didn't let me post image, add configuration under   <system.servicemodel>
an excellent article for restful services can be found here
http://www.codeproject.com/Articles/571813/A-Beginners-Tutorial-on-Creating-WCF-REST-Services
Hope this helps
Thank you
Comment: thanks your answer were really great. welcome to so btw.


Php include/require file from parent dirs not working

Question: I have the following directory structure:
- m
--> css
--> js
--> includes

- php_scripts

In my m/includes there is a file called functions.php and in my php_scripts there is a file called conn.php.
I would like to include the conn.phpin the functions.php file but I have no success with it:
<?php
require_once("../../php_scripts/conn.php");

I would assume the previous code is correct but it simply doesn't work. Even if there is no other code in functions.php (just the require), the page loads blank. If I check httpfox I see the result 500 - internal server error. If I comment the line with require_once, it works flawlessly. Any ideas? Thanks a lot!
Comment: You could check your document root using `?php phpinfo();?` to see if the path is right?
Comment: What's inside the php_scripts/conn.php file? It's getting included, it just has something so wrong that it is causing a 500 error.
Answer: try the magic constat "DIR":
require_once(__DIR__."/../../php_scripts/conn.php");


Where are the two pole CAFCI/GFCI breakers?

Question: Why aren't there very many (any?) two pole dual function breakers?
Is a GFCI + CAFCI breaker less useful for 220 or MWBC? Is it be prohibitively expensive? Or is there no demand because not many want to "go the extra mile"?
Note: I'm not asking about combination AFCI breakers, but dual function breakers (ground fault + arc fault in the same breaker) for 220. All I can find is either ground fault or arc fault.
Comment: A very good question... but it's also important to note that one **must not cross brands** on breakers.  Or to be more precise, use only breakers either listed in the panel instructions (same brand) or *UL-Classified* for competitor panels (e.g. Eaton CHQ in a QO panel).  And the latter is no help, since there are no 2-pole dual-function UL-Classified breakers.
Answer: The main reason is NEC doesn't mandate them for 240v setups. 210.12 says (2014 rev quoted, emphasis mine)

210.12 Arc-Fault Circuit-Interrupter Protection. Arc-fault circuit-interrupter protection shall be provided as required in 210.12(A) (B), and (C). The arc-fault circuit interrupter shall be installed in a readily accessible location.
(A) Dwelling Units. All 120-volt, single-phase, 15- and 20-ampere branch circuits supplying outlets or devices installed in dwelling unit kitchens, family rooms, dining rooms, living rooms, parlors, libraries, dens, bedrooms, sunrooms, recreation rooms, closets, hallways, laundry areas, or similar rooms or areas shall be protected by any of the means described in 210.12(A)(1) through (6).

Now, you can find 240v breakers with CAFCI protection. They're pricey, but they are out there. The same can be said for 240v GFCI breakers. The reason there's no dual function breakers likely has to do with them probably costing a great deal by themselves. I mean, a 240v 15A CAFCI is over $100 by itself.
Then there's the need for a GFCI on a 240v line. A subpanel doesn't need one. A dryer or stove doesn't need one. An EV charger will likely have it's own surge protection, which should cover the GFCI portion. There's just not a lot of call for 240v GFCI, and if you do need one, there's no mandate it be AFCI as well.
Answer: The use case for a 240V Dual Function breaker is to protect legacy 120V split phase branch circuits that share a neutral (eg 12/3 romex) when upgrading the main panel on an old house.
I have a 70 year old house with some sketchy hacks to the 120V circuits.  Not looking to rip all the walls open, but want to upgrade the main panel and make it as safe as possible.
The GFCI requirements is that L1 + L2 + N = 0 Amps.  If any of those 3 wires 'leak' to ground both poles should trip.  I don't see why that can't be combined with CAFCI technology too.


Android(mono), TypeLoadException : " Could not load type 'CameraInfo' "

Question: I used the below code piece to read barcode using Zxing barcode library which is downloaded from http://components.xamarin.com/gettingstarted/zxing.net.mobile. Application minVersion is selected as 2.3 and target version is selected as Automatic. I'am running the app on nexus 4 (Android 4.4.2)
<code>    BarcodeButton.Click += async delegate
    {
        var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
        var result = await scanner.Scan();

        if (result != null)
            Toast.MakeText(this,"DONE",ToastLength.Short).Show();
    };
</code>
When I run the application, after pressing the barcodebutton this error log is obtained. What is the error? How can I solve it? :
<code>                              ...
[Mono] Assembly Ref addref ZXing.Net.Mobile[0x784bb038] -> mscorlib[0x777e2a10]: 9
[Mono] Assembly Ref addref TeleLib[0x784b8c58] -> zxing.monoandroid[0x784ba440]: 2
[Mono] The request to load the assembly mscorlib v22.214.171.124 was remapped to v188.8.131.52
[Mono] Unloading image mscorlib.dll [0x78801068].
[Mono] Assembly Ref addref zxing.monoandroid[0x784ba440] -> mscorlib[0x777e2a10]: 10
[Mono] Assembly Ref addref ZXing.Net.Mobile[0x784bb038] -> Mono.Android[0x784bbb98]: 4
[Mono] Assembly Ref addref ZXing.Net.Mobile[0x784bb038] -> zxing.monoandroid[0x784ba440]: 3
[Mono] Assembly Ref addref ZXing.Net.Mobile[0x784bb038] -> Xamarin.Android.Support.v4[0x784b9848]: 2
[Mono] Assembly Ref addref zxing.monoandroid[0x784ba440] -> Mono.Android[0x784bbb98]: 5
[] TypeRef ResolutionScope not yet handled (14) for .CameraInfo in image /data/data/TeleLib.TeleLib/files/.__override__/ZXing.Net.Mobile.dll
[Mono] The class CameraInfo could not be loaded, used in
[MonoDroid] UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'CameraInfo'.
[MonoDroid] at Android.Views.ISurfaceHolderCallbackInvoker.n_SurfaceCreated_Landroid_view_SurfaceHolder_ (intptr,intptr,intptr) <0x0005f>
[MonoDroid] at (wrapper dynamic-method) object.c17a61df-f7d9-45dc-ba1c-dac5c5d9eb39 (intptr,intptr,intptr) <0x00043>
[mono]
[mono] Unhandled Exception:
[mono] System.TypeLoadException: Could not load type 'CameraInfo'.
[mono]   at Android.Views.ISurfaceHolderCallbackInvoker.n_SurfaceCreated_Landroid_view_SurfaceHolder_ (IntPtr jnienv, IntPtr native__this, IntPtr native_holder) [0x00000] in <filename unknown>:0
[mono]   at (wrapper dynamic-method) object:c17a61df-f7d9-45dc-ba1c-dac5c5d9eb39 (intptr,intptr,intptr)
[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'CameraInfo'.
[mono-rt]   at Android.Views.ISurfaceHolderCallbackInvoker.n_SurfaceCreated_Landroid_view_SurfaceHolder_ (IntPtr jnienv, IntPtr native__this, IntPtr native_holder) [0x00000] in <filename unknown>:0
[mono-rt]   at (wrapper dynamic-method) object:c17a61df-f7d9-45dc-ba1c-dac5c5d9eb39 (intptr,intptr,intptr)
</code>
Answer: I was running into the same issue and figured out that the ZXing.NET component requires Android version 2.3. Change your project to target 2.3 or newer, and this error will go away.
Comment: My problem is not because of versioning. I opened a new project, first add the reference and then copy my whole sources. After that it started working!!. But the previous one is not working(??).I compare the configurations 3 times and couldn't find any difference. Anyway it is working now.


What is the best way to beat the nougat monster in candy box two WITHOUT using rocket boots?

Question: I have jumped on him till he dies, but that is only a one in ten chance of working? What should I do?
Answer: You can beat it with boots of introspection, octopus crown with jaspers,red glove, and the enchanted monkey wizard staff. you start off by not moving, drinking a beserker potion,and then casting the black demons spell repeatedly until he is almost on top of you, then jump forward repeatedly but land on the nougat monster until he dies.


problem 'Tkinter as tk' imported but unused

Question: read the related questions but I did not understand much, I could say that nothing, I'm aware I'm in a mechanics course at the university, and I have to use a python code for a certain calculation, the thing that throws me problems but execute but I am intrigued by the error that points, and I searched as a resolution but I do not get the solution so I found this forum and I hope to get to it, the code is as follows:
imagen 1
imagen 2
imagen 3
imagen 4
imagen 5
https://www.mediafire.com/file/uvuyc2v822i3h9b/atwood_viscous_fluid_solver.py/file
I would appreciate it if you can help me, and that the translator helps you enough.
Comment: Never post image of code.
Comment: Pictures of code are absolutely useless.
Comment: To solve this, Change: `import Tkinter as tk` to `import tkinter as tk`
Comment: @U9-Forward *Change: import Tkinter as tk to import tkinter as tk*... This is incorrect. The OP simply needs to apply the `tk.` prefix to the widgets.
Answer: The main problem with your code is you are not applying the tk. prefix to your widgets.
For example if you do From Tkinter import * then you can create a widget like this:
Button(root, text="OK").pack()

However if you use the import Tkinter as tk then you will need to use the tk. prefix for all widget creation.
Like this:
tk.Button(root, text="OK").pack()

So fall all your buttons, labels, entries and any other widget you are setting up use the tk. prefix and it will work.
For this line:
ux = us[:,0]

You do not use ux down the road in your code so the IDE is telling you that ux is unused.
All that said please in the future place your code directly in the question. Using an image makes it hard to test your code as we cannot copy paste into our IDE and test.