text:
Q: Changing boolean value with React Bootstrap checkbox and hooks Trying to change the isVegan object (nested boolean) with React Bootstrap checkbox and hooks. I can access the object without any issues (e.g. checkbox is checked if isVegan is true), but have been unable to modify the state. As you can see in the Redux dev tools (image link included), the isVegan object is passed through my state and is accessible. I have also used similar code for the other objects in the chef collection without any issues so believe the issue is either related to the checkbox or how the isVegan object is nested in the chef collection. (Lastly, I know some of the code below may be extra, I slimmed down my original file to simplify this example)
import React, { useState, useEffect, setState } from 'react';
import { Form, Button, Row, Col, Tabs, Tab } from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import { getChefDetails, updateChefProfile } from '../../actions/chefActions';
import { CHEF_UPDATE_PROFILE_RESET } from '../../constants/chefConstants';
import FormContainer from '../../components/FormContainer/FormContainer.component';

import './ProfileEditPage.styles.scss';

const ProfileEditPage = ({ location, history }) => {
  const [first_name, setFirstName] = useState('')
  const [last_name, setLastName] = useState('')
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [isVegan, setIsVegan] = useState('')
  const [bio, setBio] = useState('')
  const [message, setMessage] = useState(null)

  const dispatch = useDispatch()

  const chefDetails = useSelector(state => state.chefDetails)
  const { loading, error, chef } = chefDetails

  const chefLogin = useSelector(state => state.chefLogin)
  const { chefInfo } = chefLogin

  const chefUpdateProfile = useSelector(state => state.chefUpdateProfile)
  const { success } = chefUpdateProfile

  useEffect(() => {
    if(!chefInfo) {
      history.push('/login')
    } else {
      if(!chef || !chef.username || success) {
        dispatch({ type: CHEF_UPDATE_PROFILE_RESET })
        dispatch(getChefDetails('profile'))
      } else {
        setFirstName(chef.first_name)
        setLastName(chef.last_name)
        setUsername(chef.username)
        setEmail(chef.email)
        setBio(chef.bio)
        setIsVegan(chef.isVegan)
      }
    }
  }, [dispatch, history, chefInfo, chef, success])

  const submitHandler = (e) => {
    e.preventDefault()
    if (password !== confirmPassword) {
      setMessage('Passwords do not match')
    } else {
      dispatch(updateChefProfile({
        id: chef._id,
        first_name,
        last_name,
        username,
        email,
        password,
        bio,
        isVegan
      }))
    }
  }

  const [key, setKey] = useState('auth')

  //const isVegan = chef.diets[0].isVegan
  //const isVegetarian = chef.diets[0].isVegetarian

  console.log(isVegan)

  return (
    <FormContainer className="profileEditPage">

Chef Profile

      <Form className='profileEditPageForm' onSubmit={submitHandler}>
        <Tabs id="profileEditPageTabs" activeKey={key} onSelect={(k) => setKey(k)}>
          <Tab eventKey='auth' title="Auth">
            <Form.Group controlId='first_name'>
              <Form.Label>First Name</Form.Label>
              <Form.Control
                type='text'
                placeholder='Enter your first name'
                value={first_name}
                onChange={(e) => setFirstName(e.target.value)}
                required
              >
              </Form.Control>
            </Form.Group>

            <Form.Group controlId='last_name'>
              <Form.Label>Last Name</Form.Label>
              <Form.Control
                type='text'
                placeholder='Enter your last name'
                value={last_name}
                onChange={(e) => setLastName(e.target.value)}
                required
              >
              </Form.Control>
            </Form.Group>

            <Form.Group controlId='username'>
              <Form.Label>Username</Form.Label>
              <Form.Control
                type='text'
                placeholder='Enter a username'
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
              >
              </Form.Control>
              <Form.Text className='muted'>Your username will be public</Form.Text>
            </Form.Group>

            <Form.Group controlId='email'>
              <Form.Label>Email</Form.Label>
              <Form.Control
                type='email'
                placeholder='Enter your email'
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              >
              </Form.Control>
            </Form.Group>

            <Form.Group controlId='password'>
              <Form.Label>Password</Form.Label>
              <Form.Control
                type='password'
                placeholder='Enter your password'
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              >
              </Form.Control>
            </Form.Group>

            <Form.Group controlId='confirmPassword'>
              <Form.Label>Confirm Password</Form.Label>
              <Form.Control
                type='password'
                placeholder='Confirm password'
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
              >
              </Form.Control>
            </Form.Group>
          </Tab>
          <Tab eventKey='chef-detail' title="Chef Detail">
            <Form.Group controlId='isVegan'>
              <Form.Check
                type='checkbox'
                label='Vegan?'
                checked={isVegan}
                value={isVegan}
                onChange={(e) => setIsVegan(e.target.checked)}
              />
            </Form.Group>

            <Form.Group controlId='bio'>
              <Form.Label>Chef Bio</Form.Label>
              <Form.Control
                as='textarea'
                rows='5'
                maxLength='240'
                placeholder='Enter bio'
                value={bio}
                onChange={(e) => setBio(e.target.value)}
              >
              </Form.Control>
              <Form.Text className='muted'>Your bio will be public</Form.Text>
            </Form.Group>
          </Tab>
        </Tabs>

        <Button type='submit' variant='primary'>
          Update
        </Button>
      </Form>

    </FormContainer>

  )
}

export default ProfileEditPage;

Actions
export const getChefDetails = (id) => async (dispatch, getState) => {
  try {
    dispatch({
      type: CHEF_DETAILS_REQUEST
    })

    const { chefLogin: { chefInfo} } = getState()

    const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${chefInfo.token}`
      }
    }

    const { data } = await axios.get(
      `/api/chefs/${id}`,
      config
    )

    dispatch({
      type: CHEF_DETAILS_SUCCESS,
      payload: data
    })

  } catch (error) {
    dispatch({
      type: CHEF_DETAILS_FAILURE,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    })
  }
}

export const updateChefProfile = (chef) => async (dispatch, getState) => {
  try {
    dispatch({
      type: CHEF_UPDATE_PROFILE_REQUEST
    })

    const { chefLogin: { chefInfo } } = getState()

    const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${chefInfo.token}`
      }
    }

    const { data } = await axios.put(
      `/api/chefs/profile`,
      chef,
      config
    )

    dispatch({
      type: CHEF_UPDATE_PROFILE_SUCCESS,
      payload: data
    })

    dispatch({
      type: CHEF_LOGIN_SUCCESS,
      payload: data
    })

    localStorage.setItem('chefInfo', JSON.stringify(data))

  } catch (error) {
    dispatch({
      type: CHEF_UPDATE_PROFILE_FAILURE,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    })
  }
}

Reducers
export const chefDetailsReducer = (state = { chef: { } }, action) => {
  switch(action.type) {
    case CHEF_DETAILS_REQUEST:
      return { ...state, loading: true }
    case CHEF_DETAILS_SUCCESS:
      return { loading: false, chef: action.payload }
    case CHEF_DETAILS_FAILURE:
      return { loading: false, error: action.payload }
    case CHEF_DETAILS_RESET:
      return {
        chef: {}
      }
    default:
      return state
  }
}

export const chefUpdateProfileReducer = (state = { }, action) => {
  switch(action.type) {
    case CHEF_UPDATE_PROFILE_REQUEST:
      return { loading: true }
    case CHEF_UPDATE_PROFILE_SUCCESS:
      return { loading: false, success: true, chefInfo: action.payload }
    case CHEF_UPDATE_PROFILE_FAILURE:
      return { loading: false, error: action.payload }
    case CHEF_UPDATE_PROFILE_RESET:
      return { }
    default:
      return state
  }
}

Controller
// @description Get chef profile
// @route GET /api/chefs/profile
// @access Private
const getChefProfile = asyncHandler(async (req, res) => {
  const chef = await Chef.findById(req.chef._id)

  if(chef) {
    res.json({
      _id: chef._id,
      first_name: chef.first_name,
      last_name: chef.last_name,
      username: chef.username,
      email: chef.email,
      bio: chef.bio,
      isVegan: chef.isVegan
    })
  } else {
    res.status(404)
    throw new Error('Chef not found')
  }
})

// @description Update chef profile
// @route PUT /api/chefs/profile
// @access Private
const updateChefProfile = asyncHandler(async (req, res) => {
  const chef = await Chef.findById(req.chef._id)

  if(chef) {
    chef.first_name = req.body.first_name || chef.first_name
    chef.last_name = req.body.last_name || chef.last_name
    chef.username = req.body.username || chef.username
    chef.email = req.body.email || chef.email
    chef.bio = req.body.bio || chef.bio
    chef.isVegan = req.body.isVegan || chef.isVegan

    if (req.body.password) {
      chef.password = req.body.password
    }

    const updatedChef = await chef.save()

    res.json({
      _id: updatedChef._id,
      first_name: updatedChef.first_name,
      last_name: updatedChef.last_name,
      username: updatedChef.username,
      email: updatedChef.email,
      bio: updatedChef.bio,
      isVegan: updatedChef.isVegan,
      token: generateToken(updatedChef._id),
    })

  } else {
    res.status(404)
    throw new Error('Chef not found')
  }
})

A: Issue
After much back and forth I believe the issue is with how the response "payload" is stored back in state by the reducer. The response object is a flat object with isVegan at the root, but in state isVegan is in a nested diets array.
res.json({
  _id: updatedChef._id,
  first_name: updatedChef.first_name,
  last_name: updatedChef.last_name,
  username: updatedChef.username,
  email: updatedChef.email,
  bio: updatedChef.bio,
  isVegan: updatedChef.isVegan,
  token: generateToken(updatedChef._id),
})

The reducer takes the payload and also saves it directly to a chefInfo property and overwriting any existing data.
export const chefUpdateProfileReducer = (state = { }, action) => {
  switch(action.type) {
    ...

    case CHEF_UPDATE_PROFILE_SUCCESS:
      return { loading: false, success: true, chefInfo: action.payload }

    ...
  }
}

