text:
Q: How can I create a Barplot with 3 variables? I have a problem to create an appropriate Barplot. Here is my data:
 Site Leaftype Bacteria_per_mm2           SD
1     A        E        1733540.8    455950.56
2     A        B        1062815.7    352876.56
3     A     MI_E        1414862.9    442902.69
4     A     MI_B         638189.9    287774.87
5     B        E              0.0         0.00
6     B        B              0.0         0.00
7     B     MI_E              0.0         0.00
8     B     MI_B         639858.4    213881.70
9     C        E        1862013.0    802574.16
10    C        B         628596.2    153344.48
11    C     MI_E        1417365.6    374644.06
12    C     MI_B         502209.6    270575.29
13    D        E              0.0         0.00
14    D        B         614831.3    176989.64
15    D     MI_E              0.0         0.00
16    D     MI_B       38271374.5 133237805.80
17    E        E        1084505.8    604725.59
18    E        B         306164.3    113604.13
19    E     MI_E         588135.8    178212.25
20    E     MI_B         294207.0    119656.46
21    F        E        1712406.8   1378365.84
22    F        B         329522.9    123385.05
23    F     MI_E              0.0         0.00
24    F     MI_B         389865.9    122340.59
25    G        E              0.0         0.00
26    G        B        6934997.3  28121464.95
27    G     MI_E         957702.0    235390.37
28    G     MI_B         373737.4    131594.27
29    H        E        1677647.0    609105.40
30    H        B         438390.6    145930.97
31    H     MI_E              0.0         0.00
32    H     MI_B         602317.8    187389.36
33    I        E        1683903.8    303170.48
34    I        B              0.0         0.00
35    I     MI_E              0.0         0.00
36    I     MI_B         407941.0    135698.56
37    K        E        1257192.5    297964.48
38    K        B         291982.3    124092.78
39    K     MI_E        1209432.5   1670628.39
40    K     MI_B         442144.7    182276.10
41    L        E        1453793.9    703390.84
42    L        B         663495.1    313438.15
43    L     MI_E        1405130.2  11237373.56
44    L     MI_B        2775709.1   9921931.93
45    N        E         461332.1    120115.39
46    N        B         760822.5    285298.68
47    N     MI_E        1647614.5    260567.19
48    N     MI_B         615109.4    171088.51
49    O        E         931423.6    498561.29
50    O        B         299768.5    144299.92
51    O     MI_E        1112035.5    285024.12
52    O     MI_B         335362.6    114015.88
53    P        E              0.0         0.00
54    P        B         501375.4     84989.70
55    P     MI_E              0.0         0.00
56    P     MI_B         869273.1    149036.53
57    Q        E         961873.2    189228.01
58    Q        B         381523.6    168520.10
59    Q     MI_E         894300.1    184394.29
60    Q     MI_B              0.0         0.00
61    R        E         966878.6    209821.35
62    R        B         284474.2     80791.71
63    R     MI_E         903893.8    558948.64
64    R     MI_B              0.0         0.00
65    S        E              0.0         0.00
66    S        B        1076163.4    927758.07
67    S     MI_E        1137479.7    305446.03
68    S     MI_B         802812.3    190456.51
69    T        E              0.0         0.00
70    T        B        2287681.5  10420861.06
71    T     MI_E              0.0         0.00
72    T     MI_B         761656.7    406262.84

I try to create a barplot, which shows me the number of Bacteria per mm2 leafsurface at the different Sites and for each Leaftype, so I want to create a barplot with one y (response) variable and 2 categorial variables. My first problem is, that Leaftype and Sites are not numeric and R is telling me, that it is not possible to create a barplot with variables, which are not a numeric vector.
Here is my code I used:
Bacteria_all<-read.delim("Mean_Bacteria_counts_final.csv", header = TRUE, sep = ";")# my data
Bacteria_all
str(Bacteria_all)
mean5<-Bacteria_all$Bacteria_per_mm2
mean5
sd5<-Bacteria_all$SD
sd5

library(ggplot2)
ggplot(data=Bacteria_all)+
  geom_bar(stat="identity",aes(x=Site,y=mean5),fill = "forestgreen")+
  theme_bw()+
  geom_errorbar(aes(x=Site,ymin=mean5-sd5,ymax=mean5+sd5),width=0.5)+
  ylim(0,1000000)+
  labs(x='Sites and Tree Species',y= 'Bacterial number per mm2 leafsurface')

And here is the appropriate image, but Leaftypes are missing.

Can you please help me with this problem? I found some related questions, but I am not able to apply these answers to my problem, I am a beginner in R!
Hopefully, you can help me!

A: How about adding facet_wrap to facet by leaftype:
ggplot(data=Bacteria_all)+
geom_bar(stat="identity",aes(x=Site,y=mean5),fill = "forestgreen")+
theme_bw()+
geom_errorbar(aes(x=Site,ymin=mean5-sd5,ymax=mean5+sd5),width=0.5)+
ylim(0,1000000)+
labs(x='Sites and Tree Species',y= 'Bacterial number per mm2 leafsurface') +
facet_wrap( ~ Leaftype, ncol=2)

(Note: I only took a few rows of your data to make this.)
Another approach would be to dodge the bars by leaftype, but this would be more complex to do and would probably look less nice.


text:
Q: Spring internationalization on home page I am trying to implement spring mvc internationalization on my login and Home screen(page comes up after successful login) page.
I tried to do this on login page and its working successfully by using the following code,
webui-servlet.xml

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:ValidationMessages" />
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
         <property name="cookieName" value="clientlanguage"/>
         <property name="cookieMaxAge" value="31449600"/>
    </bean>

    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">

    </bean>

    <bean id="defaultViews" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
            <property name="prefixJson" value="true"/>
        </bean>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" ></bean>

    <mvc:annotation-driven/>

    <mvc:interceptors>
        <bean class="com.check.util.RequestInterceptor"/>

        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
              <property name="paramName" value="lang"></property>
        </bean>
    </mvc:interceptors>

login.jsp

web.xml

<display-name>WebUI</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>webui</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>LoadProperty</servlet-name>
        <servlet-class>com.check.servlet.LoadProperty</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>webui</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/webui-servlet.xml,
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

but when I use the same on home screen page, then language changed but it redirects to login page again.
Please let me know is there any solution that keeps me to stay on the same page from where am changing the language.
Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Argument of type '(e: MediaQueryListEvent) => void' is not assignable to parameter of type '(e: Event) => void' I have created the following hook to listen to events:
const useEventListener = (event: keyof WindowEventMap, callback: (e: Event) => void, element: EventTarget | null = window) => {

  const callbackRef = useRef<(e: Event) => void>(callback)

  useEffect(() => {
    callbackRef.current = callback
  }, [callback])

  useEffect(() => {
    const handler: EventListener = e => callbackRef.current(e);
    element?.addEventListener(event, handler)
    return () => element?.removeEventListener(event, handler)
  }, [event, element])
}

Now I'm trying to create a hook that listens to media queries. However, when I'm passing down to callback: (e: Event) => void the following function (e: MediaQueryListEvent) => setIsMatching(e.matches) I'm getting an error from typescript. I'm struggling since MediaQueryListEvent extends Event! How can I solve?
const useMediaQuery = (mediaQuery: string) => {
  const [isMatching, setIsMatching] = useState(false);
  const [mediaQueryList, setMediaQueryList] = useState<MediaQueryList|null>(null);

  useEffect(() => {
    const list: MediaQueryList = window.matchMedia(mediaQuery)
    setMediaQueryList(list)
    setIsMatching(list.matches)
  }, [mediaQuery])

  # ERROR HERE
  useEventListener("change", (e: MediaQueryListEvent) => setIsMatching(e.matches), mediaQueryList)

  return isMatching;

}

Full error:
Argument of type '(e: MediaQueryListEvent) => void' is not assignable to parameter of type '(e: Event) => void'.
Types of parameters 'e' and 'e' are incompatible.
    Type 'Event' is missing the following properties from type 'MediaQueryListEvent': matches, media

A: The Error makes perfect sense with what you're struggling with ("MediaQueryEvents extends Event").  Event is missing a few properties that MediaQueryListEventshas (matches and media), so Typescript will complain about it.
If you'll only be using your hook with MediaQueryListEvents you can change the type from e: Event to e: MediaQueryListEvents in your hook callback argument (may require importing that type definition from whatever package you're using). If you'll be using a variety of different events, you'll either need to change it to e: any, or use the pipe operator to set multiple possible types for e (e: Event | MediaQueryListEvents and so on).


text:
Q: How to decode transaction input data using `ethers.utils.defaultAbiCoder` I'm fetching transaction data using Etherscan API. This is the example result I'm getting:
{
  blockNumber: '7409930',
  timeStamp: '1639151980',
  hash: '...',
  nonce: '4124',
  ...
  input: '0x9d90e4c8000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000002000000000000000000000000093238bb66b5d15b4152c5db574e3397ff1b1a450',
  contractAddress: '',
  cumulativeGasUsed: '403775',
  gasUsed: '1162315',
  confirmations: '191308'
}

I now need to figure out the event type (contract method, e.g. TransferOwnership, stakeTokens,...) for this transaction. This data is stored in input property of this object.
I managed to accomplish this using abi-decoder library, but I want to accomplish the same thing using ethers's utility method (whichever).
My current implementation:
const abiDecoder = require("abi-decoder");
abiDecoder.addABI(contractAbi);
// "item" is transaction data, input property is encoded stuff from which I want to get the contract method used by this transaction
const decodedInput = abiDecoder.decodeMethod(item.input);

// contract method
console.log(decodedInput.name);

I was reading through ether's documentation (https://docs.ethers.io/v5/api/utils/abi/coder/), but I can't figure it out.

A: you can try what is recommended in this: https://github.com/ethers-io/ethers.js/issues/423 . but if you are interacting with BSC, this is not possible due to the error input data too big causing Error in Big Number Number can only safely store up to 53 bits