Solution
Reducer should merge in response payload. In your redux screenshot I don't see a chefInfo key so I'll write this to match the screenshot as closely as possible.
export const chefUpdateProfileReducer = (state = { }, action) => {
  switch(action.type) {
    ...

    case CHEF_UPDATE_PROFILE_SUCCESS:
      const {
        _id,
        isVegan,
        token,
        ...chefDetails // i.e. first & last name, username, email, bio
      } = action.payload;

      return {
        ...state, // <-- shallow copy state
        loading: false,
        success: true,
        chef: {
          ...state.chef, // <-- shallow copy existing chef details
          ...chefDetails, // shallow copy new chef details
          diets: state.chef.diets.map(diet => diet._id === _id ? { // <-- map existing state
            ...diet, // <-- shallow copy diet object
            isVegan // <-- overwrite isVegan property
          } : diet),
        },
      };

    ...
  }
}

Note: This is a best guess to state structures and types since your reducers appear to have a very minimally defined initial state, so this likely needs to be tweaked to fits your exact state structure.


text:
Q: Searching through map using user input does not work This is what I need;
The user inputs a key value and a number; For instance "SK1 > 34"
The system then uses the key value from this to search through a map list called "mapdata". This is a "Map(String, List[Int])"
This value is returned with only the last digit.
However the problem I have is that when the system uses the key value to search the map, it fails to find it, even though the key value inputted is in the map.
If I change the user stackCost to direct entering "SK1" then it works. This shows me the problem is in finding "stockValue" even though my test shows it is searching for SK1.
Here is my current code;
def addNewStock =
  {
    println("Enter stock as *SK1* > AMOUNT(8) and the stock level will be taken from the stocks*")
    print("Enter new Stock > ")
    val key = readLine()
    var result = key.split(";").map(_ split ">") collect { case Array(k, v) => (k, v) } toMap

    println ("Data entered into file " + result)
    //String.valueOf(
    var stockValue = String.valueOf(result.head._1)
    var stockCost = mapdata.get(stockValue)

    println("This is the stock value " + stockValue)
    println("This is the stock cost " + stockCost)

  }

mapdata that is being queried;
SK1, 9, 7, 2, 0, 7, 3, 7, 9, 1, 2, 8, 1, 9, 6, 5, 3, 2, 2, 7, 2, 8, 5, 4, 5, 1, 6, 5, 2, 4, 1
SK2, 0, 7, 6, 3, 3, 3, 1, 6, 9, 2, 9, 7, 8, 7, 3, 6, 3, 5, 5, 2, 9, 7, 3, 4, 6, 3, 4, 3, 4, 1
SK4, 2, 9, 5, 7, 0, 8, 6, 6, 7, 9, 0, 1, 3, 1, 6, 0, 0, 1, 3, 8, 5, 4, 0, 9, 7, 1, 4, 5, 2, 8
SK5, 2, 6, 8, 0, 3, 5, 5, 2, 5, 9, 4, 5, 3, 5, 7, 8, 8, 2, 5, 9, 3, 8, 6, 7, 8, 7, 4, 1, 2, 3
SK6, 2, 7, 5, 9, 1, 9, 8, 4, 1, 7, 3, 7, 0, 8, 4, 5, 9, 2, 4, 4, 8, 7, 9, 2, 2, 7, 9, 1, 6, 9
SK7, 6, 9, 5, 0, 0, 0, 0, 5, 8, 3, 8, 7, 1, 9, 6, 1, 5, 3, 4, 7, 9, 5, 5, 9, 1, 4, 4, 0, 2, 0
SK8, 2, 8, 8, 3, 1, 1, 0, 8, 5, 9, 0, 3, 1, 6, 8, 7, 9, 6, 7, 7, 0, 9, 5, 2, 5, 0, 2, 1, 8, 6
SK9, 7, 1, 8, 8, 4, 4, 2, 2, 7, 4, 0, 6, 9, 5, 5, 4, 9, 1, 8, 6, 3, 4, 8, 2, 7, 9, 7, 2, 6, 6

EDITS***
var testing = result.toList
var stockValue = String.valueOf(result.head._1)
var stockCost = mapdata.get(stockValue).toList
var stockCheck = stockCost.map(_.lastOption.getOrElse(0))
var result2 = testing ::: stockCheck

A: The problem is in your test string. You are using the string "SK1 > 34" to test. When you call split(">") on this string, you will get back a Array("SK1 ", " 34"). Notice how there are spaces in both of those strings. This means that when you query mapdata, you are using the string "SK1 " (with a space at the end), which clearly is not a key in your map (because "SK1 " != "SK1"). A more appropriate test string for this use case would be "SK1>34".

redpajama_set_name: RedPajamaStackExchange


text:
Q: lazarus version issue I installed Lazarus 1.0.10 from Ubuntu, but installed FPC-SRC 2.6.2 from SourceForge.
I got down grade to 1.0.10 when I first run Lazarus after that I got leaks package does not exist every time I run Lazarus. I would like to know if it is possible to un install and re install to fix the issue?
Your help and information is great appreciated,
Regards,
Inung


text:
Q: Print the dictionary value and key(index) in python I am trying to write a code which inputs a line from user, splits it and feed it up to majestic dictionary named counts. All is well until we ask her majesty for some data. I want the data in the format such that the word is printed first and number of times it repeats printed next to it. Below is the code I managed to write.
counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for wording in counts:
    print('trying',counts[wording], '' )

When it executes its output is unforgivable.
Words: ['You', 'will', 'always', 'only', 'get', 'an', 'indent', 'error', 'if', 'there', 'is', 'actually', 'an', 'indent', 'error.', 'Double', 'check', 'that', 'your', 'final', 'line', 'is', 'indented', 'the', 'same', 'was', 'as', 'the', 'other', 'lines', '--', 'either', 'with', 'spaces', 'or', 'with', 'tabs.', 'Most', 'likely,', 'some', 'of', 'the', 'lines', 'had', 'spaces', '(or', 'tabs)', 'and', 'the', 'other', 'line', 'had', 'tabs', '(or', 'spaces).']
Counting:
trying 1
trying 1
trying 1
trying 1
trying 1
trying 2
trying 2
trying 1
trying 1
trying 1
trying 2
trying 1
trying 1
trying 1
trying 1
trying 1
trying 1
trying 1
trying 2

It just prints trying and number of times it is repeated and without the word(I think it is called index in dictionary, correct me if I am wrong)
Thankyou

Please help me and when replying to this question please keep in mind I am a newbie, both to python and stack overflow.

A: Nowhere in your code do you attempt to print the word.  How did you expect it to appear in the output?  If you want the word, put it in the list of things to print:
print(wording, counts[wording])

For more education, look up the package collections, and use the Counter construct.
counts = Counter(words)

will do all of your word counts for you.

A: You should use counts.items() to iterate over the key and value of counts as follows:
counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for word, count in counts.items(): # notice this!
    print(f'trying {word} {count}')

Also notice that you can use an f-string when printing.

A: I'm confuzled as to why you print trying.
Try this instead.
counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for wording in counts:
    print(wording,counts[wording], '' )

A: The code you have iterates over the dictionary keys and prints only the count in the dictionary. You would want to do something like this:
for word, count in counts.items():
    print('trying', word, count)

You might also want to use
from collections defaultdict
counts = defaultdict(lambda: 0)

So while adding to the dictionary, the code would be as simple as
counts[word] += 1


text:
Q: Using "Next" as a Return Key I use the "Next" value for the "Return Key" to get the Next button in place of the Done button, but (obviously) pressing it doesn't automatically move to the next UITextField in my view.
What's the right way to do this? I have seen many answers, but anyone have a swift solution?

A: Make sure your text fields have their delegate set and implement the textFieldShouldReturn method.  This is the method that is called when the user taps the return key (no matter what it looks like).
The method might look something like this:
func textFieldShouldReturn(textField: UITextField) -> Bool {
    if textField == self.field1 {
        self.field2.becomeFirstResponder()
    }

    return true
}

The actual logic in here might vary.  There are numerous approaches, and I'd definitely advise against a massive if/else chain if you have lots of text fields, but the gist here is to determine what view is currently active in order to determine what view should become active.  Once you've determined which view should become active, call that view's becomeFirstResponder method.

For some code cleanliness, you might consider a UITextField extension that looks something like this:
private var kAssociationKeyNextField: UInt8 = 0

extension UITextField {
    var nextField: UITextField? {
        get {
            return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UITextField
        }
        set(newField) {
            objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN)
        }
    }
}

And then change our textFieldShouldReturn method to look like this:
func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.nextField?.becomeFirstResponder()
    return true
}

Once you've done this, it should simply be a matter of setting each text field's new nextField property in viewDidLoad:
self.field1.nextField = self.field2
self.field2.nextField = self.field3
self.field3.nextField = self.field4
self.field4.nextField = self.field1

Although if we really wanted, we could prefix the property with @IBOutlet, and that would allow us to hook up our "nextField" property right in interface builder.
Change the extension to look like this:
private var kAssociationKeyNextField: UInt8 = 0

extension UITextField {
    @IBOutlet var nextField: UITextField? {
        get {
            return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UITextField
        }
        set(newField) {
            objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN)
        }
    }
}

And now hook up the nextField property in interface builder:

(Set up your delegate while you're here too.)

And of course, if the nextField property returns nil, the keyboard just hides.

A: Here is an example in Swift:
I created a screen with 6 UITextFields.  I assigned them the tags 1 through 6 in Interface Builder.  I also changed the Return key to Next in IB.  Then I implemented the following:
import UIKit

// Make your ViewController a UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {

    // Use a dictionary to define text field order 1 goes to 2, 2 goes to 3, etc.
    let nextField = [1:2, 2:3, 3:4, 4:5, 5:6, 6:1]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Make ourselves the delegate of the text fields so that textFieldShouldReturn
        // will be called when the user hits the Next/Return key
        for i in 1...6 {
            if let textField = self.view.viewWithTag(i) as? UITextField {
                textField.delegate = self
            }
        }
    }

    // This is called when the user hits the Next/Return key
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        // Consult our dictionary to find the next field
        if let nextTag = nextField[textField.tag] {
            if let nextResponder = textField.superview?.viewWithTag(nextTag) {
                // Have the next field become the first responder
                nextResponder.becomeFirstResponder()
            }
        }
        // Return false here to avoid Next/Return key doing anything
        return false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