text:
Q: undefined method `commentable' for # (accesing commentable id and type via polymorphic association) I tried to fix this issue for a day but cannot find solution.
What I am doing now is to render the comment form
<%= form_for @comment, remote: true do |form|%>
  <%= form.hidden_field :question_id, value: @question.id%>
  <%= form.hidden_field :commentable_id, :value => @question.comments.commentable.id %>
  <%= form.hidden_field :commentable_type, :value => @question.comments.commentable.class.name %>
<% end %>

I just dont know how to access the commetable_id and type that was created with the comment controller to record the id of the comment and the type of the commenting model (e.g. client or lawyer)
  # GET /questions/1 or /questions/1.json
  def show
    set_question
    @comment = Comment.new
    @comments = Comment.all
  end

  # GET /questions/1 or /questions/1.json
  def show
    set_question
    @comment = Comment.new
    @comments = Comment.all
  end

  resources :questions do
    resources :comments do
    end
  end

A: You are using question.comments which indicates has many relation, So it will return you an active record association array, So if you want to find the commentable id, you need to take single record from the array. For example if you want first comment commentable id, then use
   @question.comments.first.commentable.id

If each comment has different commentable id, you need to iterate through loop.
If you have some factor to apply condition, then apply the condition
   @question.comments.where('your condition').first.commentable.id

If you use above code, still you will get the array, so I have used .first. Use a uniq value in where condition, so you will have only single record with that value.

A: As the error message says, you can't call commentable on @question.comments - an association. Pass an array to the form_for method with the commentable (Question) object and the comment object. You don't need to set any hidden fields.
<%= form_for [@question, @comment] do |f| %>

<%= f.label :content %>

<%= f.text_area :content %>

<%= f.submit 'Post' %>

<% end %>

Replace content with the field where you're storing the comment's content.
This should generate a form tag with an action attribute of /questions/1/comments which upon submission is processed by CommentsController#create.
class CommentsController < ApplicationController
  before_action :set_commentable

  def create
    @comment = @commentable.comments.new(comment_params)
    if @comment.save
      redirect_to @commentable, notice: 'Comment created'
    else
      render :new
    end
  end

  private

  def set_commentable
    # e.g. request.path => '/questions/1/comments'
    resource, id = request.path.split('/')[1, 2] # ['questions', '1']
    @commentable = resource.singularize.classify.constantize.find(id)
  end

  def comment_params
    params.require(:comment).permit(:content)
  end
end

In the set_commentable method, the commentable type and its id are detected from the request path. Since resource is 'questions', resource.singularize.classify.constantize returns the Question model. The commentable object is then found using the find method. The CommentsController#create method creates the comment and redirects to the commentable object which is the question show page (/questions/:id). If there's an error, it renders the new view (you have to create views/comments/new.html.erb to render the form with errors).


text:
Q: React native TextInput ref error, focus is not a function I am trying to programatically focus TextInput element with a certain delay after it has mounted, I've got following component (a view that shows input and button)
For some reason this gets error saying

_this2.inputRef.focus is not a function

I'm not sure why. One out of place thing is that I get flow saying that createRef() doesn't exist on React, but I am assuming this is just missing flow definition now, as I am using react 16.3.1 and this was added in 16.3, plus there is no error when its called.
// @flow
import React, { Component, Fragment } from 'react'
import Button from '../../composites/Button'
import TextInput from '../../composites/TextInput'
import OnboardingStore from '../../store/OnboardingStore'
import withStore from '../../store'
import { durationNormal } from '../../services/Animation'

/**
 * Types
 */
export type Props = {
  OnboardingStore: OnboardingStore
}

/**
 * Component
 */
class CharacterNameView extends Component<Props> {
  componentDidMount() {
    this.keyboardTimeout = setTimeout(() => this.inputRef.focus(), durationNormal)
  }

  componentWillUnmount() {
    clearTimeout(this.keyboardTimeout)
  }

  keyboardTimeout: TimeoutID
  inputRef = React.createRef()

  render() {
    const { OnboardingStore } = this.props
    return (
      <Fragment>
        <TextInput
          ref={this.inputRef}
          enablesReturnKeyAutomatically
          value={OnboardingStore.state.username}
          onChangeText={username => OnboardingStore.mutationUsername(username)}
          placeholder="Username"
          blurOnSubmit
          returnKeyType="done"
          onSubmitEditing={/* TODO */ () => null}
        />
        <Button disabled={!OnboardingStore.state.username} color="GREEN" onPress={() => null}>
          Create
        </Button>
      </Fragment>
    )
  }
}

export default withStore(OnboardingStore)(CharacterNameView)

TextInput component I use is imported from this file
// @flow
import React, { Component } from 'react'
import { StyleSheet, TextInput as Input } from 'react-native'
import RatioBgImage from '../components/RatioBgImage'
import { deviceWidth } from '../services/Device'

/**
 * Types
 */
export type Props = {
  style?: any
}

/**
 * Component
 */
class TextInput extends Component<Props> {
  static defaultProps = {
    style: null
  }

  render() {
    const { style, ...props } = this.props
    return (
      <RatioBgImage source={{ uri: 'input_background' }} width={70} ratio={0.1659}>
        <Input
          {...props}
          placeholderTextColor="#4f4a38"
          selectionColor="#797155"
          autoCapitalize="none"
          autoCorrect={false}
          keyboardAppearance="dark"
          style={[styles.input, style]}
        />
      </RatioBgImage>
    )
  }
}

export default TextInput

/**
 * Styles
 */
const styles = StyleSheet.create({
  input: {
    width: '96.4%',
    height: '97.45%',
    color: '#797155',
    fontSize: deviceWidth * 0.043,
    marginLeft: '1%',
    paddingLeft: '5%'
  }
})

Below is what this.innerRef looks like, I don't see any focus property on it at the moment

A: inputRef is a property of the class instance, set it inside a class method.
Using a constructor, for instance:
class CharacterNameView extends Component<Props> {
  constructor() {
    this.inputRef = React.createRef()
  }
  ...
}

A: My issue was in using React.createRef() and assuming I am setting it on a child component. Unfortunately I missed part of the docs about React.forwardRef That I had to use in a child component so ref gets set properly.


text:
Q: Django, how to assign a record to a different staff member? class Enquiry(models.Model):

    CONSULTANT = {
        ('JAS', "do@do.com"),
    }

    first_name  = models.CharField(max_length=35)
    last_name   = models.CharField(max_length=35)
    email       = models.EmailField(max_length=100)
    phone_num   = models.CharField(max_length=35)
    message     = models.TextField(max_length=3000, blank=True, default='')
    processed   = models.BooleanField(default=False)
    assigned_to = models.CharField(max_length=30, choices=CONSULTANT, default='JAS')
    date_added  = models.DateTimeField(auto_now_add=True)

These records are submitted from the website.
The problem is, i am trying to initially have all enquiries go to me. do@do.com, but on the admin dashboard i have created, I will have a href for enquiries.
The staff member will only get enquiries that have been assigned to them.
I don't know how to go about this.
should i make assigned_to field a ForeignKey,  if so O have a custom user that inputs email and password.
or should i use something like request.user.id. should i somehow find my id, and set this as default.
or is there a better method.
Maybe I should assign the user or email address as a dictionary in the view.

A: It is counter intuitive to get this done using a character field. assigned_to must be a ForeignKey to User model (using settings.AUTH_USER_MODEL, see https://docs.djangoproject.com/en/dev/topics/auth/customizing/#referencing-the-user-model).
You can then write a helper method that returns the default assignee (as a User instance). The email is hard coded in the following example for simplicity, but it is recommended to make it a user configurable value (through database or settings) in production:
from django.conf import settings
from django.contrib.auth import get_user_model

def get_default_assignee():
    User = get_user_model()
    try:
        return User.objects.get(email='do@dodo.com')
    except User.DoesNotExist:
        return None

class Enquiry(models.Model):
   ...
   assigned_to =  = models.ForeignKey(
      settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
      default=get_default_assignee, blank=True, null=True)
   ...


text:
Q: How to use no-restricted-imports to prevent any import file that starts with underline (_) I'm trying to prevent any import from "private files" that are specified by prefixing them with an underscore.
As an example, I would like to prevent importing file patters as follows:
import {foo} from '_file';
import {foo} from './_file';
import {foo} from './dialog/_file';
import {foo} from '@alias_root/src/framework/dialog/_file';

To do so, I've used the following rules:
{
   'no-restricted-imports': ['error', {
      patterns: [{
         group: ['_*'],
         message: 'Import files starting with an underline are private',
      }],
    }],
}

Unfortunately this does not seem to catch all the cases I would like to prevent and I'm wondering what I'm missing or how to exactly use this rule.


text:
Q: why centre and acronym tags are removed in html5 since both tags are working fine? we can't use the centre and acronym tags anymore since they are removed in new version of html 5.Instead we have to use alignment equals to centre and abbreviation tag.
I try to use the both tags in html5 but they are not working anymore , instead the code is not executing .generally it was easy to use the centre and many more tags are there which are old and easy to use but they are gone now.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

<centre>

hello this is samten here , i am framing question for stack overflow

</centre>

A: center superseded by CSS in 1996.
acronym was never well supported (I'm talking semantics here, not the ability have to some default styling in the browser CSS) and often conflated with abbr. HTML 5 made that official and explicitly states you should use abbr instead of acronym.


text:
Q: Scraping stopping at first line I need to scrap a website to obtain some information like Film's title and the relative links. My code run correctly but it stops at the first line of the website. This is my code, thank you in advance for your help and sorry if this is not a smart question but I'm a novice.
import requests

from bs4 import BeautifulSoup

URL= 'http://www.simplyscripts.com/genre/horror-scripts.html'

def scarica_pagina(URL):
    page = requests.get(URL)
    html = page.text
    soup = BeautifulSoup(html, 'lxml') l
    films = soup.find_all("div",{"id": "movie_wide"})
    for film in films:
        link = film.find('p').find("a").attrs['href']
        title = film.find('p').find("a").text.strip('>')
        print (link)
        print(title)

A: Try the below way. I've slightly modified your script to serve the purpose and make it look better. Let me know if you encounter any further issues:
import requests
from bs4 import BeautifulSoup

URL = 'http://www.simplyscripts.com/genre/horror-scripts.html'

def scarica_pagina(link):
    page = requests.get(link)
    soup = BeautifulSoup(page.text, 'lxml')
    for film in soup.find(id="movie_wide").find_all("p"):
        link = film.find("a")['href']
        title = film.find("a").text
        print (link,title)

if __name__ == '__main__':
    scarica_pagina(URL)


text:
Q: Not able to create hyperlink when using jquery replace function I am trying to look for a text(sentence) on a page and then replace that with a new text. The below code works fine if the text to be replaced is just text. However i also want to include a hyperlink in the new text.
Original Text: It seems you have already entered this survey.
New text: It seems that someone has XYZ, to go back to your PP account please use this URL: www.xyz.com
Below is the code sample i am using
$ ("*").contents().each(function() {
if(this.nodeType == 3)
    this.nodeValue = this.nodeValue.replace("Old text", "Please click this link");
});

If i try to add hyperlink tag to the text above ""Please click this link", it does not create a hyperlink, instead displays it as a text with the html tag visible

A:
However i also want to include a hyperlink in the new text.

First clear the existing nodeValue
this.nodeValue = "";

Now create a new anchor element
var aNode = document.createElement("a");
aNode.setAttribute( "href", "#" );
aNode.innerText =  "Please click this link";

Now insert aNode this before the nextSibling of the this node
var nextNode = this.nextSibling;
var parentNode = this.parentNode;
parentNode.insertBefore( aNode, nextNode );

DEMO

$("*").contents().each(function() {
  if (this.nodeType == 3 && this.nodeValue.indexOf("Old text") > -1) {
    this.nodeValue = "";

    var aNode = document.createElement("a");
    aNode.setAttribute("href", "#");
    aNode.innerText = "Please click this link";

    var nextNode = this.nextSibling;
    var parentNode = this.parentNode;
    parentNode.insertBefore(aNode, nextNode);
  }
});

prev text

  Old text


text:
Q: Visualize Optical Flow with color model I've implemented a dense optical flow algorithm and I want to visualize it with following color model

(color denotes direction of flow at some point, intensity denotes length of displacement vector)
I've implemented a dirty version of the visualization
def visualizeFlow(u, v):
    colorModel = cv2.imread('../colormodel.png')
    colorModelCenter = (colorModel.shape[0]/2, colorModel.shape[1]/2)
    res = np.zeros((u.shape[0], u.shape[1], 3), dtype=np.uint8)
    mag = np.max(np.sqrt(u**2 + v**2))
    if mag == 0:
        return res, colorModel
    for i in xrange(res.shape[0]):
        for j in xrange(res.shape[1]):
            res[i, j] = colorModel[
                        colorModelCenter[0] + (v[i, j]/mag*colorModelCenter[0]),
                        colorModelCenter[1] + (u[i, j]/mag*colorModelCenter[1])
                    ]
    return res, colorModel

It produce nice in general case pictures but it really slow

So my question is can anyone help me make this visualization faster? If somebody knows a better way to visualize dense flow it may be cool

A: You might wanna check the awesome flow_vis package. Quoting from their page:

*

*pip install flow_vis

*Then in your code:
import flow_vis
flow_color = flow_vis.flow_to_color(flow_uv, convert_to_bgr=False)

A: If you use function provided by opencv your code will run faster.
The optical flow visualization works as follow:

*

*Transform u and v motion components matrices into polar coordinate. Applying cartToPolar function (x array = u array, y array = v array) will get you angle and magnitude matrices of your motion vectors.

The final colour visualization can than be found by an inverse HSV to RGB transformation, where the angle matrice corresponde to the Hue (H) channel and the magnitude to the saturation (S)  the value (V) is set to maxima. ( In your example the value and saturation channels are swapped).

*

*Merge the magnitude, angle and a  matrice filled with 1 to a CV_32FC3 channel matric using merge or mixChannels.

*Apply cvtColor with the flag CV_HSV2BGR. Note angle matric is in degrees and magnitude has to be rescaled to fit i [0,1] which can be done by dividing it by the maximun of the magnitude using e.g. MinMaxLoc

A: Code from OpenCV's tutorial:
import cv2
import numpy as np

# Use Hue, Saturation, Value colour model
hsv = np.zeros(im1.shape, dtype=np.uint8)
hsv[..., 1] = 255

mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
hsv[..., 0] = ang * 180 / np.pi / 2
hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
cv2.imshow("colored flow", bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()


text:
Q: AWS Secret Manager best Practice I have having a spring boot dockerize application running inside fargate cluster.This is application uses aurora DB.
I want to store DB password and API key in AWS Secret Manager.My idea was to make a API from Application and fetch the secret from secret maneger. But architect is saying this is not best approach.
What would be other better ways to achieve this ?

A: ECS provides a tutorial for specifying sensitive data to your cluster using Secrets Manager: https://docs.aws.amazon.com/AmazonECS/latest/userguide/specifying-sensitive-data-tutorial.html.
As for database credentials, if your application is written in Java, the best way to provide rotation-safe credentials to your application is to use the AWS-provided JDBC client library: https://github.com/aws/aws-secretsmanager-jdbc. Then you can safely setup rotation on your database credentials since the library will automatically pull from Secrets Manager and retry connections on authentication failures.

A: You'll want to use IAM Database authentication. Assign an IAM role to your Fargate task with permissions to access your Aurora cluster and voila! No password required.

A: Have you looked into making your code call the Secrets Manager API directly? I wouldn't suggest building an API when one already exists, this can also be used to handle rotated credentials.
Starting point: AWS Java SDK Documentation


text:
Q: share image on linkedin after login in ios I have use this code for share text and image on LinkedIn:-
 NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~/shares"];
  OAMutableURLRequest *request =
  [[OAMutableURLRequest alloc] initWithURL:url
                            consumer:[self getConsumer]
                               token:self.accesstoken
                            callback:nil
                   signatureProvider:nil];

  NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:

                    [[NSDictionary alloc]
                     initWithObjectsAndKeys:
                     @"anyone",@"code",nil], @"visibility",

                    @"comment goes here", @"comment",
                    [[NSDictionary alloc]
                     initWithObjectsAndKeys:
                    @"description goes here",@"description",
                    @"www.google.com",@"submittedUrl",
                      @"title goes here",@"title",
                    @"http://economy.blog.ocregister.com/files/2009/01/linkedin-logo.jpg",@"submittedImageUrl",nil],@"content",
                    nil];
  [request setValue:@"json" forHTTPHeaderField:@"x-li-format"];
  [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
  NSString *updateString = [update JSONString];
  [request setHTTPBodyWithString:updateString];
  [request setHTTPMethod:@"POST"];
  OADataFetcher *fetcher = [[OADataFetcher alloc] init];
  [fetcher fetchDataWithRequest:request
                 delegate:self
        didFinishSelector:@selector(postUpdateApiCallResult:didFinish:)
          didFailSelector:@selector(postUpdateApiCallResult:didFail:)];

But I have errors on:-  consumer:[self getConsumer] , token:self.accesstoken and not found these methods postUpdateApiCallResult:didFinish: , postUpdateApiCallResult:didFail:


text:
Q: How to delete only archives with a script I would like to remove all of the archives (.tar, .zip, etc) on my system.
I know how to delete files using rm but I'm wondering if there is a command just for deleting the archives on my system (and not regular files).
Thanks

A: You can delete an archive like you would any regular file you have rights to:
rm /path/to/archive

To delete all the files in a certain directory or a folder with more than one file use the -r flag (recursive).
rm -r /path/to/directory

To delete just  .tar and .zip files in /path/to/directory/ use this line:
rm -r /path/to/directory/*.tar  /path/to/directory/*.zip

Note: If you get permission denied, then run the command again with sudo in front of it.
For more information, check out the rm manual page.


text:
Q: Deserializing JSON response in Symfony In my API I have the following code:
$encoders = [new JsonEncoder()];
        $normalizer = new ObjectNormalizer();
        $normalizer->setIgnoredAttributes(array('company','profile','createdAt','profileName','appui','id','brokerId','productList','appkey'));

        $serializer = new Serializer([$normalizer], $encoders);

        return new JsonResponse($serializer->serialize($products, 'json'),
        JsonResponse::HTTP_OK
        );

It returned the following:
"[{\u0022name\u0022:\u0022i2\u0022,\u0022serial\u0022:\u0022i2\u0022,\u0022sgin\u0022:\u00225d134d280f1a9\u0022},{\u0022name\u0022:\u0022i3\u0022,\u0022serial\u0022:\u0022i3\u0022,\u0022sgin\u0022:\u00225d134dbb1609f\u0022},{\u0022name\u0022:\u0022i4\u0022,\u0022serial\u0022:\u0022i4\u0022,\u0022sgin\u0022:\u00225d1351c3c0153\u0022},{\u0022name\u0022:\u0022i5\u0022,\u0022serial\u0022:\u0022i5\u0022,\u0022sgin\u0022:\u00225d13520472ab8\u0022},{\u0022name\u0022:\u0022i6\u0022,\u0022serial\u0022:\u0022i6\u0022,\u0022sgin\u0022:\u00225d13526e4cdbc\u0022}]"

But when I try to use it in another site, I don't get it properly deserialized. It just returned that string rather than a JSON object.

A: send the value through json_decode
I found a response here after realizing what you said about it being sent as string. It was clearly unicode. So, the suggestion on that page is use json_decode inside JsonReponse first. And it worked.


text:
Q: In what conditions the checkError() method of the PrintStream object returns true? As given in JAVA docs, the variable 'trouble' gets set to true whenever there is a java.io.IOException. I write a program:
import java.io.*;
class First
{
        public static void main(String[] args) throws Exception
        {
                File f = new File("a.txt");
                PrintStream ps = new PrintStream(f);
                f.delete();
                ps.write(65);
                boolean b = ps.checkError();
                System.out.println(b); //Output: false
                ps.close();
        }
}

Even if I deleted the file before writing, why the method checkError() is not returning true? Please give an example when the variable 'trouble' set to true and the method checkError() returns true.

A: According to JavaDoc:

checkError returns true if and only if this stream has encountered an IOException other than InterruptedIOException, or the setError method has been invoked.

A:
Even if I deleted the file before writing, why the method checkError() is not returning true? Please give an example when the variable 'trouble' set to true and the method checkError() returns true.

*

*You don't know that you deleted the file, as you aren't checking the result of File.delete().

*You are creating the PrintStream without autoFlush, so println() does nothing to the file system.

*There is no reason why deleting the file should cause an IOException on write even if it succeeds and the write is flushed. Try it with FileOutputStream for example.
Your question is founded on three false assumptions.


text:
Q: Backup Plan for Server Down Time I am looking for a way to avoid as much actual downtime as possible (aren't we all). We have experienced a good deal server overload/problems lately. Our existing setup is as follows (they're Linux servers):
2 Load Balancers - one for HTTP requests, the other for HTTPS
3 Web Servers (4GB of memory per drive) - one master head which is synced to two slave drives using lSync
2 Database Servers connected to the sites via private IP
We use Varnish for caching, but primarily to uploads and admin connections to web01 for proper syncing
Almost all of our sites are WordPress installations. Our traffic is largely driven by email blasts so we have concentrated periods of time with heavy traffic.
The problem: when one site is hit with a lot of traffic, or when something goes wrong with our system configurations, all sites go to a crawl if not complete halt.
Question #1: are there server configurations that could be set in place that when one server cluster goes down, the other kicks in, etc.?
Question #2: can anybody recommended good resources on this topic possibly including diagrams of various server configurations? How do the really big guys do it? :-)
P.S. My server management knowledge is limited, but I'm looking forward to learning and attempting to understand your responses!

A: Without knowing a bit more about how you have WordPress set up, it's hard to give more than general advice.
The varnish wiki has a great set of suggestions for preparing for traffic spikes on a WordPress site.
As for me, I run all my WordPress sites on nginx and php-fpm. WP has W3 Total Cache plugin installed to generate static content, which nginx then serves directly. WP and PHP never get touched in these cases and nginx just blasts the static data out the door. So far it has not been necessary to cache further. I presume something similar could be done with varnish.


text:
Q: How can I add line breaks into a tibble output in R? I am writing an R script that is pulling expected outputs of various data sets and then putting those into a tibble that will be later exported into Excel.
I want to keep a row for each data set and then the last column will have five example outputs.
I can create a string like 2021 :: 2039909\n2020 :: 1096166\n2019 :: 195718\n2018 :: 6209\n2017 :: 1547 that has the example outputs.
But when I try to put those into a tibble I can't figure out how to convert the \n into a line break. When I try cat or writeLines I get
Error in vec_rbind(old, new) :
  Internal error in `vec_assign()`: `value` should have been recycled to fit `x`.

I get it when I try
data <- add_row(data, values = writeLines(dataset))
where dataset would be
2021 :: 2039909\n2020 :: 1096166\n2019 :: 195718\n2018 :: 6209\n2017 :: 1547
I definitely will appreciate any help you can give me!


text:
Q: Spring start another application Spring launch of other services.
I have a main application (HUB)
Service for processing requests (connector)
A service that stores data in the H2 database
When starting the hub, all services and the H2 database must be started!
How to do it correctly?
At the moment, I start all the services by simulating the console commands java -jar service_name.jar via Proccess
But I think this is a very bad approach. I can't monitor the processes of the services in any way.
For example, if I start another service "connector" from the command line, the hub will be able to see it through eureka, but if it wants to kill it, it will not be able. Because the hub does not know anything about the process instance.
I see a problem here.
Moreover, together with the hub, I want to run h2database, then I need to monitor the memory that the base occupies. What is the best way to do this?
Maybe I didn't express myself well.
I will hope for your support.
I am using eureka in this project. Maybe there are ways to run services using it?


text:
Q: Give an example of a linear map $T: \Bbb R^2 → \Bbb R^2$, such that $T^{12}$ has real eigenvalues, while $T^n$, with $n= 1,2,...,11,$ do not. I am doing my revision for exam, but I stuck in a past paper question.
Give an example of a linear transformation $T: R^2 → R^2$, such that $T^{12}$ has real eigenvalues, while $T^n$, with $n= 1,2,\dots,11$ do not. Write the matrix which represents $T$.
(Edited)
Please teach me how to tackle with that question.

A: Hint: a rotation that is neither $180^\circ$ nor $0^\circ$ has no real eigenvalues.

A: By diagonalization, you can find that any diagonal matrix $A$ can be represented as
$$A = P D P^{-1},$$
where $D$ is a diagonal matrix in which each element is an eigenvalue, and then $P$ is a nonsingular matrix (i.e. its columns are linearly independent).
Now, the power of a diagonalization is that you can easily figure out the power of a matrix (pun somewhat intended):
$$A^n = P D^n P^{-1}$$
Hence, if you have $\lambda_i$ is the $i$th eigenvalue of $A$, then $\lambda_i^n$ is the $i$th eigenvalue of $A^n$.
So if you want $A^{12}$ to have real eignvalues, but $A^1, A^2, ... A^{11}$ to have only complex eignenvalues, all you need is to find any nonsingular $2\times 2$ matrix $P$ and two values $\lambda_i$ so that $\lambda_i^n$ is real if $n = 12$ and complex if $n < 12$.
To find those $\lambda_i$ values, you can note that the nth roots of unity are complex, usually. If you take any two complex twelfth-roots of unity $e^{2\pi i {k \over 12}}$ as your two eigenvalues, then $A$ will have only complex eigenvalues, while $A^{12}$ will have only real eigenvalues.
While the other answer does provide one way of looking at the problem (rotations), here I showed how to think of the problem in general.
Hope this helps!


text:
Q: Flip ViewPager like ViewFlipper I have implemented ViewPager to swipe between multiple views.
What i want is to flip each of the view in viewpager like Viewflipper.
Placing viewflipper inside viewpager in xml layout generates random layout.


text:
Q: Не получается создать структуру которая внутри будет добавлять объект в массив такой вариант
struct SwimmingWorkout {
enum Stroke {
    case freestyle, butterfly
}
var distance : Double
var time: Double
var stroke: Stroke
var freestyleArray : [SwimmingWorkout] = []
var butterflyArray : [SwimmingWorkout] = []

mutating func saveToArray () {
    switch stroke {
    case .freestyle : freestyleArray.append(self)
    case .butterfly : butterflyArray.append(self)
    }
}

}
но он оне верный. подскажите как правильно

A: почему не верный?
просто надо создать экземпляр структуры
можно создать внутри структуры конструктор, можно вот так:
var test = SwimmingWorkout(stroke: .butterfly, freestyleArray: [], butterflyArray : [])

затем вызвать метод
test.saveToArray()


text:
Q: Get ID of form when using onsubmit Javascript:
function submitComment(e){
  e.preventDefault();
  var comment = $('#????').val(); // how do I get the ID?
  // ajax
}

Comment form:
<form id="comment-form[id]" onsubmit="submitComment(event)">
    <input id="comment-input[id]" type="text" placeholder="Comment...">
</form>

[id] is the variable ID of the specific form. The reason it has an ID is because I have a for loop that displays a whole list of posts, and each post has its own comment form (think Facebook).
What I want to know is how I can get the value (text) of the comment input box when they submit it based on the ID of the form that was submitted.

A: With your setup(HTML/javascript) you can do this with pure javascript like
function submitComment(e) {
   var id = e.target.id;
   id = id.match(/\[(.*?)\]/)[1];
   console.log(id);
   var comment  = document.getElementById('comment-input['+id+']').value;
   console.log(comment);
}

function submitComment(e){
  var id = e.target.id;
  id = id.match(/\[(.*?)\]/)[1];
  console.log(id);
  var comment  = document.getElementById('comment-input['+id+']').value;
  console.log(comment);
}
<form id="comment-form[0]" onsubmit="submitComment(event)">
    <input id="comment-input[0]" type="text" placeholder="Comment...">
  <input  type="submit" placeholder="submit">
</form>

A: You can use event.target.
var comment = $('input[id^="comment-input"]',e.target).val()

This will give you input value.

*

*e.target will give you the current form.

*Then you can use [^=""] - attribute starts with selector to find the input element.

how I can get the value (text) of the comment input box based on the ID of the form that was submitted

var formID = e.target.id;   //get form ID
var comment = $('#'+formID+' input[id^="comment-input"]').val()
//use $('#parent child') selector.

A: function submitComment(e){
       e.preventDefault();
       // e.currentTarget gives you the form element and then you can extract its id
       var formElementId = $(e.currentTarget).attr("id");
       // Then replace the form text with input which will be your comment input id
       var commentElementId = formElementId.replace("form", "input");
       var comment = $(commentElementId).val(); // how do I get the ID?
       // ajax
 }

A: function submitComment(e){
  e.preventDefault();
  var comment = $('input[id^="comment-input"]').val();
  // ajax
}

Use of jquery start-with selector can be helpful.


text:
Q: Why do libgit2 methods using kernel32.dll's GetProcAddress always return 0? I have the need to manually handle the loading / unloading of the actual git2.dll, instead of using [DllImport("git2")] in C#. I seem to have issues with creating an IntPtr for reference to the address of methods stored in libgit2.
Here're the good bits from my PluginManager class which are supposed to help facilitate manually loading, marshal/delegate (whenever I get this kink fixed), and unloading libraries.
public class PluginManager {
    public const string LIB = "Assets\\Plugins\\git2.dll";

    [DllImport( "kernel32.dll", CharSet = CharSet.Ansi )]
    public static extern IntPtr LoadLibrary( [In, MarshalAs( UnmanagedType.LPStr )] string lib );

    [DllImport( "kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true )]
    public static extern IntPtr GetProcAddress( [In] IntPtr reference, [In, MarshalAs( UnmanagedType.LPStr )] string method );

    [DllImport( "kernel32.dll" )]
    public static extern bool FreeLibrary( [In] IntPtr reference );
}

Here's where I attempt to use them:
//# Working; always non-zero.
IntPtr reference = PluginManager.LoadLibrary( PluginManager.LIB );

//# Should be valid -- LibGit2Sharp.Core.NativeMethods.cs calls this method, too.
//# Always returns IntPtr.Zero.
IntPtr methodReference = PluginManager.GetProcAddress( reference, "git_repository_open" );

Is the library not exposed to this type of loading? I've tried all kinds of methods present in the LibGit2Sharp native hooks, but they always return zero.

A: It seems that git2.dll has mangled export names, so git_repository_open is actually _git_repository_open@4. After researching some more on why this is happening, it seems that, according to This Post, and several others that I've run into while looking for a fix, that the functions may not be exported using extern "C" or may not be using a .def file.
I did look through some of the libgit2 code, and I saw extern used on a couple functions, but on others I saw no export keyword at all, but they're still being accessed externally from LigGit2Sharp's NativeMethods.cs class.
While all of that is foreign to me, I did find a very useful post about a tool shipped with Visual Studio that allows you to see all exported items, and their names: Dumpbin. With this, I was able to determine the exported names, and used the /OUT:filename flag to save them to a file: PasteBin
With all of the exported names at my disposal, I just have to follow function calls, that I'm actually using, and replace the the methods in NativeMethods.cs to look something like this: LibGit2Sharp Issue #341.


text:
Q: Pivot specific rows into columns I have a pandas dataframe with the following structure
Layer   distance    angle        X_UTM_0        Y_UTM_0
layer0  0           65.57315016  627792.796  4785636.433
layer0  66.77813701 44.90815387  627852.132  4785666.409
layer1  0           236.3706271  627854.177  4785669.487
layer1  71.46111277 244.9836507  627791.986  4785636.986
layer2  0           60.78662778  627791.393  4785637.658
layer2  70.2562004  57.98453037  627853.635  4785669.768

What I want to do is pivot the repeated layer0...n to columns to obtain something like
Layer   distance    angle       X_UTM_0     Y_UTM_0     X_UTM_1     Y_UTM_1
layer0  0       65.57315016 627792.796  4785636.433 627852.132  4785666.409
layer1  0       236.3706271 627854.177  4785669.487 627791.986  4785636.986
layer2  0       60.78662778 627791.393  4785637.658 627853.635  4785669.768

where i have both coordinates of each layer in the same row. I was thinking in using pivot_table, but I'm not sure how to approach this. Any hint would be very appreciated.
EDIT: To clarify, I do not need distance and angle columns, I can drop them. The idea is to convert to columns each field of repeated Layerrow.

A: Assuming that the splitting condition is always in the 'distance' column, the following actions can be taken. If not, this response is invalid.
df1 = df[df['distance'] == 0.0]
df2 = df[~(df['distance'] == 0.0)]
df3 = df1.merge(df2[['Layer','X_UTM_0','Y_UTM_0']], on='Layer', how='outer')
df3.columns = ['Layer', 'distance', 'angle', 'X_UTM_0', 'Y_UTM_0', 'X_UTM_1', 'Y_UTM_1']

df3
    Layer   distance    angle   X_UTM_0 Y_UTM_0 X_UTM_1 Y_UTM_1
0   layer0  0.0 65.573150   627792.796  4785636.433 627852.132  4785666.409
1   layer1  0.0 236.370627  627854.177  4785669.487 627791.986  4785636.986
2   layer2  0.0 60.786628   627791.393  4785637.658 627853.635  4785669.768


text:
Q: Generic Microcontroller Delay Function Come someone please tell me how this function works? I'm using it in code and have an idea how it works, but I'm not 100% sure exactly. I understand the concept of an input variable N incrementing down, but how the heck does it work? Also, if I am using it repeatedly in my main() for different delays (different iputs for N), then do I have to "zero" the function if I used it somewhere else?
Reference: MILLISEC is a constant defined by Fcy/10000, or  system clock/10000.
Thanks in advance.
// DelayNmSec() gives a 1mS to 65.5 Seconds delay
/*  Note that FCY is used in the computation.  Please make the necessary
    Changes(PLLx4 or PLLx8 etc) to compute the right FCY as in the define
    statement above. */
void DelayNmSec(unsigned int N)
{
unsigned int j;
    while(N--)
        for(j=0;j < MILLISEC;j++);
}

A: This is referred to as busy waiting, a concept that just burns some CPU cycles thus "waiting" by keeping the CPU "busy" doing empty loops.  You don't need to reset the function, it will do the same if called repeatedly.
If you call it with N=3, it will repeat the while loop 3 times, every time counting with j from 0 to MILLISEC, which is supposedly a constant that depends on the CPU clock.

A: The original author of the code have timed and looked at the assembler generated to get the exact number of instructions executed per Millisecond, and have configured a constant MILLISEC to match that for the for loop as a busy-wait.
The input parameter N is then simply the number of milliseconds the caller want to wait and the number of times the for-loop is executed.
The code will break if

*

*used on a different or faster micro controller (depending on how Fcy is maintained), or

*the optimization level on the C compiler is changed, or

*c-compiler version is changed (as it may generate different code)

so, if the guy who wrote it is clever, there may be a calibration program which defines and configures the MILLISEC constant.

A: This is what is known as a busy wait in which the time taken for a particular computation is used as a counter to cause a delay.
This approach does have problems in that on different processors with different speeds, the computation needs to be adjusted.  Old games used this approach and I remember a simulation using this busy wait approach that targeted an old 8086 type of processor to cause an animation to move smoothly.  When the game was used on a Pentium processor PC, instead of the rocket majestically rising up the screen over several seconds, the entire animation flashed before your eyes so fast that it was difficult to see what the animation was.
This sort of busy wait means that in the thread running, the thread is sitting in a computation loop counting down for the number of milliseconds.  The result is that the thread does not do anything else other than counting down.
If the operating system is not a preemptive multi-tasking OS, then nothing else will run until the count down completes which may cause problems in other threads and tasks.
If the operating system is preemptive multi-tasking the resulting delays will have a variability as control is switched to some other thread for some period of time before switching back.
This approach is normally used for small pieces of software on dedicated processors where a computation has a known amount of time and where having the processor dedicated to the countdown does not impact other parts of the software.  An example might be a small sensor that performs a reading to collect a data sample then does this kind of busy loop before doing the next read to collect the next data sample.


text:
Q: Unexpected response code 500 for when calling C# web services **Here is the web service link:
geting error 500 when calling the webservice...is there anything wrong with my codes? that i need to change?
the web service is running fine in the browser
http://www.spgautopark.com.my/spgservices/parking_registration.asmx?op=Signup**
Registration
public class SignupActivity extends AppCompatActivity {

    Button signup;
    TextView login;

   EditText edt_name,edt_phone,edt_mail,edt_vehno,edt_pwd,edt_cpwd;
    String email;

    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

    String name,phone,mail,pwd,vehno;
    String deviceId;
    String Result, Message, Username,cid,Email,Mobile, address;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        context = this;

        deviceId = Settings.Secure.getString(this.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        //Toast.makeText(getApplicationContext(), deviceId, Toast.LENGTH_SHORT).show();

        signup = (Button) findViewById(R.id.signaccount);
        login= (TextView) findViewById(R.id.login);

        edt_name= (EditText) findViewById(R.id.name);

        edt_phone= (EditText) findViewById(R.id.phone);

        edt_mail= (EditText) findViewById(R.id.mail);

        edt_vehno= (EditText) findViewById(R.id.vehno);
        edt_pwd= (EditText) findViewById(R.id.pwd);

        edt_cpwd= (EditText) findViewById(R.id.cpwd);

        login.setText(Html.fromHtml("<u>Login</u>"));

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                email = edt_mail.getText().toString().trim();

               /* if (emailText.getText().length() != 0) {

                } else {
                    emailText.setError("Invalid Email");

                }*/

                if (edt_name.getText().length() == 0) {
                    edt_name.setError("Enter name");

                }

                else if (edt_phone.getText().length() != 10) {
                    edt_phone.setError("Enter Mobile no");

                }

                if (email.matches(emailPattern) && email.length() > 0) {
                    //Toast.makeText(getApplicationContext(), "valid email address", Toast.LENGTH_SHORT).show();
                    // or
                    //textView.setText("valid email");
                } else {

                    edt_mail.setError("Invalid email");
                    //Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
                    //or
                    // textView.setText("invalid email");
                }
                if (edt_vehno.getText().length() == 0) {
                    edt_vehno.setError("Enter vehno");

                }

                else if (edt_pwd.getText().length() == 0) {
                    edt_pwd.setError("Enter Password");
                }
                else if (edt_cpwd.getText().length() == 0) {
                    edt_cpwd.setError("Enter Re-Type Password");

                }
                else if (edt_pwd.getText().toString().equals(edt_cpwd.getText().toString())) {

                    if ((edt_name.getText().length() != 0) && (edt_mail.getText().length() != 0) && (edt_vehno.getText().length() != 0)
                            && (edt_phone.getText().length() != 0) && (edt_pwd.getText().length() != 0)
                            && (edt_cpwd.getText().length() != 0) && (email.matches(emailPattern) && email.length() > 0)) {
                        Log.e("testing", "before user data class");
                        registerUser();
                        //openProfile();

                    }

                }

                else

                {

                    Toast.makeText(getApplicationContext(), "Password Missmatch", Toast.LENGTH_LONG).show();

                }

                // Start the Activity_Signup activity

                /*Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
                 //((Activity_Login) context).finish();
                startActivity(intent);
*/
               /* HomeFragment fragment4 = new HomeFragment();

                android.support.v4.app.FragmentTransaction fragmentTransaction4 =
                        getSupportFragmentManager().beginTransaction();

                fragmentTransaction4.replace(R.id.fragment_container, fragment4);

                fragmentTransaction4.commit();
*/
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Start the Activity_Signup activity

                Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
                //((Activity_Login) context).finish();
                startActivity(intent);

               /* HomeFragment fragment4 = new HomeFragment();

                android.support.v4.app.FragmentTransaction fragmentTransaction4 =
                        getSupportFragmentManager().beginTransaction();

                fragmentTransaction4.replace(R.id.fragment_container, fragment4);

                fragmentTransaction4.commit();
*/
            }
        });

    }

//---------------------------------Registration Method------------------------------------------------//

    private void registerUser(){

        name = edt_name.getText().toString().trim();

        phone = edt_phone.getText().toString().trim();

        mail= edt_mail.getText().toString().trim();
        //phone = edt_pwd.getText().toString();
        pwd =edt_pwd.getText().toString().trim();
        vehno = edt_vehno.getText().toString().trim();
//The above values u need to pass to the SIGNUP_URL...

        //utype = spstring;

//correct code
        StringRequest stringRequest = new StringRequest(Request.Method.POST, End_Urls.SIGNUP_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("sinup response testing", "json response = "+response);

                        try {

                            JSONObject jsonArray1 = new JSONObject(response);

                            Log.e("jsonArray1", "json jsonArray1 = "+jsonArray1);

                            Result = jsonArray1.getString("status");
                            Message = jsonArray1.getString("response");

                            //name1 = jsonArray1.getString("user_id");
                            //email1 = jsonArray1.getString("user_id");
                            //password1 = jsonArray1.getString("user_id");
                            //phone1 = jsonArray1.getString("user_id");
                            //area1 = jsonArray1.getString("user_id");
                            cid = jsonArray1.getString("register_id");
                            //oname1 = jsonArray1.getString("user_id");

                            Log.e("testing","Result == "+Result);
                            Log.e("testing","Message == "+Message);
                            //Log.e("testing","RegisterName == "+JsonName);
                            Log.e("mahi cid testing","RegisterId == "+cid);

                        } catch (JSONException e) {
                            //Log.e("testing","Exception =" + e);
                            e.printStackTrace();
                        }

                        // Log.e("testing", "json response=="+response);

                        if (Result.equals("yes")) {

                            Toast.makeText(getApplicationContext(),Message,Toast.LENGTH_LONG).show();
                            Log.e("testing", "Message111==" + Message);
                            openProfile();
                        }

                        else if (Result.equals("null"))
                        {
                            Toast.makeText(getApplicationContext(),Message,Toast.LENGTH_LONG).show();
                            Log.e("testing", "Message222=="+Message);
                            Intent intentN = new Intent(SignupActivity.this,LoginActivity.class);

                            ((SignupActivity) context).finish();
                            //intent.putExtra(KEY_PHONENO, phoneno);
                            startActivity(intentN);

                        }

                        else if (Result.equals("No")){

                            Log.e("testing", "json response == " + response);
                            Toast.makeText(SignupActivity.this, Message, Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(SignupActivity.this, LoginActivity.class);

                            //((Activity_Login) context).finish();
                            //intent.putExtra(KEY_PHONENO, phoneno);
                            startActivity(intent);

                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(SignupActivity.this,Message,Toast.LENGTH_LONG ).show();
                        Log.e("testing","error response == " +
                                ""+error);
                        Intent intent = new Intent(SignupActivity.this,LoginActivity.class);
                        //intent.putExtra(KEY_PHONENO, phoneno);
                        startActivity(intent);

                    }
                })

        {
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();

                params.put(End_Urls.Signup_username,name);
                params.put(End_Urls.Signup_phone,phone);
                params.put(End_Urls.Signup_email, email);
                params.put(End_Urls.Signup_vehno, vehno);
                params.put(End_Urls.Signup_deviceid, pwd);
                params.put(End_Urls.Signup_pwd, pwd);
                params.put(End_Urls.Signup_deviceid, deviceId);
                //params.put(End_Urls.Signup_deviceid, "deviceIdtesting");
                //params.put(UrlEndpoints.KEY_user_type, spstring);
                Log.e("testing", "params11==" + params);

                return params;

            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void openProfile(){

       /* final String name = _userNameText.getText().toString().trim();

        final String email = emailText.getText().toString().trim();

        final String password = _passwordText.getText().toString().trim();

        final String area = areaText.getText().toString().trim();
        final String oname = onameText.getText().toString().trim();

*/
        Intent intentN = new Intent(SignupActivity.this,Activity_Verify_Phone.class);

        intentN.putExtra("cid", cid);

        //((Activity_Signup) context).finish();
        //intent.putExtra(KEY_PHONENO, phoneno);
        startActivity(intentN);

    }

}

A: use the below code , put your parameter and result on the map
public void HttpPOSTRequestWithParameters() {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://www.spgautopark.com.my/spgservices/parking_registration.asmx?op=Signup";
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("ERROR","error => "+error.toString());
                }
            }
                ) {
            // this is the relevant method
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("grant_type", "password");
                // volley will escape this for you
                params.put("keys", "values");
                params.put("put keys", "values");
                params.put("keys", "valuers");

                return params;
            }
        };
        queue.add(postRequest);
    }


text:
Q: Comparing 2 arrays for tolerance What I am trying to do is tax an array, transpose it , subtract the two arrays and then see if the difference of each cell is with a certain tolerance. I am able to get a subtracted array - but I don't know how to cycle through each item to compare the amounts - ideally I would test for floating-point near-equality; and return true - if all items are with a tolerance and false otherwise - not sure how do to this last step as well.
import numpy as np

a = np.array(([[1, 2, 3], [2, 3, 8],[ 3, 4, 1]])
b = a.transpose(1, 0)

rows = a.shape[1]
col = a.shape[0]
r = abs(np.subtract(a, b))  # abs value of 2 array

i = 0
while i < rows:
    j = 0
    while j < rows:
        if np.any(r[i][j]) > 3:  # sample using 3 as tolerance
            print("false")
        j += 1
    print("true")
    i += 1

A: Is this not sufficient for your needs?
tolerance = 3
result = (abs(a - b) <= tolerance).all()

A: In this step
r = abs(np.subtract(a, b))

you already have a matrix of distances, so all you need to do is apply comparison operator (which in numpy is applied element-wise)
errors = r > 3

which results in boolean array, and if you want to see how many elements have true value, just sum it
print( np.sum(r > 3) )

and to check if any is wrong, you can just do
print( np.sum(r > 3) > 0 ) # prints true iff any element of r is bigger than 3

There are also built-in methods, but this reasoning gives you more flexibility in expressing what is "near" or "good".


text:
Q: Let $T:\mathcal{P}(\mathbb{R})\to \mathcal{P}(\mathbb{R})$ such that $T(p)=p-p'$. Find all eigen values and eigen vectors of $T$. Let $T:\mathcal{P}(\mathbb{R})\to \mathcal{P}(\mathbb{R})$ such that $T(p)=p-p'$. Find all eigen values and eigen vectors of $T$.
Please someone help me with this problem. Thank you

A: I will assume $\mathcal{P}(\mathbb{R})$ is the set $\mathbb{R}[x]$ of polynomials with real coefficients. Then if $p$ is an eigenvector of $T$, we have $T p = p - p' = \lambda p$. By comparing the leading coefficients, we have that $\lambda =1$, so that $p'=0$, and $p=c$ for some constant $c$. Thus there is only one eigenvalue, $\lambda=1$, with corresponding eigenspace $\langle 1 \rangle$.


text:
Q: Python does not play mp4 and avi files This program does not play videos but the sound is okey.
I get an error about h264 or MJPG.When trying to play an .mp4 or .avi file I see the this messages.

main decoder error: Codec `MJPG' (Motion JPEG Video) is not supported.
main decoder error: Codec not supported
main decoder error: VLC could not decode the format "MJPG" (Motion
  JPEG Video)