A: There is nothing wrong with the other answers, this is just a different approach with the benefit of being more focused on OOP - imho (although this is a bit more work up front, it can be reused). In the storyboard, I start off adding tags with a distinct range (e.g 800-810) that define the specific order of the fields I want to move between. This has the benefit of working across all subviews in the main view so that one can navigate between UITextField's and UITextView's (and any other control) as needed.
Generally - I typically try to have view controllers message between views and custom event handler objects. So I use a message (aka, NSNotification) passed back to the view controller from a custom delegate class.
(TextField Delegate Handler)

Note: In AppDelegate.swift: let defaultCenter = NSNotificationCenter.defaultCenter()

//Globally scoped
struct MNGTextFieldEvents {
    static let NextButtonTappedForTextField = "MNGTextFieldHandler.NextButtonTappedForTextField"
}

class MNGTextFieldHandler: NSObject, UITextFieldDelegate {

    var fields:[UITextField]? = []

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        return true
    }
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.backgroundColor = UIColor.yellowColor()
    }
    func textFieldDidEndEditing(textField: UITextField) {
        textField.backgroundColor = UIColor.whiteColor()
    }
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        return true
    }
    func textFieldShouldClear(textField: UITextField) -> Bool {
        return false
    }
    func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        return true
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {

        //passes the message and the textField (with tag) calling the method
        defaultCenter.postNotification(NSNotification(name: MNGTextFieldEvents.NextButtonTappedForTextField, object: textField))

        return false
    }
}

This allows my view controller to remain focused on it's main job of handling the messaging between objects, model and view.
(View Controller receives a message from the delegate and passes instructions using the advanceToNextField function)

Note: In my storyboard my custom handler classes are defined using an NSObject and that object is linked into the storyboard as a delegate for the controls that I need monitored. Which causes the custom handler class to be initialized automatically.

class MyViewController: UIViewController {
    @IBOutlet weak var tagsField: UITextField! { didSet {
        (tagsField.delegate as? MNGTextFieldHandler)!.fields?.append(tagsField)
        }
    }
    @IBOutlet weak var titleField: UITextField!{ didSet {
        (titleField.delegate as? MNGTextFieldHandler)!.fields?.append(titleField)
        }
    }
    @IBOutlet weak var textView: UITextView! { didSet {
     (textView.delegate as? MNGTextViewHandler)!.fields?.append(textView)

        }
    }

    private struct Constants {
     static let SelectorAdvanceToNextField = Selector("advanceToNextField:")
}
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        registerEventObservers()
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        deRegisterEventObservers()
    }

    func advanceToNextField(notification:NSNotification) {
        let currentTag = (notification.object as! UIView).tag

        for aView in self.view.subviews {
            if aView.tag == currentTag + 1 {
                aView.becomeFirstResponder()
            }
        }
    }

    func registerEventObservers () {

        defaultCenter.addObserver(self, selector: Constants.SelectorAdvanceToNextField, name: MNGTextFieldEvents.NextButtonTappedForTextField, object: nil)
    }

    func deRegisterEventObservers() {

        defaultCenter.removeObserver(self, name: MNGTextFieldEvents.NextButtonTappedForTextField, object: nil)
    }

    ....
}

A: Just another way to achieve the result that I found helpful.  My app had 11 text fields followed by a text view.  I needed to be able to cycle through all fields using the next key and then resign the keyboard following the textview (i.e. other notes).
In the storyboard, I set the tag on all of the fields (both text and textview) starting with 1 through 12, 12 being the textview.
I'm sure there are other ways to do it and this method isn't perfect, but hopefully it helps someone.
In code, I wrote the following:
func textFieldShouldReturn(textField: UITextField) -> Bool {

    let nextTag = textField.tag + 1

    //Handle Textview transition, Textfield programmatically
    if textField.tag == 11 {
        //Current tag is 11, next field is a textview
        self.OtherNotes.becomeFirstResponder()

    } else if nextTag > 11 {
        //12 is the end, close keyboard
        textField.resignFirstResponder()

    } else {
        //Between 1 and 11 cycle through using next button
        let nextResponder = self.view.viewWithTag(nextTag) as? UITextField
        nextResponder?.becomeFirstResponder()

    }

    return false
}

func textFieldDidEndEditing(textField: UITextField) {

    textField.resignFirstResponder()
}

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    //Remove keyboard when clicking Done on keyboard
    if(text == "\n") {
        textView.resignFirstResponder()
        return false
    }
    return true
}

A: Another approach, if you're using storyboards, you can change the textfield's attribute for Return Key.
Currently you have the following options: Default (Return), Go, Google, Join, Next, Route, Search, Send, Yahoo, Done, Emergency Call, Continue


text:
Q: Circuit elements classification I want to understand from theoretical point of view the structure of electric circuits. I don't mean Ohm's law or the Law of induction...
E.g. there are resistors $R$, capacities $C$, inductors $L$ and EMF $\mathcal E$ and they are coefficients in the second order linear differential equation for the charge on capacitor $q$
$$
L\ddot{q} + R\dot{q} + \frac{1}{C}q = \mathcal E
$$
Can other elements of circuits be understood likewise? Can one derive a classification of all possible elements?

A: Some Examples of Non-Linear elements
Diodes :
   Intensity  $I = I_0 (e^{\frac{V}{V_T}}- 1) $, see examples of circuit with diodes
Transistors: see for instance Transistors NPN, section "Large-signal models", to see Intensity/Voltage relations


text:
Q: Rounding in Python Hi everyone I am currently doing a school project and even my teacher is stumped. In Canada the penny has been removed so now all purchases are rounded to either 0 or 5. For example 5.53 would become 5.55 and 5.52 would become 5.50. I am trying to get my program to round like this, but I can't figure out how. I know how to round to decimal places, but I don't know how to round to specifics like this. Any help would be appreciated!
Here is my code. The project is about making a program that a cashier would use in a coffee shop.
order = ['coffee', 'tea', 'hashbrown','jelly','cream','chocolate','glazed','sandwich','bagel','cookie','pannini']
quantity = ['0','0','0','0','0','0','0','0','0','0','0']

# coffee = $1
# Tea = $1.30
# hashbrown = $1.25
# all donuts = $1.50
# sandwich = $2.50
# bagel = $2
# cookie = $0.50
# pannini = $4

cashier = 1
total = 0

while cashier == 1:
    print "What did the customer order?"
    ordered = input ()

    while ordered > 10 or ordered < 0:
        print "Do you want to input a valid order?"
        ordered = input ()

    print "How many are being ordered?"
    quantityorder = input ()
    quantity[ordered] = quantityorder
    print "Ordered",quantityorder,"",order[ordered],"!"
    if ordered == 0:
        ordered = 1.0
    elif ordered == 1:
        ordered = 1.30
    elif ordered == 2:
        ordered = 1.25
    elif ordered == 3 or ordered == 4 or ordered == 5 or ordered == 6:
        ordered = 1.50
    elif ordered == 7:
        ordered = 2.50
    elif ordered == 8:
        ordered = 2
    elif ordered == 9:
        ordered = 0.50
    else:
        ordered = 4.0

    price = ordered * quantityorder
    total = total + price
    print "Anything else?"
    cashier = input ()  #If the user inputs 1 then they can input another order if they didn't put in 1 then the program assumes that it is the end of a customers order

print "Your total is $", total * 1.13,"!"
total = total * 1.13
print
print "How much money was given?"
print
money = input ()* 1.0
while money < total:
    print "Please input a valid number!"
    money = input ()

print "The change should be $",money - total,"!"

A: This tortured me until I solved it. One rule I set for myself was NOT to use a case-by-case switch on modulo 5, but to use builtin functions. Nice puzzle. wim's "double it, round, then halve it" comment was close.
def nickelround(n):
    N = int(n)
    print "%0.2f" % (N + round((n - N) * 20) * 0.05)

A: In [42]:
x=0.57
int(x/0.05)*0.05

Out[42]:
0.55

A: As you already hinted, use the Decimal class (module decimal). Replace all floats in your code with decimal constructors like Decimal('13.52').
Now the function you want to use is 'quantize'.
You use it like that:
Decimal('1.63').quantize(Decimal('0.5'), rounding=ROUND_HALF_DOWN)

The parameter Decimal('0.5') indicates that you want to round to the halves.
UPDATE:
As the OP wanted to round to the units of 0.05, he must obviously use:
Decimal('1.63').quantize(Decimal('0.05'), rounding=ROUND_HALF_DOWN)

A: Usually in these programming problems you're explicitly asked to solve for how to "make change", not just provide the total amount of change due (which is trivial).  So you can just in-line the pennies correction into that function:
def make_change(bal):
    bal = bal + .02 #correction for no pennies
    currency = [20,10,5,1,.25,.1,.05]
    change = {}
    for unit in currency:
        change[unit] = int(bal // unit)
        bal %= unit
    return change

This particular form returns a dict of change denominations and their corresponding counts.

A: I'm going to be old-school and say, convert your number into a list of values with a null or some kind of tag to represent the decimal.
The  make a variable to hold your rounded number and add each value from 1000s or whatever, to 100s, 10s and 1s. (You are looping of course).
Once your loop hits the tag, depending on how far you want to round, (this should be a parameter for your function) throw in a conditional to represent how you want to round ie. 5 means round up, 4 round down (this is another parameter).  Then add the final value(s) and return your newly rounded number.
Step 2: Fire your teacher because this is an unbelievably easy problem.
Bare in mind, anyone who knows c or has worked with memory assignment should find this question a breeze.

A: You could use something as simple as this to round your numbers to a given base:
def round_func(x, base=0.05):
    return round(base*round(float(x)/base), 2)

And since you want only 2 decimal places, you can just round it to 2 decimals. The inner round function is to round the given number as per the base, which is 0.05 in your case.

A: Do you know, how to use own functions?
Add this function to your code:
def nickelround(m):
  return round(m/0.05,0)*0.05

and use it:
print "The change should be $", nickelround(money - total),"!"


text:
Q: How can I prove that F(n)= Theta(T(n))? How can I prove that F(n)= Theta(T(n))? I couldn't put the theta symbol in the question. I know theta means equal?

A: You should prove the function with the definition of Theta.
That is to say if lim(F(n)/T(n))=c (if n->mega), that means Theta

A: Show that F(n) = O(T(n)) and that F(n) = Omega(T(n)).

A: Do a bit of reading on "proof by mathematical induction"
So you say, if something is true for k=1,2...n, then n+1, then it is true for all n.
There is a good book called "The nuts and bolts of proofs" that shows this method.


text:
Q: how can i make my xmldataprovider update my datagrid's content on filechange? I've been following this tutorial and bound my Datagrid successfully to an XML data provider resource.
My grid didn't update when the xmlfile (that the xmldataprovider was referenced to) changed.
So I followed this guy's tutorial and while I could get a notice every time the file changed (the tutorial offers a custom class 'myxmldataprovider' that extends xmldataprovider and has a filesystem watcher listening for file change. There is a function in the class called "on file changed" and it is accessed when the XML file is changed). Using refresh in the file changed function, as suggested by 2nd tutorial didn't do anything to update the datagrid or the dataprovider's content.
I'm really late on my project.. and this seems to be the sole thing keeping me from moving on. I've searched the internet and browsed countless forums. and have yet to find a clear answer that works.
custom class
public class MyXmlDataProvider: XmlDataProvider
{

    public new Uri Source
    {
        get { return base.Source; }
        set
        {
base.Source = value;
            FileSystemWatcher watcher = new FileSystemWatcher();
            //set the path of the XML file appropriately as per your requirements
            watcher.Path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\"));
            //name of the file i am watching
            watcher.Filter = value.OriginalString;

            //watch for file changed events so that we can refresh the data provider
            watcher.Changed += new FileSystemEventHandler(file_Changed);

            //finally, don't forget to enable watching, else the events won't fire
            watcher.EnableRaisingEvents = true;
        }
    }

    void file_Changed(object sender, FileSystemEventArgs e)
    {base.refresh();

}

xaml
<local:MyXmlDataProvider Source="XMLFile123.xml"
                     XPath="firstnode" x:Key="xml" />
</Window.Resources>
<DataGrid Name="CustomerGrid" AutoGenerateColumns="False"
              ItemsSource="{Binding Source={StaticResource xml},XPath=*}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding XPath=@attribute1}"
                                Header="attribute1" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute2}"
                                Header="attribute2" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute3}"
                                Header="attribute3" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute4"
                                Header="attribute4" />
        </DataGrid.Columns>
    </DataGrid>