or

main decoder error:Codec `h264' (H264 - MPEG-4 AVC (part 10)) is not
  supported.
main decoder error: Codec not supported
main decoder error: VLC could not decode the format "h264" (H264 -
  MPEG-4 AVC (part 10))

and this is my code
import vlc

from time import sleep

Instance = vlc.Instance('--fullscreen')
player = Instance.media_player_new()
Media = Instance.media_new('/home/onur/video_005.avi') #Media Location
Media.get_mrl()
player.set_media(Media)
player.play()

sleep(5) # Or however long you expect it to take to open vlc

while player.is_playing():
    sleep(1)


text:
Q: How to Preload the Next Page of a Website into the Browser I am looking to implement special functionality for my website, where loading a page that has multiple other consecutive pages (such as a search result) pre-loads the next page into the browser, accessible via the "forward" button. This sort of functionality is seen on the MSN News website; see the following screenshot.

I am looking to have this functionality implemented through JavaScript on a static deployment, as in, the server would just send everything client side. Is this at all possible? Where could I look for documentation for such a thing? I have already attempted to search for the answer to this inquiry elsewhere with no avail. Thanks in advance.

A: I'd avoid looking to use the forward button as its not a primary target but rather preload links on the page like the next button, but rather do it through something called InstaClick. If you're looking to specifically target the forward button itself best place to look is at the History API but thats browser specific. I've attached Mozillas doc on this.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
http://instantclick.io/
https://github.com/dieulot/instantclick


text:
Q: Convert xelatex to html I take this minimal example for document. I need 'polyglossia'.
\documentclass{article}

\usepackage{polyglossia}
%\usepackage[utf8]{inputenc}
\setdefaultlanguage{arabic}
\newfontfamily\arabicfont[Script=Arabic]{Scheherazade}
\setotherlanguage{english}
\begin{document}

شكرا

\begin{english} Thanks \end{english}

\end{document}

Compiling with 'xelatex' works and I get the correct pdf file.
How can I get the apropriate html file ?
I've tried  'hlxelatex' but I get this message:
(/usr/share/texmf-dist/tex/generic/tex4ht/html4-math.4ht)) (./polygl.aux)
! You can't use `\relax' after \the.
\NoHtmlEnv ....0pt\ht:everypar {\the \ht:everypar
                                                  }
l.8 \begin{document}

?

When I remove the arabic word شكرا
it also doesn't work, I have to remove the two lines in the preamble too, to get a html file.
I also tried 'tex4ht' and 'make4ht' with this simple file, I couldn't find a solution.
Any suggestions what to do or to try?

A: I was able to convert your file with slight change:
\documentclass{article}

\usepackage{fontspec}
\usepackage{polyglossia}
%\usepackage[utf8]{inputenc}
\setdefaultlanguage{arabic}

\newfontfamily\arabicfont{Scheherazade}[Script=Arabic]
\setotherlanguage{english}
\begin{document}

شكرا

\begin{english} Thanks \end{english}

شكرا

\end{document}

It seems there is an issue with Arabic support for Polyglossia in TeX4ht at the moment. It can be fixed with the following file, usepackage.4ht. It contains fixes that should be executed when the packages are loaded
% usepackage.4ht (2019-10-31-14:15), generated from tex4ht-4ht.tex
% Copyright 2003-2009 Eitan M. Gurari
% Copyright 2009-2019 TeX Users Group
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any
% later version. The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions
% of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% The Current Maintainer of this work
% is the TeX4ht Project <http://tug.org/tex4ht>.
%
% If you modify this program, changing the
% version identification would be appreciated.
\immediate\write-1{version 2019-10-31-14:15}

   \def\:temp{tex4ht}\ifx \:temp\@currname
   \:warning{\string\usepackage{tex4ht} again?}
   \def\:temp#1htex4ht.def,tex4ht.sty#2!*?: {\def\:temp{#2}}