text:
Q: Flutter Page Not Updating Upon Exiting The Page I am trying to make a product management application. In this application, I divided the products into categories. And in order to reach the products, it is necessary to choose a category from the main page.
I'm saving the user-selected category with GetX and on the Listing Products page, I'm trying to list the products by making a category filter from Firebase Firestore.
But I am having a problem. When the application is opened, when any category is entered, the products of the category entered normally are listed. But when you leave the product listing page and enter a different page, the list of the first entered product is displayed.
My guess is that the source of this problem is the page not refreshing. Can you help me to solve this problem?
Codes:
HomePage.dart(page listing product categories):
  return ListTile(
    leading: Categories[index].icon,
    title: Text(Categories[index].name, style: TextStyle(fontSize: 18, fontFamily: "Montserrat"),),
    onTap: () {
      if (Categories[index].name == "Meyve & Sebze") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Meyve & Sebze", "FruitAndVegetable"];
        // Item 0 of the list is for the AppBar on the product listings page. The 1st item of the list is to be able to filter category from Firebase Firestore.

        Get.to(ProductsPage());
      }
      else if (Categories[index].name == "Fırın") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Fırın", "Bakery"];
        Get.to(ProductsPage());
      }
      else if (Categories[index].name == "Temel Gıda") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Temel Gıda", "Food"];
        Get.to(ProductsPage());
      }
      else if (Categories[index].name == "Süt Ürünleri") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Süt Ürünleri", "DairyProducts"];
        Get.to(ProductsPage());

      }
      else if (Categories[index].name == "Atıştırmalık") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Atıştırmalık", "Snacks"];
        Get.to(ProductsPage());
      }
      else if (Categories[index].name == "Su & içecek") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Su & içecek", "Waters"];
        Get.to(ProductsPage());
      }
      else if (Categories[index].name == "Teknoloji") {
        _temporaryHoldOfInformation.temporaryInformationProducts.value = ["Teknoloji", "Tech"];
        Get.to(ProductsPage());
      }
    },
  );`

temporary_hold_of_information.dart (To keep user selected category from HomePage.dart - GetX):
import 'package:get/get.dart';

class TemporaryHoldOfInformation extends GetxController {
  RxList temporaryInformationProducts = RxList([]);
}

ProducsPage.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:market_cebimde/paginations/temporary_hold_of_information.dart';

class ProductsPage extends StatefulWidget {
  @override
  State<ProductsPage> createState() => _ProductsPageState();
}

TemporaryHoldOfInformation _temporaryHoldOfInformation = Get.put(TemporaryHoldOfInformation());
String _productName = _temporaryHoldOfInformation.temporaryInformationProducts.value[0];
String _productCategory = _temporaryHoldOfInformation.temporaryInformationProducts.value[1];
FirebaseFirestore _firestore = FirebaseFirestore.instance;
FirebaseAuth _auth = FirebaseAuth.instance;

class _ProductsPageState extends State<ProductsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueAccent[700],
        title: Text("${_productName.toString()}", style: const TextStyle(color: Colors.white),),
        centerTitle: true,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            StreamBuilder(
              stream: _firestore.collection("products").where("category", isEqualTo: _productCategory).snapshots(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return GridView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 1.5,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: snapshot.data!.docs.length,
                    itemBuilder: (context, index) {
                      return Container(
                        child: Column(
                          children: [
                            Container(
                              width: double.infinity,
                              height: 200,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                image: DecorationImage(
                                  image: NetworkImage(snapshot.data!.docs[index].data()["productImageLink"]),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            Text(snapshot.data!.docs[index].data()["productName"]),
                            Text(snapshot.data!.docs[index].data()["productCost"]),
                            Text(snapshot.data!.docs[index].data()["category"]),
                            Text(snapshot.data!.docs[index].data()["productWeight"]),
                          ],
                        ),
                      );
                    },
                  );
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

The page that is selected in HomePage.dart, saved with GetX, filtered in Firebase Firestore by category, and the products are listed. The problem is on this page. When you exit-enter the page, the products of the category entered are listed, not the products of the entered category. So the page is not updating.
I have to restart the application for the products according to the selected category to arrive.
I would be glad if you help. Thanks in advance for your help :)


text:
Q: Good antonym for "pet peeve" I'm looking for a pithy and preferably alliterative antonym for "pet peeve". "Pet pleasure" has the benefit of both simplicity and parallelism to "pet peeve", but I'm concerned it may imply a sexual context. Suggestions?

A: How about soft spot?
From Merriam-Webster:

soft spot: a
  strong liking for someone or something

Given that a pet peeve is something that annoys or bothers a person very much, i.e., is something one dislikes strongly, it would seem that soft spot is an appropriate antonym.

A: What about a penchant, or even, if you wanted to alliterate, pet or personal penchant?

(UK): /ˈpɑːnʃɑn/, [ˈpɑ̃ʃɑ̃]
  (US): /ˈpɛnt͡ʃənt/
a taste, liking, or inclination (for)
He has a penchant for fine wine.

A: Perhaps hobby-horse (or hobbyhorse), in the sense of a topic one likes to talk about constantly or keeps reverting to.  Google's definition #2 "a preoccupation; a favorite topic."
At http://www.dictionary.com/browse/hobbyhorse their first dictionary, definition #3 "a pet idea or project."

A: Soft spot is good!  Here are a few more ideas:
Labor of love
True treasures
Delicious delicacies
Particular preferences
Preferred pleasures
best-liked bits
popular preferences
and the best for last:
sweet satisfactions

New:
favorite features

A: It's not alliterative, but favorite thing.  Sound clip from the Sound of Music. (Click on My Favorite Things -- Julie Andrews -- You Tube, which appears below the picture. Do not click on the picture of Ms. Andrews.  That click gave me a car commercial.)
The song refers to favorite things (plural) and the OP asked for the antonym of pet peeve (singular), so that is a problem with this answer.
Lyrics of song:
*Raindrops on roses and whiskers on kittens
Bright copper kettles and warm woolen mittens
Brown paper packages tied up with string
These are a few of my favorite things
Cream colored ponies and crisp apple strudels
Doorbells and sleigh bells and schnitzel with noodles
Wild geese that fly with the moon on their wings
These are a few of my favorite things
Girls in white dresses with blue satin sashes
Snowflakes that stay on my nose and eyelashes
Silver white winters that melt into springs
These are a few of my favorite things
When the dog bites
When the bee stings
When I'm feeling sad
I simply remember my favorite things
And then I don't feel so bad
Raindrops on roses and whiskers on kittens
Bright copper kettles and warm woolen mittens
Brown paper…*


text:
Q: Home folder synced to HD: results differ! I'm new to Ubuntu. I would like to have an exact copy of my home folder on my Hard drive.
I've tried the following  (no programs running on Ubuntu):
1.
Copy-paste ~/ to /dest1/ per drag and drop in nautilus
--> du -s differs and diff -r ~/ /dest1/ differs (more files in src)
2.
rsync -ahv ~/ /dest1/
du -s differs and diff -r ~/ /dest1/ differs (more files in src)
3.
sudo rsync -ahv ~/ /dest2/
--> du -s differs and diff -r ~/ /dest2/ differs (more files in src)
4.
sudo cp -a ~/. /dest3/
--> du -s differs and diff -r ~/ /dest2/ differs (more files in src)
Then I ejecdted HD from ubuntu and compared folders via Windows:
dest3 and dest2 are identical
dest 1 contains one more file
What can I do to exactly mirror my home folder to a HD?

A: Use rsync utility to clone a directory. Run:
sudo rsync -xrlptgoEvv --progress /home/user/source/ /home/user/dest/

To keep destination directory in fresh state, you can add --delete option - this will remove from destination directory files and directories which have been deleted in source directory since previous syncing, i.e.
sudo rsync -xrlptgoEvv --progress --delete /home/user/source/ /home/user/dest/

Another solution is tar with or without compression. Tar itself is just a multiple files "container". To create uncompressed tar-archive (archive file is larger, but creation process is faster) of a directory, issue the command:
tar pcvf archive.tar sourcedir/

Gzip compressed tar-archive (archive file is smaller, but creation process is slower) can be created with
tar pczvf archive.tar.gz sourcedir/

To extract such archives, use commands:
tar xvf archive.tar
tar xzvf archive.tar.gz

Remark. Use sudo before tar command if your directory contains files with restricted access for current user.


text:
Q: angular change filtered ng-repeat scenarios with ng-click I have four filtered scenarios I want the user to be able to click through. I have a different ng-repeat filter for each scenario.

 ">

 ">

And these are my buttons:
All
Inspire
Show Off
Share

How do I set it up so that each filtered ng-repeat scenario is only triggered when a tab is clicked. How can I do this?

A: All
    Inspire
    Show Off
    Share


text:
Q: WARNING:root:The given value for groups will be overwritten I'm getting a warning after calling load_model in Keras;
    outfile = self.output_directory+self.data_set_name+'_'+self._model_name()
    model_path = outfile + '_best_model.hdf5'
    model = keras.models.load_model(model_path)

    WARNING:root:The given value for groups will be overwritten.
    WARNING:root:The given value for groups will be overwritten.
    WARNING:root:The given value for groups will be overwritten.
    WARNING:root:The given value for groups will be overwritten.

Do you have any idea what is about?
Thanks

A: If you use Instancenormalization from TF/addons there is your warning in the init call of the instancenorm layer in line 338.
if "groups" in kwargs:
        logging.warning("The given value for groups will be overwritten.")

https://github.com/tensorflow/addons/blob/master/tensorflow_addons/layers/normalizations.py


text:
Q: How to render a dynamic number of GroupBoxes I'm trying to do something like the following: for each contract, render a GroupBox with some info.
The number of contracts changes based on the selected company.
How would I accomplish something like this? The only dynamic GUI elements I've been able to implement or found help on are things like DataGridViews, which are bound directly to the data.

A: not a lot to go on, but here is a start:
 for each c in Contracts
     Dim g as new GroupBox
     with g
         .Location = ...   ' needed else it could be off screen
         .Size = ...
     End With

     Dim Lbl as new Label
     ... set location, text etc
     g.Controls.Add(lbl)
     ... continue for the stuff needed
     g.Controls.Add(otherstuff)

     ' depending on the amount of similarity you can make factories:
     Dim cbo as ComboBOx = MakeContactCBO(someKey)
     g.Controls.Add(cbo)

     Me/theFormName.Controls.Add(g)            ' add g with all the child ctls
  next c

It can get lengthy.  if they are somewhat similar you can several on the form already and then modify or hide them as needed. e.g. a layout that serves 80% of the situations, then remove and add to that base.

A: What I was looking for was the DataRepeater control. This lets me write a "template" for each entity in the list, and repeats it for the number of entities.


text:
Q: Trying to get property 'name' of non-object but i have data name
I do REST API MONGODB-PHP CRUD via postman and got Trying to get
property 'name' of non-object. but i have a data name. Why did it
happen ? I use XAMPP 3.2.2 PHP 7.2.1 are there any suggestion to fix
it ?

delete.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database file
include_once 'db.php';
$dbname = 'dbprakt';
$collection = 'classroom';

//DB connection
$db = new DbManager();
$conn = $db->getConnection();

//record to delete
$data = json_decode(file_get_contents('php://input'), true);

//_id field value
$name = $data->{"name"};

// delete record
$delete = new MongoDB\Driver\BulkWrite();
$delete->delete(
    ["name" => $name]
);
$result = $conn->executeBulkWrite("$dbname.$collection", $delete);

// verify
if ($result->getDeletedCount() == 1) {
    echo json_encode(
        array("message" => "Error while saving deleted")
    );
} else {
    echo json_encode(
            array("message" => "Error while deleting record")
    );
}
?>

how i fix error
Trying to get property 'name' of non-object in C:\xampp\htdocs\mongo\delete.php on line 22

A: your json_decode pass the seccond parameter is true which mean $data is array,
it not an object
either
change
json_decode(file_get_contents('php://input'), true)

to
json_decode(file_get_contents('php://input'))

or using $data as array $data["name"]

associative
When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects. When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags.

https://www.php.net/manual/en/function.json-decode.php


text:
Q: A square-squareroot integer race sequence involving primes I wonder what is the expected behavior of this process?
Let

$f^2_{\mathrm{next}}(n) =$ the next prime after $n^2$.
$g_{\mathrm{sqrt}}(n) = \lfloor \sqrt{n} \rfloor$.

Now iterate as follows, with $n = n_0$:
\begin{eqnarray}
n &=&  f^2_{\mathrm{next}}(n)\\
n &=& g_{\mathrm{sqrt}}(n)\\
n &=& n \pm 1 \;,
\end{eqnarray}
where $n$ is augmented in the last equation by $\{-1,1\}$ with equal probability.
So, for $n_0=20$, $f^2_{\mathrm{next}}(20)$ is $401$, the next prime after $20^2$, and then
$\lfloor \sqrt{401} \rfloor = 20$.
But then, the random $\pm 1$ leads to
$\lfloor \sqrt{401} \rfloor -1  = 19$,
which leads to $f^2_{\mathrm{next}}(19)=$ the next prime after $361$,
which is $367$. Etc.
So in one random sequence, we see development like this:

So there is a push-forward toward the next prime by $f^2_{\mathrm{next}}(n)$,
counterbalanced by a fall-backward via the floor-function in $g_{\mathrm{sqrt}}(n)$,
and confused by the $\pm 1$.

Q. What is the ultimate behavior of this sequence for a given $n_0$?

A: As requested, I am making my comment into an answer.
It is a conjecture of Legendre that there is always a prime between $n^2$ and $(n+1)^2$.  According to Wikipedia, this has been checked for $n$ up to $10^{18}$, and it would follow from standard conjectures about the distribution of gaps between primes.  In particular, Legendre's conjecture is roughly equivalent to knowing that $p_{n+1}-p_n \leq 2 \sqrt{p_n}$ for all $n$.  The best results we have toward this are due to Baker, Harman, and Pintz, who have shown that $p_{n+1}-p_n \ll p_n^{0.525}$, and it's a conjecture of Cramer that $p_{n+1}-p_n \ll \log^2 p_n$ for all $n$ and that this is sharp (i.e., the limsup of the ratio exists and is positive).
At any rate, assume Legendre's conjecture is true.  We then have, for any $n\geq 1$, that $g_{\mathrm{sqrt}}(f^2_\mathrm{next}(n))=n$, and we also visibly have $g_{\mathrm{sqrt}}(f^2_{\mathrm{next}}(0))=1$.  Thus, everything interesting is happening with the $\pm 1$ factor in the final step of the iteration, and so we're just looking at a random walk that is not permitted to go below 0.


text:
Q: when use editurl: 'clientArray' jqgrid see error dont found page hi iam use   editurl: 'clientArray', in jqgrid but see  this error:
plase see pic error.how sloved this problem

But when they edit, it should not call server.So i tried 'ClientArray' But still it shows Url is not set alert box
how sloved this problem
 myGrid.jqGrid({
                            pager: myPager, data: col[cols], datatype: 'local',
                            editurl: 'clientArray',
                            },
                            jsonReader: {
                                root: "Rows",
                                page: "Page",
                                total: "Total",
                                records: "Records",
                                repeatitems: true,
                                userdata: "UserData",
                                id: "Id",
                                cell: "RowCells"
                            },

                            cmTemplate: { editable: false, autoResizable: true },
                             loadonce: true,
                            shrinkToFit: true,

                            autoencode: true,

                        })
                        .navGrid( '#' + $(myPager)[0].id ,

                  { add: false, del: false, edit: false, search: false }

                  )
                           .jqGrid('inlineNav', '#' + $(myPager)[0].id ,
                         {
                             // cloneToTop: true,
                             edit: false, add: true, save: false, cancel: false,
                             edittext: "ویرایش", addtext: "جدید", savetext: "ذخیره", canceltext: "لغو",

                             addParams: {
                                 position: "last",
                                 rowID: '0',
                                 useDefValues: true,
                                 addRowParams:  getInlineNavParams(true)
                             },
                             //editParams: getInlineNavParams(false)
                         }

                         );

                        myGrid.jqGrid('filterToolbar', {
                            stringResult: true,//// وجود این سطر سبب می‌شود تا اپراتورها به سرور ارسال شوند
                            enableClear: false,
                            searchOnEnter: true,
                            searchOperators: true, // فعال سازی منوی اپراتورها
                            defaultSearch: "cn"

                        });

A: The usage of editurl: 'clientArray' is correct. I'd recommend you to try to upgrade to free jqGrid 4.15.1 - it's the fork of jqGrid, which I develop after the main fork are made commercial and renamed to Guriddo jqGrid JS.
To test free jqGrid you can load jqGrid files directly from CDN:
https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.1/css/ui.jqgrid.min.css
https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.1/i18n/min/grid.locale-fa.js
https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.1/jquery.jqgrid.min.js

See the wiki article for more details.


text:
Q: Kotlin toFloat function round-off problem One of the library is accepting only float value, so i am trying to convert integer value to float value in kotlin using toFloat() function. But it is giving nearest value and not the exact value. Official documentation also says

Returns the value of this number as a Float, which may involve rounding.

I am trying to convert 105312355 to Float, which is giving me 1.05312352E8. If i reverse calculate float to integer it is giving me 105312352.
So, how do i force to calculate correct value.

A: The nature of Floating Point is that it can express a wider range of values at the expense of precision compared to the same size of Int.
Only a Double (rather than Float) can preserve the full precision of the Int. Something will need to give.


text:
Q: Uniform Acceleration - Does the Reason explain the assertion? Can you please help with the following question?
This question is formulated as an Assertion and a Reason and the possible answers are as follows:
a) Both assertion and Reason are true and Reason is the correct explanation of the Assertion.
b) Both assertion and Reason are true but Reason is NOT the correct explanation of the Assertion.
c) Assertion is true but the Reason is false
d) Assertion is false but the Reason is true
Question:
Assertion: When the displacement of a body is directly proportional to the square of the time, then the body is moving with uniform acceleration.
Reason: The slope of velocity time graph with time axis gives acceleration.
While I understand that both the Assertion and the Reason are true, the key part I am interested in is, if the Reason correctly explains the Assertion or not (and why?).
Thank you very much for your help

A: From Newton's second law of Motion, we have s = ut + ½ at² where s = displacement, u = initial velocity, v = final velocity, a = acceleration and t = time taken.
Putting initial velocity = 0, we have s = ½ at² i.e., s ∝ t² (a = constant).
Hence, one can conclude from the above equation that when the displacement of a body is directly proportional to the square of the time, the body is moving with uniform acceleration. However the above Reason does not explain this.
So, I think the answer will be opt. b)


text:
Q: Removing word + wildcard number from string I have a string that is
$str = "testingSUB1";

How can I strip out SUB* from the string? I assume using preg_replace but I'm not good with matching what I want with regex.
Does anyone know how I can do this?
Thank you

A: That's the way.
$str = preg_replace("#SUB[0-9]+#", "", $str);

The #s are delimiters; they can be any non-alphanumeric/whitespace/backslash character that doesn't appear in the pattern. [0-9] means any digit (you can use \d too in some languages, but I usually don't bother), and the + means one or more of the previous, so if you take the + out it will only replace the first digit

A: This should do it:
$word = 'SUB';
$string = 'testingSUB1';

echo preg_replace('~^(.*?)(' . preg_quote($word, '~') . '\d+)(.*?)$~', '$1$2', $string);

EDIT - This is better:
echo preg_replace('~' . preg_quote($word, '~') . '\d+~', '', $string);


text:
Q: how to create a task of a specific record type from a workflow I want to be able to create a task of a specific record type from a workflow. At the moment all I can see is the option for customising certain fields on the task from within the workflow action.

A: How about trigger that will set recordType based on some values in new Task?


text:
Q: How to position a div relative to img without a parent div wrapping the img I am currently writing a little jqueryplugin for preloading images with a statusbar for each image.
The statusbar should be centered horizontally and vertically above each image.
As it should be a plugin I don't want the user need to wrap each image by a relative positioned div in order to position another div relative to the img. Using a cms the user might not even be able to change the way an image is being output.
So what I don't want is this:

100% loaded

What I want is:

100% loaded

I tried to place a div right behind the image with jQuery, setting it to position relative and place a div right inside that div positioned absolute. That might work for some cases, but it depends on the css of the img... is it floated or not etc.
Does any CSS- or jQuery-Guru got some suggestions for me? :-)
Cheers

A: This will wrap imgs and remove the wrapper when the images are loaded.
$('img').each(function () {

  var $img = $(this),
      $percentLoaded = $('');

  $img.wrap('');

  $img.parent().append($percentLoaded);

  $img.on('load', function () {
    $percentLoaded.fadeOut(5000);
    $img.unwrap();
  });

});

Then the CSS would look something like this:
.preloader {
  position: relative;
  display: inline-block;
}

.preloader .percent-loaded {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: rgba(255, 0, 0, 0.5)
}

Here is a demo: http://jsbin.com/jesuneqo/1/edit


text:
Q: Перевод части ветки на master Подскажите пожалуйста, как можно перенести часть ветки и/или последние изменения на ветку мастер. (желательно с сохранением имени)

A:
Возможно, можно проще, но наиболее очевидным мне кажется такой вариант:

# Переходим на branch-2 и создаём новую ветку.
$ git checkout branch-2
$ git checkout -b branch-2-new

# Переносим новую ветку до branch-1.
$ git rebase --onto master branch-1

# Переходим на branch-3 и создаём новую ветку.
$ git checkout branch-3
$ git checkout -b branch-3-new

# Переносим новую ветку до branch-2.
$ git rebase --onto branch-2-new branch-2

A: Решил вопрос таким образом.
1) переключаемся на нужную ветку.
2) делаем git reset --soft HEAD~1
3) git stash
4) git branch -m {current_branch_name} {new_branch_name} как нибудь переименуем ветку
5) создаем ветку от мастер с нужным названием как всегда.
6) git stash apply
7) при необходимости решаем конфликты и коммитим


text:
Q: Stripe Account Disappeared from Dashboard I had an account recently processing payments in USD for a site and a few days ago it vanished without a trace from the dashboard within Stripe. It is a subscription based site which makes use of Foxycart / Foxyshop wordpress. Within foxycart there is an area in which I have placed keys.
The only thing that has changed last week is that I set up a new wordpress installation on same server which also charged USD in Test Mode only.
This does not make use of FOxycart and I am using woocommerce and a woocomerce plguin for subscriptions + stripe.
The Stripe account used for the second site is a separate stripe account.
I have contacted Stripe 4 times in last 4 days with no answer whatsoever. The original account is still processing payments for subscriptions that have previously been set.
I was thinking I could always set up a new account and update keys within Foxycart but am not sure if this will affect past subscriptions in any way. I would like to retain records as well fdrom previous transactions. Help appreciated as my client is very upset.


text:
Q: How to read and test a class from java extension file in junit? How can I access that class for testing? In a software for mutation testing, a lot of mutants of java extension files (like mutant01.java) are created. Now I need to test these files by using jUnit4. I'm trying to find out the way that I will be able to read the file and then access a specific class from that file, and perform jUnit testing on it. But I need help to do it?
I had found the ways that only results that my file is uploaded but I'm not be able to access the contents or specific class from that file.
@Test
public void testReadFileWithClassLoader(){
    try {
        ClassLoader classLoader = this.getClass().getClassLoader();
        File file = new File(classLoader.getResource("arith.java").getFile());
        Class<? extends File> f=file.getClass();
        assertTrue(file.exists());

I'm expecting that I become able to access the class from a java extension file and then perform junit testing on it but actually I'm stuck on it.

A: AS @John Mercier pointed you must compile your class first and then load it. You could use jOOR in order to do it easier.

jOOR - Fluent Reflection in Java jOOR is a very simple fluent API that
  gives access to your Java Class structures in a more intuitive way.
  The JDK's reflection APIs are hard and verbose to use. Other languages
  have much simpler constructs to access type meta information at
  runtime. Let us make Java reflection better.

For use with Java 9+
<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor</artifactId>
  <version>0.9.7</version>
</dependency>

For use with Java 8+
<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor-java-8</artifactId>
  <version>0.9.7</version>
</dependency>

For use with Java 6+
<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor-java-6</artifactId>
  <version>0.9.7</version>
</dependency>

Usage example:
Supplier<String> supplier = Reflect.compile(
    "com.example.HelloWorld",
    "package com.example;\n" +
    "class HelloWorld implements java.util.function.Supplier<String> {\n" +
    "    public String get() {\n" +
    "        return \"Hello World!\";\n" +
    "    }\n" +
    "}\n").create().get();

// Prints "Hello World!"
System.out.println(supplier.get());

Note you must read your .java file before as a String


text:
Q: tensorflow import error. With /Library/Python/2.7/site-packages not included Trying to install tensorflow. Tried anaconda, it worked but affected my other program. Then decided to use pip install.
But after I installed it, I just can't import it within ipython.
Here are the messages: I tried uninstall and reinstall.
pip install tensorflow
Requirement already satisfied (use --upgrade to upgrade): tensorflow in /Library/Python/2.7/site-packages
Cleaning up...

First I try to import in ipython:
In [1]: import tensorflow
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-a649b509054f> in <module>()
----> 1 import tensorflow

ImportError: No module named tensorflow

And then I copied the folder of tensorflow from /Library/Python/2.7/site-packages to /usr/local/lib/python2.7/site-packages/. I try to import:
In [1]: import tensorflow
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-a649b509054f> in <module>()
----> 1 import tensorflow

/Library/Python/2.7/site-packages/tensorflow/__init__.py in <module>()
     21 from __future__ import print_function
     22
---> 23 from tensorflow.python import *
     24
     25

/Library/Python/2.7/site-packages/tensorflow/python/__init__.py in <module>()
     57 please exit the tensorflow source tree, and relaunch your python interpreter
     58 from there.""" % traceback.format_exc()
---> 59   raise ImportError(msg)
     60
     61 from tensorflow.core.framework.node_def_pb2 import *

ImportError: Traceback (most recent call last):
  File "tensorflow/python/__init__.py", line 53, in <module>
    from tensorflow.core.framework.graph_pb2 import *
  File "tensorflow/core/framework/graph_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
ImportError: No module named google.protobuf

Error importing tensorflow.  Unless you are using bazel,
you should not try to import tensorflow from its source directory;
please exit the tensorflow source tree, and relaunch your python interpreter
from there.

However, I have protobuf installed under /Library/Python/2.7/site-packages as well.
I find out this version of ipython is using macports python package directory:
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/
I am not sure how to let ipython search for the pip installed directory.
I reinstalled the tensorflow again as it is described on the website:
sudo pip install --upgrade $TF_BINARY_URL
Password:
Downloading/unpacking https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl
  Downloading tensorflow-0.11.0rc0-py2-none-any.whl (35.5MB): 35.5MB downloaded
Downloading/unpacking protobuf==3.0.0 (from tensorflow==0.11.0rc0)
  Downloading protobuf-3.0.0-py2.py3-none-any.whl (342kB): 342kB downloaded
Requirement already up-to-date: wheel in /Library/Python/2.7/site-packages (from tensorflow==0.11.0rc0)
Requirement already up-to-date: mock>=2.0.0 in /Library/Python/2.7/site-packages (from tensorflow==0.11.0rc0)
Requirement already up-to-date: numpy>=1.11.0 in /Library/Python/2.7/site-packages (from tensorflow==0.11.0rc0)
Requirement already up-to-date: six>=1.10.0 in /Library/Python/2.7/site-packages (from tensorflow==0.11.0rc0)
Downloading/unpacking setuptools from https://pypi.python.org/packages/be/20/3f4d2fb59ddeed35532bd4e11e900abcf8019d29f4558d38169639303536/setuptools-28.2.0-py2.py3-none-any.whl#md5=02e79b1127c5a131a2dace6d30cf7f25 (from protobuf==3.0.0->tensorflow==0.11.0rc0)
  Downloading setuptools-28.2.0-py2.py3-none-any.whl (467kB): 467kB downloaded
Installing collected packages: tensorflow, protobuf, setuptools
  Found existing installation: protobuf 3.1.0.post1
    Uninstalling protobuf:
      Successfully uninstalled protobuf
  Found existing installation: setuptools 18.5
    Uninstalling setuptools:
      Successfully uninstalled setuptools
Successfully installed tensorflow protobuf setuptools
Cleaning up...

And still no luck:
In [1]: import tensorflow
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-a649b509054f> in <module>()
----> 1 import tensorflow

A: OK, I got the problem fixed.
I am not sure what exactly is causing it. Because I installed all this on my RMBP, nothing wrong. But desktop just won't take it.
Solution is:
Uninstall all previously installed or half installed tensorflow, and my other packages (just two main packages). And use anaconda to install tensorflow, activate it. And use anaconda to install my other packages.
Then problem solved.


text:
Q: How to get Approval submitted Date for the existing data I have a requirement where I want Approval Submitted date for existing data.
I tried Field Update on Approval process, and put formula Today() and apparently I got the Approval Date but it is working only for new data not for the existing one.
How can I achieve this for existing data.
Tia,

A: Ask your admin to execute following code snippet. As admins can update records, even when they are locked.
This is for Account, but make changes for your object and replace fieldName with your respective field
    Map<id,Account> accounts = new Map<ID,Account>([Select {fieldName}, id From Account]);

Map<ID,Date> approvalTimeStampMap = new Map<ID,Date>();
For(ProcessInstance approval : [Select createdDate,TargetObjectId From ProcessInstance Where TargetObjectId IN:accounts.keySet()){
    approvalTimeStampMap.put(approval.TargetObjectId, approval.createdDate);
}

List<Account> accountsSubmittedForApproval = new List<Account>();
for(Account acc : accounts.values()){
    acc.{fieldName} = approvalTimeStampMap.get(acc.id); // Do string conversion if your field is a String
    //Keep a track of number of records you are processing
    accountsSubmittedForApproval.add(acc);
}

//Size should be less than 10k
update accountsSubmittedForApproval;

Hope this helps :)


text:
Q: Highcharts dates in xaxis customisation How can we format dates in to this format

Right now it is like this:

xAxis: {
            type: 'datetime'
        }

JS Fiddle here

A: I just changed the code of your xAxis
Here it is :
xAxis: [{
            type: 'datetime',
            labels: {
            formatter: function() {

                return Highcharts.dateFormat('%e', this.value);

            }
        },

        tickInterval: 1 * 24 * 3600 * 1000
        },
        {   lineWidth: 0,
           minorGridLineWidth: 0,
           lineColor: 'transparent',
           minorTickLength: 0,
           tickLength: 0,
            type: 'datetime',
            labels: {
            formatter: function() {
                return Highcharts.dateFormat('%b', this.value);

            }
        },

        tickInterval: 30 *24 * 3600 * 1000
        }]

For details follow this jsFiddle Link http://jsfiddle.net/3nLmxs89/1/


text:
Q: Проблема в ng-switch Не выводится значение ng-switch, в чем может быть проблема?
<!DOCTYPE html>

    <title>HomeWork #3</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.2/semantic.min.css">

HomeWork #3

            <input ng-model="number" value="{{$index}}" name="radio" type="radio">
            {{item.question}}

                1

                2

A: Ошибка заключается в том, что ng-repeat создает свой собственный скоп. Поэтому при использовании ng-model="number" переменная number будет создана в скопе ng-repeat, и к ней не будет доступа вне ее.
Обычное решение - использовать dot rule, гласящее, что в выражении используемом в директиве ng-model должна быть точка.
Например так:

var app = angular.module('myApp', [])
  .controller('mainCtrl', function($scope) {
    $scope.items = [{
      question: "Question 1",
      answer: ["1", "2", "3", "4"]
    }, {
      question: "Question 2",
      answer: ["1", "2", "3", "4"]
    }, ];
  })

<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.2/semantic.min.css">

HomeWork #3

        <input ng-model="c.number" value="{{$index}}" name="radio" type="radio">
        {{item.question}}

          1

          2


text:
Q: Fecha SQL mostrar en php hace cuando fue el registro Trabajo sobre una tabla de recordatorios y me gustaria poder mostrar hacer cuanto fue creado el registro en mi tabla

Mi tabla tareas :
id idusuario usuario titulo   Contenido fecha          Estado
1  1         juan    titulo1  aaa qq    17-08-18/12:30 atendido
2  1         juan    titulo2  bbb qq    07-08-18/01:21 pendiente
3  1         juan    titulo1  ccc qq    05-08-18/11:22 atendiendo
4  2         pepe    titulo2  ddd qq    12-08-18/04:20 pendiente
5  2         pepe    titulo3  eee qq    20-08-18/10:50 canceloado
6  3         alex    titulo4  fff qq    17-08-18/05:59 nadie sabe

quiero que en mi tabla donde muestro los compos referentes al usuario juan diga hace cuanto tiempo fue el registro.
Si la fecha del primer registro es : 17-08-18/12:30 y hoy es 17-08-18/12:30 diga hace 3m y si a pasado un dia poder mostrar el resultado hace 1d 3m estoy recien creando la base de datos asi que puedo crear cambios sobre la misma si hace falta
Con una consulta como:
<?php
$sql_tarea = sqlsrv_query(
$conn, "SELECT tareas
        FROM periodo where
                     idusuario=$idsuario
        ORDER BY id DESC");

//$conn contiene mis datos de conecion a my base,
//y $idsuario es el id del usuario que inicio la secion
 if($c=sqlsrv_fetch_array($sql)) {
                                $fecha=$c['fecha'];
                            }
?>

poder hacer que $fecha diga el tiempo transcurrido cuando lo muestre en un echo $fecha

A: Si es SQL Server deberia de funcionar algo asi:
SELECT tareas , DATEDIFF ( mi, fecha, getdate() )  as
        FROM periodo where
                     idusuario=$idsuario
        ORDER BY id DESC

El ejemplo solo dira la diferencia de minutos, para algo mas complejo creo que tendrias que meter validaciones.
Igual para mas documentacion puedes ver este link:
https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017


text:
Q: How can I run a command before executing tests with both `dotnet test` and VS? I have a .NET project which depends on a database that I am writing integration tests for. When I run the tests I need a local docker container to be running. It can be started using the following command (from the solution root):
docker compose up -d db

For now, this is simple enough to do manually but, ideally, standing up the container would be automated whenever the tests are run. To this end I tried the adding following:
(solution root)/Directory.Build.props:
<SolutionRoot>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))</SolutionRoot>

(solution root)/tests/IntegrationTests/IntegrationTests.csproj:
  <Target Name="DbContainerUp" BeforeTargets="VSTest">
    <Exec Command="cd $(SolutionRoot)" />
    <Exec Command="docker compose up -d db" />
  </Target>

This works but only when executed via dotnet test. If I execute the tests using either Visual Studio Test Explorer or VSCode Test Runner then the DbContainerUp target is not invoked. I assume this is because the Test Explorer/Runner does not invoke dotnet msbuild /t:VSTest (which is what dotnet test is translated to) but I am unable to find any documentation of what targets (if any) VS and VSCode use.
I have looked into the following and not found a viable path forward yet:

*

*.runsettings does not provide an extensibility point for executing commands.

*The xunit runner source doesn't contain a custom target.

A: For now I have solved this by adding an AfterTargets="AfterBuild" attribute to the DbContainerUp target like so:
  <Target Name="DbContainerUp" BeforeTargets="VSTest" AfterTargets="AfterBuild">
    <Exec Command="cd $(SolutionRoot)" />
    <Exec Command="docker compose up -d db" />
  </Target>

This works because VS (and VS Code) must build the IntegrationTests project as part of either test discovery or prior to test execution (depending on implementation). Additionally, because BeforeTargets and AfterTargets are cooperative (either will trigger the custom target), this means that dotnet test continues to behave as expected.
While this isn't a perfect solution--any generic dotnet build will also start the container--it is acceptable for our needs to ensure the container is started.


text:
Q: Initialise a counter before the first loop This line
$.each(data[0].hotel_id, function (index, value) {

Loops through hotel_id array executing the inner JS code for each entry in the dictionary setting index to the key in the dictionary and value to the contents.
My dictionary:
"hotel_id": [{
    "hotel_id": ["1"]
}, {
    "hotel_id": ["2"]
}, {
    "hotel_id": ["3"]
}, {
    "hotel_id": ["4"]
}],

Has all items with the same index, therefore the value of index will always be 'hotel_id', which is no use to i when i try to use it to find the relevant extra data from my other dictionaries.
I would initialise a counter before the first loop and increment it on each iteration then use this value to find the associated extra data from the other arrays.
See full my js code: http://pastebin.com/jBWEDZrN
This is summary from my js code in ajax call(url: 'get_gr',):
$.each(data[0].hotel_id, function (index, value) {
    var $li = $('
<input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;">
');
    var $tooltip = $('

').appendTo($li);
    $li.appendTo('#residence_name');

    var info_ru = data[0].residence_u[index];
    $.each(info_ru.units, function (index, value) {
        $tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '
');
    });

    var info_rp = data[0].residence_p[index];
    $.each(info_rp.start_date, function (index, value) {
        $tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '
');
    });
    tool_tip()
});

This is output php code(url: 'get_gr',):
[{
    "guide": null,
    "hotel_id": [{
        "hotel_id": ["1"]
    }, {
        "hotel_id": ["2"]
    }, {
        "hotel_id": ["3"]
    }, {
        "hotel_id": ["4"]
    }],
    "residence_u": [{
        "units": ["hello", "how", "what"],
        "extra": ["11", "22", "33"],
        "price": ["1,111,111", "2,222,222", "3,333,333"]
    }, {
        "units": ["fine"],
        "extra": ["44"],
        "price": ["4,444,444"]
    }, {
        "units": ["thanks", "good"],
        "extra": ["55", "66"],
        "price": ["5,555,555", "6,666,666"]
    }],
    "residence_p": [{
        "start_date": ["1111", "2222"],
        "end_date": ["1111", "2222"],
        "price_change": ["1111", "2222"]
    }, {
        "start_date": ["3333", "444"],
        "end_date": ["3333", "4444"],
        "price_change": ["3333", "4444"]
    }, {
        "start_date": ["5555", "6666"],
        "end_date": ["5555", "6666"],
        "price_change": ["5555", "6666"]
    }]
}]

What do i do?
Update:(this update is for above output php)
I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery.
Output js code is this:

1 hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33
  & 3,333,333, 1111 & 1111 & 1111  2222 & 2222 & 2222

2 fine & 44 & 4,444,444 3333 & 3333 & 3333  4444 & 4444 & 4444

3 thanks & 55 & 5,555,555 good & 66 & 6,666,666 5555 & 5555 & 5555  6666 & 6666 & 6666

4

A: No, your array doesn't have items with the same index. It has items with different indexes, but the value is an object that contains a property with the same name for each object. The index will go from 0 to 3 if the array has four items as in the example.
You can use value.hotel_id in the loop to get the array that is the value of the property, for example ["1"].
If the array in the property only ever contains one id, you can just use value.hotel_id[0] to get that id.
Example:
$.each(data[0].hotel_id, function (index, value) {
  alert(value.hotel_id[0]);
});

http://jsfiddle.net/Guffa/BWLqw/

A: I don't see the point of using each and an anonymous function.
I would just use a for loop.
for(var n = 0; n < data[0].hotel_id.length; n++) {
  // put your function code here or call a named func(data[0].hotel_id[n])
}

I only use each if I am applying a function that I would reuse elsewhere.


text:
Q: watching my whole application for events and logout when a time lapse of inactivity thanks in advance for your response. I am implementing an inactivity log out and it works just fine. Right now I have this implemented in my home component only, but, of course I want to use it in my whole application. I tried in app.component.ts, but the problem is that it it only works once when you load the page and login, it starts watching the whole app, but when it logs you out it doesn't work anymore because app.component onInit only triggers once, unless the page is reloaded. I have no idea how to make this without having to copy this code in every component of my app. Any ideas?
Here's my code:
This component is injected in my home.component.ts

import { Component, OnInit, NgZone, ChangeDetectorRef } from '@angular/core';
import { ProvisionedService } from '../../devices/provisioned-list/provisioned.service';
import { UsersService } from '../../users/users.service';
import { fromEvent, merge, interval, Observable, of, Subscription } from 'rxjs';
import { switchMap, take, skipWhile, takeLast, skipUntil, tap } from 'rxjs/operators';
import { FuseConfirmDialogComponent } from "@fuse/components/confirm-dialog/confirm-dialog.component";
import { MatDialogRef, MatDialog } from "@angular/material";
import { StorageService } from '../../common/services/storage.service';
import { AuthService } from '../../common/services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  deviceList: DeviceModel[];
  devicesAlive: any;
  vanillaDevices: DeviceModel[];
  getDevicesInfoLoop: any;
  isAlive: any;
  invitationList: InvitationModel[];
  deviceId: any

  inactivityTime: number = 15;

  timeLapsedSinceInactivity: number = 0;
  seconds: number = this.padZero(0);
  subscription: Subscription;
  observeable$: Observable<any>;
  mergedObservable$: Observable<any>;
  event: Event;
  confirmDialogRef: MatDialogRef<FuseConfirmDialogComponent>;

  public inactivityTimerEvent: Array<any>[] = [[document, 'click'], [document, 'wheel'], [document, 'scroll'], [document, 'mousemove'],
   [document, 'keyup'], [window, 'resize'], [window, 'scroll'], [window, 'mousemove']];

  constructor(private provisionedService: ProvisionedService, private VanillaService: VanillaService,
    private UsersService: UsersService, public _ngZone: NgZone,
    public _cd: ChangeDetectorRef,
    public matDialog: MatDialog,
    public storageService: StorageService,
    private authService: AuthService,
    private router: Router) {
  }

  ngOnInit() {

    let observableArray$: Observable<any>[] = [];

    this.inactivityTimerEvent.forEach(x => {
      observableArray$.push(fromEvent(x[0], x[1]))
    })
    this.mergedObservable$ = merge(...observableArray$);

    this.startTimer(event);

  }

  public createObserable(): void {
    this._ngZone.runOutsideAngular(() => {

      this.observeable$ = this.mergedObservable$
      .pipe(
        switchMap(ev => interval(1000).pipe(take      (this.inactivityTime))),

        tap(value => this.isItTimeToShowPopUp(value)),

        skipWhile((x) => {
          this.timeLapsedSinceInactivity = x;
          return x != this.inactivityTime - 1
        })
      );

      this.subscribeObservable();
    })

  }

  public isItTimeToShowPopUp(val: number) {
    let timeLeftForInactive = this.inactivityTime - val;
    if (timeLeftForInactive <= 15) {

      this.timeLapsedSinceInactivity = timeLeftForInactive;
      this.seconds = this.padZero(timeLeftForInactive % 15);
      this._cd.detectChanges();
      console.log(timeLeftForInactive);
    }

    if(timeLeftForInactive === 1) {
      this.authService.removeUserData();
      this.storageService.removelocalStorageData();
      this.router.navigate(['/login']);

    }
    }

  public subscribeObservable() {
    this.subscription = this.observeable$.subscribe((x) => {
      console.log(`subscribed for ${x + 1} sec`);
      this.unsubscribeObservable()
    })
  }
  public padZero(digit: any) {
    return digit <= 9 ? '0' + digit : digit;
  }

  public unsubscribeObservable() {
    console.log('  unsubscriebd')
    this.subscription.unsubscribe();
  }

  public startTimer($event) {
    this.createObserable();
    console.log('subscription started');
  }
  public stopTimer(event) {
    if (this.subscription && !this.subscription.closed) {
      this.seconds = this.padZero(0);
      this.unsubscribeObservable();
    }
  }

}

A: You should put your code in app.component.ts Or better make separate service which handles this.
So that it will be available to the whole app.

A: Yes, you are right. When I implemented session idle timeout feature in my app, this post helped me.
[https://stackoverflow.com/a/51651151/12222270]
Here goes my app.component.ts
import { Component, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/index';

@Component({
  providers: [],
  selector: 'intellect-app',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html'
})

export class AppComponent {

  private userActivity;
  private userInactive: Subject<any> = new Subject();

  public constructor(
    private router: Router
  ) {

    this.startTimer();

    this.userInactive.subscribe(() => this.router.navigateByUrl('/login'));

  }

  private startTimer() {

    this.userActivity = setTimeout(() => this.userInactive.next(undefined), 5000);

  }

  @HostListener('window:resize')
  @HostListener('window:scroll')
  @HostListener('window:mousemove')
  @HostListener('document:click')
  @HostListener('document:wheel')
  @HostListener('document:scroll')
  @HostListener('document:mousemove')
  @HostListener('document:keyup') resetTimer() {

    clearTimeout(this.userActivity);

    this.startTimer();

  }

}


text:
Q: How to gain speed up in this recursive tree with openMP? I wrote a small code that grows a graph recursively and afterwards free the nodes too (shown below). I am compiling the code with mpicc with and without the -fopenmp flag.
Running the code with time (time mpirun ./a.out) I get a real time of 4.259 s, but I get a huge penalty using openmp directives (shown in the code) - real time is now 10.744 s. I have been trying some settings to set the numbers of threads etc., but I do not get any speed up.
Is there something more I can set to achieve more parallelism and performance gains? or is the code so small and has dependencies between parent and offspring nodes blocking any potential gains?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

struct tree_node{
    int value;
    struct tree_node *left_node, *right_node;
};

typedef struct tree_node tree_node_t;

tree_node_t* new_node(int value){
    tree_node_t *p = (tree_node_t*) malloc(sizeof(tree_node_t));
    p->value = value;
    p->left_node = p->right_node = NULL;
    assert((p->value > 0 || p->value == 0) && p->value < 10);
    return p;
}

void tree_grow(tree_node_t* parent, int depth){
    if(depth == 0){
        return;
    }
    #pragma omp task
    {
        #pragma omp task
        {parent->left_node = new_node(rand() % 10);}
        #pragma omp task
        {parent->right_node = new_node(rand() % 10);}
        #pragma omp task
        {tree_grow(parent->left_node, depth-1);}
        #pragma omp task
        {tree_grow(parent->right_node, depth-1);}
    }
}

void branch_cutting(tree_node_t* current){
    if (current == NULL){
        return;
    }
    #pragma omp task
    {
        #pragma omp task
        {branch_cutting(current->left_node);}
        #pragma omp task
        {branch_cutting(current->right_node);}
    }
    #pragma omp task
    free(current);
}

int main (int argc, char **argv)
{
    //omp_set_dynamic(0);
    //omp_set_num_threads(6);
    tree_node_t *root = new_node(0);
    tree_grow(root, 25);
    printf("tree grown and now freeing the memory...");
    //#pragma omp taskwait
    branch_cutting(root);
    printf("tree is removed\n");
    return 0;
}