\expandafter\:temp \@filelist htex4ht.def,tex4ht.sty!*?: %
\ifx \:temp\empty  \else
   \:warning{if
    \string\RequirePackage[tex4ht]{hyperref} or
    \string\usepackage[tex4ht]{hyperref} was
    used try instead, repectively,
    \string\RequirePackage{hyperref} or
    \string\usepackage{hyperref}}
\fi

\fi
\gdef\a:usepackage{\use:package
xr,xr-hyper,eso-pic,expl3,savetrees,biblatex,xeCJK,polyglossia,fontspec,tikz,pdfbase,graphics,xcolor,imakeidx,minted,fancyhdr,,!*?:
}
\gdef\use:package#1,{%
   \if :#1:\def\:temp##1!*?: {}\else
      \def\:temp{#1}\ifx \@currname\:temp
             \def\:temp##1!*?: {\input usepackage.4ht  }%
      \else \let\:temp=\use:package \fi
   \fi \:temp}
\def\:temp{xr}\ifx \@currname\:temp
   \AtEndOfPackage{\let\XR:\XR@
   \def\XR@[#1]#2{%
    \Configure{AtBeginDocument}{\XR:[#1]{#2}}{}}%
}

\fi
\def\:temp{xr-hyper}\ifx \@currname\:temp
   \AtEndOfPackage{\let\XR:\XR@
    \def\XR@[#1][#2]#3{%
      \AtBeginDocument{\XR:[#1][#2]{#3}}
    }%
}

\fi
\def\:temp{eso-pic}\ifx \@currname\:temp
\:dontusepackage{eso-pic}
\newcommand\AddToShipoutPicture{\@ifstar{}{}}
\let\AddToShipoutPictureBG\AddToShipoutPicture
\let\AddToShipoutPictureFG\AddToShipoutPicture
\fi
\def\:temp{expl3}\ifx \@currname\:temp
\ifdefined\XeTeXversion%
\xenunidelblock{Latin-expl3}%
\AtEndOfPackage{\xeuniuseblock{Latin-expl3}}
\fi
\fi
\def\:temp{savetrees}\ifx \@currname\:temp
\:dontusepackage{savetrees}
\fi
\def\:temp{biblatex}\ifx \@currname\:temp
\AtEndOfPackage{%
  \def\blx@mknoautolang{%
    \blx@lbxinput{\blx@languagename}%
    {}{}%
  }%
  \def\blx@lbxinput@iii#1#2{%
  \global\csundef{blx@lng@#2}%
  \:IfFileExists{#1.lbx}
    {\blx@lbxinput@iv{#2}{#1}{language '#2' -> '#1'}}
    {\ifcsdef{blx@suffmaptried@#2}
      {}
      {\blx@warning@noline{%
          File '#1.lbx' not found!\MessageBreak
          Ignoring mapping '#2' -> '#1'}%
       \global\cslet{blx@suffmaptried@#2}\@empty}%
     \blx@lbxinput@iv{#2}{#2}{language '#2'}}}

}
\fi
\def\:temp{xeCJK}\ifx \@currname\:temp
\:dontusepackage{xeCJK}
\AtEndOfPackage{%
  \RequirePackage{fontspec}
}
\DeclareDocumentCommand\setCJKmainfont{o m o}{}
\let\setCJKsansfont\setCJKmainfont
\let\setCJKmonofont\setCJKmainfont

\DeclareDocumentCommand\setCJKfamilyfont {m o m }{}
\DeclareDocumentCommand\newCJKfontfamily {o m o
m}{\expandafter\gdef\csname #2\endcsname{\relax}}

\DeclareDocumentCommand\xeCJKsetup{m}{}
% }
\AtBeginDocument{%
  \xeuniuseblock{CJK}
}
\fi
\def\:temp{polyglossia}\ifx \@currname\:temp
\ExplSyntaxOn
\AtEndOfPackage{

\cs_set_eq:NN\orig_polyglossia@keys_define_lang:n\polyglossia@keys_define_lang:n
\cs_set_protected:Npn \polyglossia@keys_define_lang:n #1 {
  \orig_polyglossia@keys_define_lang:n{#1}
  \keys_define:nn {polyglossia}{
    #1 / direction
    .  code:n = {}
}
}
\def\RequireBidi{}%
}
\ExplSyntaxOff
\fi

\def\:temp{fontspec}\ifx \@currname\:temp
  \ifdefined\fontspec
    \:dontusepackage{fontspec}
  \else
    \input usepackage-fontspec.4ht
  \fi
\fi
\def\:temp{tikz}\ifx \@currname\:temp
\AtEndOfPackage{%
\let\use:tikzlibrary\usetikzlibrary
\def\find:externalize#1external#2\@nil{%
\if\relax#2\relax\else
  \let\tikz:externalize\tikzexternalize
  \renewcommand\tikzexternalize[1][]{\tikz:externalize[##1,mode=only graphics]}
    \tikzset{%
      tex4ht inc/.style={%
        /pgf/images/include external/.code={%
          \includegraphics[]{####1.pdf}%
        }%
      }
    }
    \tikzset{tex4ht inc}
  \fi
}
\renewcommand\usetikzlibrary[1]{%
  \use:tikzlibrary{#1}%
  \find:externalize#1external\@nil%
}
}
\fi
\def\:temp{pdfbase}\ifx\@currname\:temp
\AtEndOfPackage{%
  \let\old:outputpage\@outputpage
  \def\@outputpage{\old:outputpage{}}
}
\fi
\def\:temp{graphics}\ifx\@currname\:temp
  \ifdefined\XeTeXversion
    \PassOptionsToPackage{dvips}{graphics}
  \fi
\fi
\def\:temp{xcolor}\ifx\@currname\:temp
  \ifdefined\XeTeXversion
    \PassOptionsToPackage{dvips}{xcolor}
  \fi
\fi
\def\:temp{imakeidx}\ifx\@currname\:temp
  \PassOptionsToPackage{noautomatic}{imakeidx}
\fi
\def\:temp{minted}\ifx\@currname\:temp
  \AtEndOfPackage{%
    \define@booleankey{minted@opt@g}{breaklines}{}{}{}%
  }
\fi
\def\:temp{fancyhdr}\ifx\@currname\:temp
  \AtEndOfPackage{%
  \def\ps@fancy{}%
  }
\fi

\endinput

With this change the document compiles. It is also necessary to fix the text direction. We can use a configuration file for this:
\Preamble{xhtml}
\Configure{LRdir}{ dir="rtl"}
\ConfigureEnv{english}{\bgroup\Configure{LRdir}{ dir="ltr"}}{\egroup}{}{}
\begin{document}
\EndPreamble

The LRdir configuration is used to configure the text direction. We define the RTL direction, used in Arabic as the main text direction. For English text the LTR direction will be used.
Compile using
 make4ht -ux -c config.cfg filename.tex

This is the result:


text:
Q: Check values in columns, allowing for not all columns being present I'm trying to clean up raw data exported from an online database.
There can be up to five columns. If all cells in a row have a value of 0, I want to delete that row.
When the user exports the data, they can choose to exclude columns, and the columns can be in any order.
For example, if the data contains only two of the possible five columns, I want to check just those two for 0s.

A: Could do a a big loop looking at every row and seeing if all 5 columns in that row are blank
Sub test()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("sheetname")
Dim LastRow As Integer
LastRow = sh.UsedRange.Rows.Count - 1

For i = 1 To LastRow
If (sh.Cells(i, 1).Value = "" And sh.Cells(i, 2).Value = "" And sh.Cells(i, 3).Value = "" And _
sh.Cells(i, 4).Value = "" And sh.Cells(i, 5).Value = "") Then
sh.Cells(i, 1).EntireRow.Delete
i = i - 1
Dim newLastRow As Integer
newLastRow = sh.UsedRange.Rows.Count - 1
If i = newLastRow Then
Exit For
End If
End If
Next i
MsgBox ("Done")
End Sub

A: @kyle campbell, thank you for your input!  It didn't quite get me there, but it did get my wheels turning.  Here is the solution I came up with, if anyone's curious:
I set a variable to represent the column number for each of the 5 possible columns using Range.Find.  If the Find came up with nothing, I set the variable to 49, since the maximum number of columns this report can have is 48.
Then I did a nested If to test if the value in each cell was either 0 or null (because if the column number is 49, there won't be any data there).  If all Ifs were true, I deleted the row.  I also added a counter and message box, just to make sure this worked.
Sub DeleteRows()

Dim O As Long
Dim E As Long
Dim H As Long
Dim B As Long
Dim P As Long

lRow = Range("A1").CurrentRegion.Rows.Count

If Range("1:1").Find("SUM(OBLIGATIONS)") Is Nothing Then
    O = 49
Else
    O = Range("1:1").Find("SUM(OBLIGATIONS)").Column
End If

If Range("1:1").Find("SUM(EXPENDITURES)") Is Nothing Then
    E = 49
Else
    E = Range("1:1").Find("SUM(EXPENDITURES)").Column
End If

If Range("1:1").Find("SUM(HOURS)") Is Nothing Then
    H = 49
Else
    H = Range("1:1").Find("SUM(HOURS)").Column
End If

If Range("1:1").Find("SUM(BUDGET_RESOURCES)") Is Nothing Then
    B = 49
Else
    B = Range("1:1").Find("SUM(BUDGET_RESOURCES)").Column
End If

If Range("1:1").Find("SUM(PRIOR_YEAR_RECOVERY)") Is Nothing Then
    P = 49
Else
    P = Range("1:1").Find("SUM(PRIOR_YEAR_RECOVERY)").Column
End If

Dim j As Integer
j = 0

For i = lRow To 2 Step -1
    If Cells(i, O) = 0 Or Cells(i, O) = "" Then
        If Cells(i, E) = 0 Or Cells(i, E) = "" Then
            If Cells(i, H) = 0 Or Cells(i, H) = "" Then
                If Cells(i, B) = 0 Or Cells(i, B) = "" Then
                    If Cells(i, P) = 0 Or Cells(i, P) = "" Then
                        Rows(i).Delete
                        j = j + 1
                    End If
                End If
            End If
        End If
    End If
Next i

MsgBox "Macro complete, " & j & " lines deleted."

End Sub


text:
Q: Using Swift 5 Libraries in a Swift 4 Project I am using Swift 4 version in my current project.
However, the Swift version of Cocoapods library is 5.
I can't downgrade the library because the latest version of the library has the features I want.
In addition, there are a lot of difficulties in raising the version of the project immediately.
I'm trying to modify the code in a library after installing the latest version of the library.
But the workload is very heavy.
Is there a good way?? Help me..

A: Try setting the pod swift version manually on the podfile:
post_install do |installer|
  installer.pods_project.targets.each do |target|
      if ['INSERT POD NAME HERE'].include? target.name
          target.build_configurations.each do |config|
              config.build_settings['SWIFT_VERSION'] = '4.0'
          end
      end
  end
end

If you get a syntax error from the pod, it means that the language is not compatible. Unfortunately xCode don't like backward compatibility very much.
Then, the only solution would be upgrade the project (maybe the swift migration assistant could help) or downgrade the lib, as you are doing right now.


text:
Q: Do i need to use AppCompatActivity for Android M I've to update an app to android version 6 to incorporate the new permissions functionality. but all the examples i see use AppCompatActivity.
https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
The app I'm updating' base class inherits from Activity. If i change this to use AppCompatActivity, the cascading effect is quite big. for one the OnMenuItemSelected(int featureId, IMenuItem item) is now sealed and i have to change to using OnOptionsItemSelected instead, and issues with the Themes.
Is it possible to use Activity as the base class and still request permissions in android 6. If so, is there an example, they all seem to use AppCompatActivity

A: It is, but you'll need to not call that API in any version of the framework below M.  So that means you'll need to write a function that checks the version and conditionally calls the request or not based on build id.
In general I think its best to use the compat version of any class in the compat library.  It tends to cause less pain down the road as new versions roll out.


text:
Q: Hide some shortcodes on posts from back-end I searched everywhere on the web and I didn't find something that could really help me. Here is my problem;
I use a plugin that provides shortcodes to show a file in a page or a post. For each file I need to write 2-3 shortcodes to change the 'url' part of that shortcode, and depends on the subdomain I am, I want to hide the shortcodes that aren't concerned. I tried some solutions;
First, put each shortcode into a div with a specific class then hide it. Failed
Second, try to add directly a class in the shortcode, try to find it and replace it by an empty string. Failed
Third, try to find the shortcode by the name and modify its url (so an unique shortcode per file). Failed
I don't know which code could work, I took it from some websites (this one and this one for example) and tried to 'mix' them, but it hasn't worked like I would..
Does someone have a solution ?

A: Check it like this inside your php file:
if($_SERVER["HTTP_HOST"] == "product1.domain.com") { // check the current domain
// your shortcode here. use do_shortcode to display the shorcode
}

I can help better if you post the codes that handle the shortcode.


text:
Q: Is a Data Adapter always needed? If have a query that I ONLY want to execute, and have no need to fill any data within a table, then is it necessary to have a data adapter for that purpose?

A: No it is not necessary to use a SqlDataAdapter. Its really a bridge between a DataSet and Sql Server.
Instead you can use SqlCommand - ExecuteNonQuery.

You can use the ExecuteNonQuery to perform catalog operations (for
  example, querying the structure of a database or creating database
  objects such as tables), or to change the data in a database without
  using a DataSet by executing UPDATE, INSERT, or DELETE statements.
  Although the ExecuteNonQuery returns no rows, any output parameters or
  return values mapped to parameters are populated with data.

using (SqlConnection conn = new SqlConnection(
           "your connection string"))
{
      using (SqlCommand command = new SqlCommand("your sql", conn)
      {
        conn.Open();
        command.ExecuteNonQuery();
      }
}


text:
Q: Producing a list of media library items categorized under a certain taxonomy item I created a custom taxonomy called "Reference Type" which is used to categorize media library items. In the taxonomy.php page, I want to produce a list of all media library items that are categorized under "Reference Type". How would I go about doing this?

A: You can use a tax query for all "Reference Type" terms, which will retrieve all attachments that have at least one "Reference Type" term.
$rt_media = new WP_Query(
    array(
        'posts_per_page' => -1,
        'post_type' => 'attachment',
        'tax_query' => array(
            array(
                'taxonomy' => 'reference_type',
                'terms' => get_terms(
                    'reference_type',
                    array(
                        'hide_empty' => false,
                        'fields' => 'ids',
                    )
                )
            )
        )
    )
);

while ( $rt_media->have_posts() ) : $rt_media->the_post(); ?>

    <div class="item">
        Use any template tags you want to output the list!
    </div>

<?php endwhile ?>


text:
Q: How to find all callers of all methods in a specified class? I'm looking for a way to output into file all methods, that are calling all methods in a specified class. I see that I could use ASM for this, but I cannot figure it out.
Example:
class A has methods aA, bA, cA.
class B calls methods aB -> aA, bB -> bA, cB -> cA.
I want to output "aB -> aA, bB -> bA, cB -> cA" into file.
My main goal is to trace all these calls from ExceptionFactory to service layer, and then output which service methods can throw specific exceptions.
The most suitable way for me would be, that it would run as a test, the file would be created during test phase.
EDIT: I actually don't know what class B is, I need to find out which class/classes calls class A.

A: You can achieve something like above in your question by making use of JavaAssist library as given here : Java Assist - Java bytecode engineering toolkit
This Jar file provides you with methods that can help you inspect your classes and its methods much more deeply to fetch that kind of information (i.e , methods in a given class are invoking method from which particular class) . For example , lets take example of this class A as below :
public class A {

    void meth1()
    {
        System.out.println("meth1 A");
    }

    void meth2()
    {
        System.out.println("meth2 A");
    }

    void meth3()
    {
        System.out.println("meth3 A");
    }
}

Now , let's take another class B , which has also 3 methods . Inside each of these 3 methods , methods of A are being called as below :
public class B {

    A a =new A();
    void meth1()
    {
        System.out.println("meth1 B");
        a.meth1();
    }

    void meth2()
    {
        System.out.println("meth2 B");
        a.meth2();
    }

    void meth3()
    {
        System.out.println("meth3 B");
        a.meth3();
    }
}

As you can see , methods in class B are invoking methods of class A from inside them . Now, we can make use of methods of JavaAssist library as shown below , to fetch the information that from each method of class B , which method of A has been called ? The method.instrument construct from the JavaAssist library allows you to build a bytecode manipulation expression , which helps you to list methods invoked per method and the classes to which those method belong . As a demo for your problem , i am adding the mapping to the method invocations in the methodToInvokedMethodMap , where key is the source class method from where method is being invoked , and value is the method which class information that is being invoked from inside method B , just like you asked in your question :) . Adding the code for the class C , which displays this mapping as below :
import javassist.*;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class C {

    static Map<String, String> methodToInvokedMethodMap = new HashMap<>();

    public static void main(String[] args) throws NotFoundException, CannotCompileException {

        Class thisClass = B.class;
        Method[] methods = thisClass.getDeclaredMethods();

        for (int i = 0; i < methods.length; i++) {

            ClassPool cp = ClassPool.getDefault();
            CtClass ctClass = cp.get("B");

            String currentMethod = methods[i].getName().toString();
            CtMethod method = ctClass.getDeclaredMethod(methods[i].getName().toString());
            method.instrument(new ExprEditor() {
                public void edit(MethodCall m) throws CannotCompileException {

                    if (m.getClassName().equals("A")) {
                        methodToInvokedMethodMap.put("Class B method " + currentMethod, m.getClassName() + " with name as : " + m.getMethodName());
                    }
                }
            });

            methodToInvokedMethodMap.forEach((key, value) -> {
                System.out.println(key + " invokes method from class " + value);
            });
        }
    }
}

You can further explore JavaAssist library to find out different methods to serve your usecase . Also , in your Spring Boot project you can use this Jar as it is , or you can convert this jar as a Maven Dependency in your project and use it as a dependency via your pom.xml file . Hope this helps you resolve the problem you asked for :) .
Also , i'm attaching here how the output looks like for this :

A: Attach a debugger to your running application and set some breakpoints using your IDE to the methods where you want to know the calling classes of. Then configure these breakpoint to log/write the information you want to some file (In eclipse you can find this under "Conditional" in the breakpoint properties, in IntelliJ the breakpoint properties have an "Evaluate and Log" section for example).
In these breakpoints you can for example use Thread.currentThread().getStackTrace() to access the stack trace and collect the information you want from the result.

A: Here is a variant that doesn't need a running application.
Open the project in eclipse. If you don't have a project for your application create a new java project and add everything from the classpath of your application to the new java project.
Then search for the methods you want to collect the callers. Then for each of those use "References" -> "Project" to find those. In the resulting search view select "Show as List" from the view options and adopt search preferences and filters to adapt the result to your needs. Then select every match in the view and just copy this to a file.
The file will look something like this (shown are references to java.lang.Thread#interrupt()):
acquireRead(boolean, long) (4 matches) - java.util.concurrent.locks.StampedLock
afterReadLine() - jline.console.ConsoleReader
append(LoggingEvent) - org.apache.log4j.AsyncAppender
append(LoggingEvent) - org.apache.log4j.net.SocketAppender
apply(Source, Target, List<? extends Factory>) - net.bytebuddy.build.Plugin.Engine.Default
awaitTermination(ExecutorService) - org.apache.solr.common.util.ExecutorUtil
cleanUp() - org.apache.log4j.net.SocketHubAppender
close() - com.mchange.v1.util.SimpleRunnableQueue
close() - com.zaxxer.hikari.HikariDataSource
close() - org.apache.solr.client.solrj.impl.ConcurrentUpdateHttp2SolrClient
closeKeeper(SolrZooKeeper) - org.apache.solr.common.cloud.SolrZkClient
createTimeoutException(Thread) - org.junit.internal.runners.statements.FailOnTimeout
doConfigure(ParseAction, LoggerRepository) - org.apache.log4j.xml.DOMConfigurator

This method won't find reflection based calls.


text:
Q: Disable all mouse events for NSView How do I disable all mouse events to a specific NSView(and all its subviews)
For eg: In following image,
I have a scrollView and a border view(say MyBorderView) over it
The functionality I want to acheive is to disable all mouse events to scroll view when button is pressed.
My fix to it is to override mouseDown and rightMouseDown event of NSView. This seems to work fine but fails for scroll.
In simple words, I want to achieve some thing like [_scrollView disableAllMouseEvents]

A: Override the method:
- (void)scrollWheel:(NSEvent *)theEvent;

For example, you have a boolean variable disableEvents for enable or disable events in your scroll view. The code will be:
- (void)scrollWheel:(NSEvent *)theEvent
{
    // No disable events ---> disableEvents = NO
    if (!disableEvents) {
        [super scrollWheel:theEvent];
    }
}

If you set disableEvents = YES the scroll will be disabled. On the other hand, you need disable the scrollers too or the scroll works moving them:
[self setHorizontalScroller:nil];
[self setVerticalScroller:nil];

If you need reverse the scrollers later, just write:
NSScroller *scrollerHorizontal = [[NSScroller alloc]init];
NSScroller *scrollerVertical = [[NSScroller alloc]init];

[self setHorizontalScroller:scrollerHorizontal];
[self setVerticalScroller:scrollerVertical];

Good luck!


text:
Q: What measures should go into fact tables (SSMS) I am trying to develop a multi-dimensional database. I am a little confused in what measures are included in the facts table.
Data-Set - https://www.kaggle.com/johnolafenwa/us-census-data
Currently, These are my dimensions tables
**Person Table**
    personID INT PRIMARY KEY IDENTITY,
    age_group varchar(20) NOT NULL,
    age INT NOT NULL,
    gender varchar(20) NOT NULL,
    race varchar(20) NOT NULL,
    relationship varchar(20) NOT NULL,
    martial_status varchar(20) NOT NULL,

**Education Table**
    educationID INT PRIMARY KEY IDENTITY,
    education_num INT NOT NULL,
    education varchar(20) NOT NULL,
    education_level varchar(20) NOT NULL,

**Employment Table**
    employmentID INT PRIMARY KEY,
    occupation varchar(20) NOT NULL,
    workclass varchar(20) NOT NULL,
    is_Government varchar(20) NOT NULL,
    hours_per_week INT NOT NULL,

**Income Table**
    incomeID INT PRIMARY KEY,
    capital_loss INT NOT NULL,
    capital_gains INT NOT NULL,
    greater_then_50K varchar(5) NOT NULL,

I'm very confused in what to measure. For instance, how many measures should be there? These were some I was thinking of to answer business questions:
total_capital_gains AND total_capital_loss (additive)
average_capital_gains AND average_capital_loss (semi-additive)
total_hours_per_week (additive)
average_hours_per_week (semi-additive)
Trying to understand what these measures would look like in their grain. For example, the finest grain would be per person. The next roll up would be possible per age group etc..
I understand that percentage can be a good measure, but I am not sure what ratio I should check.
Sorry if I am asking the wrong question, but I am really stuck on this concept.
Thanks


text:
Q: Функция удаляющая пробелы в строке Здравствуйте, написал функцию которая удаляет пробелы в строке, но в некоторых ситуациях она не выводит последний символ.
#include <stdio.h>
#include <string.h>
#define SIZE 81
#define LIM 20

void delSpace(char * str);

int main(void)
{
    int i = 0;
    char string[LIM][SIZE];

    puts("Input text:");

    while (i < LIM && gets(string[i]) != NULL && string[i][0] != '\0')
    {
        delSpace(string[i]);
        puts(string[i]);
        i++;
    }
    puts("Goodbye!");

    return 0;
}
void delSpace(char * str)
{
    int i, j;
    int len = strlen(str);
    char temp[len];

    for (i = 0, j = 0; i < len - 1; i++)
    {
        if (str[i] == ' ')
        {
            if (str[i + 1] == ' ')
            {
                i++;
                continue;
            }
            else
            {
                temp[j] = str[++i];
                j++;
            }
        }
        else
        {
            temp[j] = str[i];
            j++;
        }
    }
    for (i = 0; i < j; i++)
        str[i] = temp[i];
    str[i] = '\0';
}

Вот результат вывода:

Вообщем всегда когда строка заканчивается одним символом, вывод нормальный, а когда последнее слово более одного символа, то последний не выводится.
(PS) И нормально ли вообще работает оператор i++; в этом фрагменте кода:
  if (str[i + 1] == ' ')
  {
      i++;
      continue;
  }

Подскажите пожалуйста в чем ошибка?

A: Последний символ теряется из-за условия цикла i < len - 1, поскольку он не доходит до конца из-за одновременного знака меньше и вычитания единицы.
В случае, когда перед последним символом стоит пробел, последний символ будет сохранен за счет внутренней ветки else:
...
else
{
    temp[j] = str[++i];
    j++;
}
...

Честно говоря, не очень понятно, зачем нужны все эти внутренние проверки наличия двойных пробелов, но обычную функцию по удалению пробелов я бы написал как-то так:
void delSpace(char * str)
{
    int i, j;
    int len = strlen(str);

    for (i = 0, j = 0; i < len; i++)
        if (str[i] != ' ')
            str[j++] = str[i];
    str[j] = '\0';
}


text:
Q: Hover popup shows wrong/duplicate rep for week/month/etc in user profile page I posted a similar question on Meta.English.SE before I realized the problem extended to other sites as well.  I'll pick on SO for the images here, though I can repro this behavior in  any other site.  In the user page, in the voters or editors tabs, in any view except all, hovering over the rep of any user brings up a popup such as the following:

And when the user's rep is less than 10000, it appears like this:

Not sure why, but the rep tab has no problems in any view:

A: Thanks, this will be fixed in the next build.