How to implement global messaging system in drupal for multiple sites?

Question: I have more than 100 sites that need to be maintained. So I am looking for way to put up a notice message for this group of sites. For example: We are having maintenance scheduled for tomorrow 10 PM. The message will be persisting for a time being for all the sites.
Here I am assuming that there should be a central node from where we can push a message to all sites at once and delete when required.
So, I am looking for some help if there is already existing set of tools or way I can implement the workflow.

I have tried Drupal Remote Dashboard module, the module seems to
  offer site monitoring from master node (site), but it doesn't seem to
  offer the global messaging option.
Answer: The nice thing in the "Drupal Remote Dashboard" module that you can run cron on your sites, so I would suggest that you build a custom messaging module that pull messages from master site (using cron to fire that).
- you can use services module to push your messages out
Answer: You can have a separate maintenance.html page in your web root and copy of vhosts file for all of your sites something as
site.conf.live
site.conf.maintenance

Inside site.conf.live webroot will be drupal installation while in site.conf.maintenance webroot will be maintenance.html page.
So at a time any of the two file will be synlinked to original vhost file which will decide whether site is live or in maintenance. You can create a script to update all symlinks from live to maintenance and another one from maintenance to live.
As a admin you will have to login using server ip
Updated Answer
Option 1.
You can use combination of features module + strongarm and a custom module.
Custom Module will hold configuration form and logic to show splash message. On one of your site you will update message to show in the configuration page from your custom module, pull it in features, push the feature across all sites, it will require scripts to automate code push/pull, feature revert and turn on/off of custom module.
Option2.
You can try using third party tools like Web-Engage. It has a drupal integration module also. You can try it can provide you one place for setting up notification.
Option3.
You can have a custom table in all your sites. with columns as Message ID, Message, Timestamp, write a small scripts which loops over all your sites connect to mysql one by one and insert a new message row to the message table. To show the message you can create a custom module which pulls the latest entry from your custom message table and show on a popup, again a small script which all turn on/off this module by drush command looping all your sites.
Comment: thanks for the answer @arpitr but my goal here is to put the persisting notice message on the sites, prior to taking site in maintenance. And the message could be something like "Events happening on 2016"  :)
Comment: @shrish added few more pointers if it helps you. Check under updated answer.
Answer: Worth looking.
https://www.drupal.org/project/site_notice
Use cases for notices may include:
Scheduled downtime
Holiday office hours
Policy updates
New features
Comment: This module isn't useful in it's current state, because it doesn't allow you to set up notices for multiple sites at one. But there is planned Drush integration, which would allow to automate work using something like [Ansible](http://ansible.com).
Answer: Solution 1:
If the websites are hosted on the same machine you could use redis module and Implement the pub/sub messaging protocol between websites using redis api in your case you could have one website(node) acts as publisher and others acts as subscriber and using nodejs to run queries against DB to put site under maintaince or what ever you want
Solution 2:
Or you could implement the same technique with socket io with nodejs too if it was not in the same machine using any headless browser tools like phantomJs to start socket connect without opening browser session.
My solutions may need extra work outside drupal framework
Answer: Below is an approach based on site building techniques only, which only uses commonly used modules with a stable release, and leaves a lot of options open for further refinements.
Step 1
Define a content type in your "master" site (= cfr. your "central node"), with these custom fields:

notice message: to store the actual message to be shown.
date/time from: the start date and time for the message to be shown.
date/time to: the end date and time for the message to be shown.

Using content editing features, create a node in this master site for each message to be shown "somewhere in the future". You may want to set permissions for these kinds of nodes to be created by selected roles only.
Step 2
Define the same content type in each "slave" site (= cfr. your "group of sites"). You can probably automate this process (so that you don't have to do this manually "over 100 times" ...), using export/import features, e.g. by using the Features module.
Step 3
Implement a process to periodically "copy" the nodes created in the master site to each of the slave sites. A few possible solutions for this:

Use the Drupal-to-Drupal data migration module.
Use the Feeds integration of the Forena module.

Step 4
In each of the slave sites, use the Rules module to create:

a Rules component "Display notice messages" with these specs:

use the "node id" as a parameter.
Condition: current date/time is between date/time from and date/time to.
Action: display notice message in the Drupal message area.

a rule with these specs:

Event: when (selected) content is "going to be viewed". Attention: that's different from "when viewing content"!
Action: Loop over each of the existing nodes as created in step 3, and execute the Rules component "Display notice messages" (passing the node id as a parameter).

Step 5
To remove the obsoleted nodes later on (cfr. your "delete when required"), simply build a list of them using the Views module, and combine it with the Views Bulk Operations module so that the resulting list can be processed by the Rules module (to delete those nodes again).
Answer: You will not find a simpler solution
TL;DR : Use RSS and PHP!
Caveat : Unfortunately not as elegant as a simple module installation & configuration, This involves creating a feed view, and php code to process the rss in a block.
Step 1
a) On the control site, use nodequeue to easily insert and remove message nodes.
In a Feed(rss) type view add Nodequeue as relationship and sort criteria
Step 2
Make a block on each other site with the following php :
<?php
    $rss = new DOMDocument();
    $rss->load('http://mydrupalsite.org/message/feed/');
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array (
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            );
        array_push($feed, $item);
    }
    $limit = 1;
    for($x=0;$x<$limit;$x++) {
        $title = str_replace(' & ', ' & ', $feed[$x]['title']);
        $description = $feed[$x]['desc'];
        echo '
'.$title.'
';
        echo '
'.$description.'
';
    }
?>

Adjust the output to your own liking.
The advantage of using Nodequeue, is that you can keep your node(for sytle or generic message), and just remove it from the queue.
(We tried going with contrib modules such as aggregator, feeds, etc, but had issues with cache and specifically cron being used to import items, that would persist once messages were removed from the source feed!)


OpenVPN Server Ethernet Bridging Question

Question: I am having a difficult time properly configuring an ethernet bridge using OpenVPN 2.0.9 install on CentOS 5 ( VPN server ). The goal that I am trying to complete is to connect a VM ( instance running on the same CentOS machine ) acting as a Microsoft Business Contact Manager server. I would then like this "BCM server" to serve Windows XP clients on 192.168.1.0/24 network as well as clients connecting from VPN ( 10.8.0.0/24 ). The setup as it is now was based off a known working configuration. The problem with the working configuration was that it would allow to the client to connect and access everything running on the VPN server ( SVN, Samba, VM Server ) but not any computers on the 192.168.1.0/24 network.
I must disclose that the VPN server is behind a router/firewall. Ports are being forwarded correctly ( again, clients were able to connect to the VPN server with no problem. netcat confirms the udp port is open as well ).
current ifconfig output
br0       Link encap:Ethernet  HWaddr 00:21:5E:4D:3A:C2
          inet addr:192.168.1.169  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::221:5eff:fe4d:3ac2/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:846890 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3072351 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:42686842 (40.7 MiB)  TX bytes:4540654180 (4.2 GiB)

eth0      Link encap:Ethernet  HWaddr 00:21:5E:4D:3A:C2
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
          RX packets:882641 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1781383 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:82342803 (78.5 MiB)  TX bytes:2614727660 (2.4 GiB)
          Interrupt:169

eth1      Link encap:Ethernet  HWaddr 00:21:5E:4D:3A:C3
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
          RX packets:650 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1347223 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:67403 (65.8 KiB)  TX bytes:1959529142 (1.8 GiB)
          Interrupt:233

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:17452058 errors:0 dropped:0 overruns:0 frame:0
          TX packets:17452058 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:94020256229 (87.5 GiB)  TX bytes:94020256229 (87.5 GiB)

tap0      Link encap:Ethernet  HWaddr DE:18:C6:D7:01:63
          inet6 addr: fe80::dc18:c6ff:fed7:163/64 Scope:Link
          UP BROADCAST RUNNING PROMISC MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3086 errors:0 dropped:166 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 b)  TX bytes:315099 (307.7 KiB)

vmnet1    Link encap:Ethernet  HWaddr 00:50:56:C0:00:01
          inet addr:192.168.177.1  Bcast:192.168.177.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:fec0:1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4224 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

vmnet8    Link encap:Ethernet  HWaddr 00:50:56:C0:00:08
          inet addr:192.168.55.1  Bcast:192.168.55.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:fec0:8/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4226 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

current route table
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.55.0     *               255.255.255.0   U     0      0        0    vmnet8
192.168.177.0   *               255.255.255.0   U     0      0        0    vmnet1
192.168.1.0      *               255.255.255.0   U     0      0        0    br0

current iptables output
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

server_known_working.conf
local banshee
port 1194
proto udp
dev tap0
ca ca.crt
cert banshee_server.crt
key banshee_server.key
dh dh1024.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
push "route 192.168.1.0 255.255.255.0"
client-to-client
keepalive 10 120
tls-auth ta.key 0
user nobody
group nobody
persist-key
persist-tun
status openvpn-status.log
verb 4

The following is the current CentOS server config file.
server_ethernet_bridged.conf ( current )
local 192.168.1.169
port 1194
proto udp
dev tap0
ca ca.crt
cert server.crt
key server.key
dh dh1024.pem
ifconfig-pool-persist ipp.txt
server-bridge 192.168.1.169 255.255.255.0 192.168.1.200 192.168.1.210
push "route 192.168.1.0 255.255.255.0 192.168.1.1"
client-to-client
keepalive 10 120
tls-auth ta.key 0
user nobody
group nobody
persist-key
persist-tun
status openvpn-status.log
verb 6

The following is one of the client's config file that was used with the known working configuration.
client.opvn
client
dev tap
proto udp
remote XXX.XXX.XXX 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca client.crt
cert client.crt
key client.key
tls-auth client.key 1
verb 3

I have tried the HOWTO provided by OpenVPN as well as others
http://www.thebakershome.net/openvpn_tutorial?page=1
with no success.
Any help or suggestions would be appreciated.
Comment: What's with the bridging?  I don't see any reason to be bridging anything here.
Comment: Thanks for the reply. My understanding was that the bridged interface was needed to allow clients connecting from the VPN to be on the same 192.168.1.0/24 network behind the VPN server.
Answer: Unless you really need the vpn clients to appear to be on the same layer 2 subnet, I would avoid bridging.
if 192.168.1.0/24 is your current internal subnet, configure openvpn to assign 192.168.2.0/24 or so to VPN clients.
then you need to do one of two things:

configure the openvpn server to NAT vpn addresses
configure your router to add a static route for 192.168.2.0/24 through your openvpn server

1 can be as simple as
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j MASQUERADE

This will work as long as you don't care that all vpn clients will show up as the same address on the server.  this way also makes it impossible for a connection to be made TO a vpn client from the lan.
2 is not really that complicated, in IOS land it would be just
ip route 192.168.2.0 255.255.255.0 a.b.c.d

where a.b.c.d is the internal ip address of your openvpn server.  A static route can even be added on a cheap linksys router.
Answer: I am have a similar setup where I have:
Internal LAN <--> OpenVPN Server (behind our enterprise firewall) <--> OpenVPN Client (which also acts as a FW/DHCP server) <--> Subnet behind it
Basically we have the OpenVPN server internally act as the server and the OpenVPN client connects to it using tun interfaces (we use routing). Through that tunnel, I then use ipforward rules and route rules to allow all traffic from the internal LAN to flow through the VPN tunnel to the external subnet that lies behind the OpenVPN client. It's normal setup of OpenVPN, plus just adding the correct routes and also adding the ccd and iroute commands as well in the server.conf to give you access to that subnet behind the OpenVPN client. Essentially with this setup you just extend your local LAN to an off site location with an encrypted tunnel using routed interfaces instead of bridging. Hope that helps some, I never have messed with the bridging aspect of it.
Answer: bridging can be made to work in this case, although strictly speaking it's not necessary. Try removing the lines
push "route 192.168.1.0 255.255.255.0 192.168.1.1"
client-to-client

from the server config , as they should not be required in bridging mode. After a client connects, try pinging the VPN server IP and the default LAN IP.
Also, post the output of
brctl show

HTH,
JJK


Handling async request with React, Redux and Axios?

Question: I am new to React JS and Redux and it has been too overwhelming to get going. I am trying to make a POST request using Axios, but I am unable to make it. May be I am missing something in the container file. Below is the code. Check plnkr
Update:  I am getting @@redux-form/SET_SUBMIT_SUCCEEDED message after submitting. But when I am checking in the network tab, I don't see the call to API. And also when I am consoling the submitted values, I see only name and fullname values. It doesn't consist of logo and details. What am I missing?
Component file
   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { Field,reduxForm } from 'redux-form'
   import {   Columns,Column, TextArea, Label,Button  } from 'bloomer'
   import FormField from 'FormField'

   const validate = (values) => {
     const errors = {}
    const requiredFields =
      ['organizationName','organizationFullName','organizationDetails']

    requiredFields.forEach((field) => {
     if (!values[field]) {
     errors[field] = 'This field can\'t be empty!'
    }
  })
     return errors
}

  const formConfig = {
   validate,
   form: 'createOrganization',
   enableReinitialize: true
   }

  export class CreateOrganization extends PureComponent {
   static propTypes = {
     isLoading:PropTypes.bool.isRequired,
     handleSubmit: PropTypes.func.isRequired, // from react-redux
     submitting: PropTypes.bool.isRequired // from react-redux
    }
   onSubmit = data => {
     console.log(data)
   }
  render () {
     const { handleSubmit,submitting,isLoading } = this.props
      return (
        <Columns isCentered>
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))} >

          <Column isSize='3/6' >
            Organization Name
            <Field
              name="organizationName"
              component={FormField}
              type="text"
              placeholder="Organization Name"
            />
          </Column>

          <Column isSize='3/6'>
            Organization Full Name
            <Field
              name="organizationFullName"
              component={FormField}
              type="text"
              placeholder="Organization Full Name"
            />
          </Column>

           <Column isSize='3/6'>
            Organization Logo
            <Input
              name="organizationLogo"
              type="file"
              placeholder="Logo"
            />
          </Column>

          <Column isSize='3/6'>
            Organization Details
                <TextArea placeholder={'Enter Details'} />
          </Column>

          <Column >

              <Button type="submit" isLoading={submitting || isLoading} isColor='primary'>
                Submit
              </Button>

              <Button type="button" isColor='danger'>
                Cancel
              </Button>
          </Column>

        </form>
      </Columns>
    )
  }
}

  export default reduxForm(formConfig)(CreateOrganization)

Container File
   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { connect } from 'react-redux'
   import Loader from 'Loader'
   import organization from 'state/organization'
   import CreateOrganization from '../components/createOrganization'

   export class Create extends PureComponent {
   static propTypes = {
     error: PropTypes.object,
     isLoaded: PropTypes.bool.isRequired,
     create: PropTypes.func.isRequired,
    }
    onSubmit = data => {
      this.props.create(data)
    }

    render () {
      const { isLoaded, error } = this.props
    return (
       <CreateOrganization onSubmitForm={this.onSubmit} isLoading=
         {isLoading} />
     )
   }
 }

   const mapStateToProps = state => ({
     error: organization.selectors.getError(state),
     isLoading: organization.selectors.isLoading(state)
   })

    const mapDispatchToProps = {
      create: organization.actions.create
    }

  export default connect(mapStateToProps, mapDispatchToProps)(Create)

Comment: First things first, people will begin down voting this question purely because the formatting is awful. Making it hard to read. You can post a codepen example if you're unable to get the formatting right on here. Second, you should be more descriptive in what you need. What's not working? Are you able to get into the callAPI function? Is the response not getting console logged?
Comment: p.s. `` `this.props` is an object **not** a function
Comment: I am not able to get into the call API function. Thank you for your suggestion.Will add changes
Comment: onSubmit should point to a function on the props object.
Comment: And that function will be declared in action?
Comment: Can you link me to a place where this code is posted? I'm losing my mind trying to read it as is :)
Comment: Hi. Here is the link https://plnkr.co/edit/w8H3YvFCunqC3621lmmd?p=preview   But I have just posted code here for reference, since there are lot of dependencies created using webpack.
Comment: 1. containers/createOrganization.js: onSubmit={create} // Where is create coming from?

2. components/createOrganization.js: this.props.onSubmitForm //where is onSubmitForm coming from? You pass onSubmit as a prop in the container but not onSubmitForm
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160034/discussion-between-heblev-and-joshua-underwood).
Comment: seems like theres plenty of answers, just pointing out the `mapDispatchToProps` is malformed here, should be a function mapping dispatch to, well, props
Answer: Your redux action creators must be plain, object and should dispatch and action with a mandatory key type. However using custom middlewares like redux-thunk you could call axios request within your action creators as without custom middlewares your action creators need to return plain object
Your action creator will look like
export function create (values) {

  return (dispatch) => {
     dispatch({type: CREATE_ORGANIZATION});
     axios.post('/url', values)
        .then((res) =>{
            dispatch({type: CREATE_ORGANIZATION_SUCCESS, payload: res});
        })
        .catch((error)=> {
            dispatch({type: CREATE_ORGANIZATION_FAILURE, payload: error});
        })
  }

}

and your reducer will look like
export default (state = initialState, action) => {
  const payload = action.payload

   switch (action.type) {
    case CREATE:

      return {
        ...state,
        loading: true,
        loaded: false
      }

    case CREATE_SUCCESS:
      return {
        ...state,
        data: state.data.concat(payload.data),
        loading: false,
        loaded: true,
        error: null
      }

      }

    case CREATE_FAILURE:

      return {
        ...state,
        loading: false,
        loaded: true,
        error: payload
      }
    default:
      return state
  }
}

now while creating the store you can do it like
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
const store = createStore(
  reducer,
  applyMiddleware(thunk)
);

Apart from this you also need to setUp the redux form
you need to use combineReducers and Provider to pass on the store
import reducer from './reducer';
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form'

export const rootReducer = combineReducers({
   reducer,
   form: formReducer
})

CodeSandbox
Comment: it seems your configuration doesn't allow redux-thunk to submit the action that triggers your api request.
check your `applyMiddleware( your_middleware?, thunk, logger)(createStore)`
Then try to implement the logic without the use of `redux-form`
Comment: check this answer and let me know if you face any difficulties
Comment: I  am still getting '@@redux-form/SET_SUBMIT_FAILED' in console
Comment: I added a codeSandbox with all the error rectification, you needed to use combineReducers and set up redux-form in it. Apart from it there were other mistakes like not using Uppercase characters for the Component. Let me know if you still face troubles
Comment: Will have a look. Thanks
Comment: Difficult to produce a similar thing as it has lot dependencies. For ex: callAPI component written in another package and uses redux thunk for async calls. Check my updated plnkr
Comment: I see the callApi function, that need not be there, create essentially replaces callApi
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160259/discussion-between-heblev-and-shubham-khatri).
Comment: @Karlos, what do you mean
Comment: redux-thunk is very sensible, review your configuration having a closer look at https://www.npmjs.com/package/redux-thunk, then try to free yourself from the use of `redux-form`
Comment: Hi, @ShubhamKhatri this method is not working on the post request. Can you please help ?? `export function loginDetails(input) { let url = "admins/api_login"; debugger; return (dispatch) => { dispatch({type: "LOGIN_FETCH"}); ApiCall.postApiCall(url, input) .then((response) => { dispatch({type: "LOGIN_SUCCESS", payload: response}); }) .catch((error) => { dispatch({type: "LOGIN_FAIL", payload: error}); }) } } `
Comment: `const mapStateToProps = (state) => { return { sessionReducer: state.sessionReducer }; }; const mapDispatchToProps = (dispatch) => { return { loginDetails: (login_details, loggedIn, error, payload) => { dispatch(loginDetails(login_details, loggedIn, error, payload)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Signin);`
Comment: `const sessionReducer = (state = {INITIAL_STATE},action) => { switch(action.type){ case "LOGIN_FETCH": state={ ...state, login_details: action.payload, loggedIn: false }; break; case "LOGIN_SUCCESS": state={ ...state, loggedIn: true, error: null }; break; case "LOGIN_FAIL": state={ ...state, loggedIn: false, error: action.payload }; break; default: break; } return state; }; export default sessionReducer;`
Comment: @RiyaKapuria, Can you point me to the question you had asked. Also what error or problem you are facing
Comment: https://stackoverflow.com/questions/48162063/how-to-get-normal-json-object-from-promise-object-in-react-redux?noredirect=1#comment83303803_48162063 this is my qus
Answer: You can do that easily with the help of redux-saga.
About redux-saga:
redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures.
Installation:
$ npm install --save redux-saga
or
$ yarn add redux-saga
Please refer to the link : https://github.com/redux-saga/redux-saga
Answer: Redux action creators apparently don't support asynchronous actions which is what you're trying to do with the post request. Redux Thunk should help with this.
You'll want a store.js file that looks like this:
//npm install --save redux-thunk

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducer.js';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk) //needed so you can do async
);

Here is what your actions file would look like. Create becomes an action creator that returns a function that then performs the post request and allows you to do the dispatch there allowing you to update your store/state. :
import axios from 'axios'
import { CREATE_ORGANIZATION, CREATE_ORGANIZATION_SUCCESS, CREATE_ORGANIZATION_FAILURE,

       } from './constants'
import * as selectors from './selectors'

/*
  CREATE ORGANIZATION
*/
//uses redux-thunk to make the post call happen
export function create (values) {
  return function(dispatch) {
    return axios.post('/url', values).then((response) => {
      dispatch({ type: 'Insert-constant-here'})
      console.log(response);
    })
    }
  }

Also, you'll want to pass in the onSubmit method you created into onSubmitForm like this. I'm not sure where isLoading is coming from because I don't see it imported in that container component so you may want to look at that too.:
  <createOrganization onSubmitForm={this.onSubmit.bind(this)} isLoading={isLoading} />

Comment: Is 'Insert-constant-here' an action type like CREATE_ORGANIZATION_SUCCESS for ex?
Comment: Yes put in the action type there.
Comment: I am still getting '@@redux-form/SET_SUBMIT_FAILED' in console
Comment: I updated my answer. I think you'll want to make some changes there
Comment: Still not calling the API
Comment: Does it give you the same error "SET_SUBMIT_FAILED"?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160256/discussion-between-heblev-and-dream-cap).
Answer: I would suggest using redux-promise-middleware. This library requires that the action have a property named payload that is a promise and this is easy with axios. It then integrates with Redux to suffix the root action type (e.g. GET_CUSTOMERS) with PENDING, FULFILLED, and REJECTED and fires those actions.
Firing the action is the same as any other action.
Store
import {applyMiddleware, compose, createStore} from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers';

let middleware = applyMiddleware(promiseMiddleware());
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(middleware);

export default createStore(reducer, enhancer);

Action
export function getCustomers() {
  return {
    type: 'GET_CUSTOMERS',
    payload: axios.get('url/to/api')
      .then(res => {
        if (!res.ok) throw new Error('An error occurred.');
        return res;
      })
      .then(res => res.json())
      .catch(err => console.warn(err));
  };
}

Reducer
export default function(state = initialState, action) => {
  switch (action.type) {
    case 'GET_CUSTOMERS_PENDING':
      // this means the call is pending in the browser and has not
      // yet returned a response
      ...
    case 'GET_CUSTOMERS_FULFILLED':
      // this means the call is successful and the response has been set
      // to action.payload
      ...
    case 'GET_CUSTOMERS_REJECTED':
      // this means the response was unsuccessful so you can handle that
      // error here
      ...
    default:
      return state;
  }
}


Combinatorial Interpretation

Question: I am looking for a combinatorial interpretation to $f(n)=\sum\limits_{k=0}^{n}(-1)^{n-k}\binom{n}{k}g(k)$, where
1.) $g(n)=\binom{nr}{s}$
2.) $g(n)=\binom{\binom{n}{r}}{s}$
3.) $g(n)=2^{\binom{n}{2}}$
Comment: You phrase it as if you are giving someone an order --- that's not appreciated. Also, you give no indication that you have put the slightest effort into the problem, no indication of what you do or don't know about it. You don't make it easy to help you.
Comment: I am sorry for that. I did not mean to be rude. Well, the $f(n)$ part looks to me like Inclusion-Exclusion principle. So I guess it is about counting the intersections of some kind of sets. Other than that I can not really think of anything. Thank you!
Comment: You might find the answers to [this question](http://math.stackexchange.com/q/55659/2370) helpful.
Answer: Hints:
$$f(n)=\sum_{k=0}^{n}(-1)^{n-k}\binom{n}{k}g(k)=\sum_{m=0}^{n}(-1)^{m}\binom{n}{m}g(n-m)$$
Try to use the Inclusion–exclusion principle: Find sets $A_1,...,A_n$ such that the intersection of any $m$ of them is of size $g(n-m)$. Give a combinatorial interpretation (as bad properties) to $A_1,...,A_k$, and then $f(n)$ is the amount of elements with no 'bad' properties.
For example:
In $(3)$ you can take $A_k$ to be the set of all labeled graphs on $n$ vertices in which the vertex $k$ is isolated (not connected to any other vertex). Then $f(n)$ will be the number of graphs on $n$ vertices without isolated vertices.
Comment: Thank you, @DennisGulko for your answer. I do not understand what you mean by recombination interpretation. Would you give me an example, please!
Comment: Stupid auto-correct! I will edit my answer now.
Comment: So in the case of 3.) it would mean that $f(n)$ is the number of elements with no two 'bad properties', right?
Comment: No - still without any bad properties. For example, you can take $A_k$ to be the set of all labeled graphs on $n$ vertices in which the vertex $k$ is isolated (not connected to any other vertex). Then $f(n)$ will be the number of graphs on $n$ vertices without isolated vertices.
Comment: So $f(n)$ is the number of graphs on n vertices without isolated vertices because $2^{\binom{k}{2}}$ is the number of elements in the intersection of all sets of labeled graphs on $n$ vertices with an isolated vertex?!
Comment: $2^{\binom{n-m}{2}}$ is the number of graphs on $n$ vertices in which the vertices $1,...,m$ are isolated.
Comment: Thank you, Dennis. However, I do not have much experience with combinatorics so I am stuck with coming up with ideas for the other two. I know that 1.) it is choosing $s$ elements out of a $(n-m)r$-set and 2.) choosing $r$ elements from a $n-m$-set and then choosing $s$ elements from those. Still I dont see how this can be intersections of sets with bad properties.

Combinatorial Interpretation


Find text between key phrases

Question: I have a var that have some text in:
<cfsavecontent variable="foo">
element.password_input=

 $${label_text}
<input name="$${input_name}" id="$${input_id}" value="$${input_value}" type="password" />

# END element.password_input
element.text_input=

 $${element_label_text}
<input name="$${element_name}" id="$${element_id}"
value="$${element_value}" type="text"
class="textInput"  />

# END element.text_input
</cfsavecontent>

and I am trying to parse through the var to get all of the different element type(s) here is what I have so far:
ar = REMatch( "element\.+(.*=)(.*?)*", foo )

but it is only giving me  this part:
element.text_input=
element.password_input=

any help will be appreciated.
Answer: Your immediate problem is that by default . doesn't include newlines - you would need to use the flag (?s) in your regex for it to do this.
However, simply enabling that flag still wont result in your present regex doing what you're expecting it to do.
A better regex would be:
(element\.\w+)=(?:[^##]+|##(?! END \1))+(?=## END \1)

You would then do ListFirst(match[i],'=') and ListRest(match[i],'=') to get the name and value. (rematch doesn't return captured groups).
(Obviously the #s above are doubled to escape them for CF.)

The above regex dissected is:
(element\.\w+)=

Match element. and any alphanumeric, placed it into capture group 1, then match = character.
(?:
    [^##]+
|
    ##(?! END \1)
)+

Match any number of non-hash characters, or a hash not followed by the ending token (using negative lookahead (?!...)) and referencing capture group 1 (\1), repeat as many times as possible (+), using a non-capturing group ((?:...)).
(?=## END \1)

Lookahead (?=...) to confirm the variable's ending token is present.

Find text between key phrases


Hide package in conda environment (without removing)

Question: I need to check if a piece of Python code works as expected when a given package is installed and when it is not. My conda working environment already has this package installed, and I'm looking for a way to "hide" it. I know I could:

Remove + test + re-install the package
Create a brand new environment without this package

but:

I need to run checks multiple times as the code evolves, and this quickly becomes a hassle
The environment is rather large (numerous packages) and I also need to test this on other packages, which means I'd need several similar environments

It would be ideal if I could just tell conda: "act as if this package is not installed". Can this be done?
Answer: How about creating a mock module with the same name and put it first in your PYTHONTPATH? Its only content could be
raise ImportError

This way, any import in your code will receive an ImportError as if it hadn't found the module.
To revert, simply reset your PYTHONPATH
Comment: Thanks for the suggestion but I don't want the code to fail, I want it to check if the package is there and take a different route if it isn't.
Comment: and you are catching `ImportError` to decide the route?
Comment: I am. (more chars required...)
Comment: How about, instead of an empty mock module you have one that raises `ImportError` when imported or renaming the package folder in the `site-package` folder to mock uninstall
Comment: Raising `ImportError` manually is an easy fix that I did not think of. Would you like to add this to your answer and I'll accept it?


Quick true false integral spherical coordinates question

Question:
$$\int_0^{2\pi}\int_0^2\int_{\pi/3}^{2\pi/3}r^2\sin\varphi \operatorname{d}\varphi\operatorname{d}r\operatorname{d}\theta$$
  represents the volume of the solid enclosed by the sphere $x^2+y^2+z^2=4$ and the planes $z=1$ and $z=-1$.

This is a true or false question. I see $x^2+y^2+z^2=4$ gets transformed into $r^2=4$ i.e. $r=2$ and $z=1$ and $z=-1$ get transformed into $2\cos\varphi=1$ and $2\cos\varphi=-1$, i.e. $\varphi=\pi/3$ and $\varphi=-\pi/3$. The part that is freaking me out, is I've only done problems using spherical coordinates where I do the order of integration as
$$\operatorname{d}r\operatorname{d}\theta\operatorname{d}\varphi.$$
Answer: false  ... the volume of the cone is missing.

the volume element in spherical coordinate does not go straight in blocks. It goes radially. If you rotate the below figure by $360^\circ$ and from $\pi/3 \to 2 \pi/3$ with length radius $2$ then the above picture is what you get (including opposite side).

You should add the volume of the cone (2x) to get the volume you require.


Problem when using return key to move to TDBGrid from TEdit

Question: In a search form I have two components, a TEdit and and TDBGrid.   The user enters text into the TEditand in the TEdit.OnChange event I search for matching items in a table using a query. These are displayed in a TDGrid.  The event only triggers when the user has entered more than three characters in the TEdit.Textto cut down the overhead.
The problem occurs when the search has returned all possible records and the user wants to select one of the records displayed in the TDBGrid.  While I told the users to use the Tab key (or the mouse) to switch from the TEdit to the TDBGrid, they use the return key to do this in another application and are insisting that they should be able to do the same thing in the application I'm altering/adding to.  I can understand this, but the problem is that if I use
if (key = VK_RETURN) then key := VK_TAB;

in the TEdit.OnKeyUp event, the original value of the last key pressed in the TEdit is "remembered" as VK_RETURN and is passed to the TDBGrid's OnKeyUp event.  Since I have other actions triggered in that event, I get undesired things happening as soon the the TDBGrid gains focus because they also want to select the correct row in the grid by pressing the return key again.
Therefore what I want to do is to "cancel" the key value passed to the TDBGrid from the TEdit. I tried using if (Sender = TEdit) then Key := VK_CANCEL; in the DGBrid's OnKeyUp event but I get a compiler "Incompatible types" error and I can't find anything to tell me how I should use it in this situation.
Is this possible?  Or am I going about this the wrong way?
Thanks in advance!
Answer: I believe the following approach satisfies your needs and I suspect it to be the shortest such approach:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
    Key := #0;
end;

procedure TForm1.Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_RETURN then
  begin
    PostMessage(Handle, WM_NEXTDLGCTL, 0, 0);
    Key := 0;
  end;
end;

This will make Enter, in Edit1, move focus to the next control. This is accomplished by posting the form a WM_NEXTDLGCTL message. The OnKeyPress handler is needed to suppress the "invalid input" message beep.
For bonus points, do
PostMessage(Handle, WM_NEXTDLGCTL, Ord(ssShift in Shift), 0);

instead to have Shift+Enter correspond to Shift+Tab.
I'm not quite sure I like this entire idea, though. I think I prefer to have Enter act on key down instead. The target control shoudn't care about this key up message.
Comment: Thanks Andreas, that works a treat.   I put the Edit1.OnKeyUp code into Edit1.OnKeyDown as you suggested.  Cheers!
Answer: Just to add to Andreas answer, I have used the same approach.  There are 3 events you can play around with, onkeydown, onkeypress, onkeyup.  At some point you will probably have to assign the key to null to avoid the "beep".  The other thing to watch out for are unintended side effects, like moving 2 fields instead of one as has happened to me in the past.
Comment: I don't see this as adding any value. You've basically just agreed with Andreas and provided no information not already provided in Andreas' answer, including the information about *assigning the key to null to avoid the "beep"*. This space is to be used to provide an answer to the question, not just comment on another answer.
Comment: I would have preferred adding a comment but not enough reputation.
Comment: You can't use the answer space to bypass not having the comment privilege. This space is ONLY for answering the question asked.
Comment: It was never my intention to "bypass" the comment privilege.
Comment: But your non-answer is still here, even after you've been made aware that it shouldn't be.
Comment: Delete your comment about me just wanting to bypass the comment privilege and I will delete my answer.


Using plupload with aspx page form submission

Question: A little background. I am using plupload to upload files within my application.
The url passed is the url to my aspx where I handle all the processing of the file.
What happens is, the first time you browse for and select a file nothing happens. The second time, it posts back both form submissions immediately.
Can you find any glaring omissions from the below code?
// Initialize the uploader
uploader = new plupload.Uploader({
                    runtimes: 'html5,gears,flash,silverlight,browserplus',
                    browse_button: 'browse',
                    drop_element: 'uploadContainer',
                    container: 'uploadContainer',
                    max_file_size: '10mb',
                    multi_selection: false,
                    url: 'someURLHere',
                    filters: [{ title: "Pdf files", extensions: "pdf"}]
                });

FilesAdded event fires when (obviously) a file is added
// File Added event
uploader.bind('FilesAdded', function (up, files) {
                    $.each(files, function (i, file) {
                        // Add element to file object
                        file.formattedSize = plupload.formatSize(file.size);

                    $('form').submit();

                    // Reposition Flash/Silverlight
                    up.refresh();
                });

Submit the form
$('form').submit(function (e) {
                    uploader.start();
                    e.preventDefault();
                });

HTML
<form id="uploadForm">

     Drag and Drop items here</span

     <button id="browse" class="ButtonSubmit">Browse...</button>

</form>

I was using this great answer as a starting point. using Plupload with ASP.NET/C#
Answer: The fix to this is actually very simple.
I needed to init() the uploader BEFORE I bound any events to it, as the init() actually binds some default handlers.
// Initialize the uploader
uploader = new plupload.Uploader({
                    runtimes: 'html5,gears,flash,silverlight,browserplus',
                    browse_button: 'browse',
                    drop_element: 'uploadContainer',
                    container: 'uploadContainer',
                    max_file_size: '10mb',
                    multi_selection: false,
                    url: 'someURLHere',
                    filters: [{ title: "Pdf files", extensions: "pdf"}]
                });

   uploader.init();

   // Then add in any of your event handlers.


Ler colunas exatas csv php

Question: Estou lendo o csv desta forma:
<code>    $handle = fopen($file, "r");
    while ($data = fgetcsv($handle, 1000, ",")) {
        if($row !== 0)
        {
            $dados      = explode(";", $data[0]);
            $VALOR_1        = utf8_encode($dados[1]);
            $VALOR_2        = $dados[2];
            $VALOR_3        = $dados[3];
            $VALOR_4        = $dados[4];
            $VALOR_6        = $dados[11];

                $insert = "
                    INSERT INTO
                        dados
                    VALUES
                    (
                        NULL,
                        '$VALOR_1',
                        '$VALOR_2',
                        '$VALOR_3',
                        '$VALOR_4',
                        '$VALOR_6',
                    )
                ";
                    //$insert_now = mysqli_query($mysqli, $insert);
        }
    }
</code>
A primeira linha do csv contem o título de cada coluna, o csv possuí várias colunas, o problema é que as colunas nem sempre estão posicionadas no mesmo local.
O que preciso é ler o csv, e já deixar informado o título das colunas a serem salvas no bd.
Comment: Coloque o exemplo do `csv`, porque pelo visto o resto já está feito. e para entender melhor a sua duvida precisa de algum exemplo
Comment: No arquivo `csv` tem um separador de colunas, que no seu exemplo é o `;`, isso não está funcionando?
Comment: Você precisa identificar as colunas na tabela! também com é essa tabela que precisa gravar resultados!?
Comment: Mas se esta usando fgetcsv pra que então usar explode? Não tem necessidade disto. Diga-me, qual separador o teu csv usa, é virgula ou ponto-virgula?
Answer: Tente atribuir a uma variável o índice da coluna, dai é independente o posicionamento da mesma...
Exemplo:
<code>$fieldnames = fgetcsv($handle, 1000, ',');
$idx_dado_5 = array_search("dado_5", $fieldnames);
while ($row = fgetcsv($handle , 4096, ',')) {

        $valor_5 = $row[$idx_dado_5];
$insert = "
                INSERT INTO
                    dados
                VALUES
                (
                    NULL,
                    '$VALOR_1',
                    '$VALOR_2',
                    '$VALOR_3',
                    '$VALOR_4',
                    '$VALOR_5',
                )
            ";
}
</code>

Ler colunas exatas csv php


:8:7: error: Variable not in scope: ys :: [a]

Question: ys = [1,2,3,4,5]
last' xs = head (reverse xs)

I wrote this simple function in Haskell using Vscode to get the last element in list.
when I tried to run it on GHCI there was a compilation  error:
*Main> last' xs
<interactive>:2:7: error: Variable not in scope: xs :: [a]

I don't know how to fix it .
Comment: Please include *code*, not *images of code*: see [*Why not upload images of code errors when asking a question*](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). [edit] the question and include code fragments.
Answer: When you try to run last' xs, note that xs is just a name the argument is bound to in the last' function definition, and there is no "variable" with such a name outside the scope of the function itself. You should use the name the list is bound to, namely ys, i.e.  last' ys:
ghci> ys = [1,2,3,4,5]
ghci> last' xs = head (reverse xs)
ghci> last' ys
5

Keep in mind that this solution works only with non-empty lists, because head function is partial and do not return normally on empty list (throws an exception).


"The project 'Web' must provide a value for Configuration" error after migrating to .NET Core 3

Question: I've migrated an ASP.NET Core 2.2 project to Core 3.0 and am getting the error:

The project [Project location] must provide a value for Configuration.

There's not really a lot to go on with that error message, does anyone know how to resolve this error?
This looks like it could be similar to this issue on the dotnet cli github repo.
Answer: The issue turned out to be that I was still referencing Microsoft.AspNetCore.Razor.Design Version="2.2.0" in the .proj file's package references. Deleting that reference (which isn't needed at all as Razor.Design is now part of AspNetCore library) fixed the issue.
Once I'd done that, I then got hundreds of errors about nullable objects being a new feature not compatible with razor. That was because I had <LangVersion>Latest</LangVersion> in my .proj file. Removing that line fixed that issue and got the project running again.
(In some cases you might need to clean and rebuild and/or restart VS too, according to comments on the github thread)
If that doesn't solve it, it's possible that one the NuGet packages used by your project is the cause.  Try removing the dependencies to see if that clears the issue, and then re-add them one at a time to work out which NuGet package is the cause.
Comment: Very useful answer.  It's annoying that it's one of many errors in which there is no way of debugging or solving it apart from either Googling or removing random bits of code/config until it magically works.
Comment: Removing the line and restarting Visual Studio were both required steps. THANKS
Comment: Full list of changes to csproj file here: https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio-mac#update-the-project-file
Comment: I completely agree with this
Comment: You can reinstall all the Nuget packages in one go. Open 'Package Manager Console' and run:

`Update-Package -Reinstall -IgnoreDependencies`
Answer: There is an MS document title "Migrate from ASP.NET Core 2.2 to 3.0".  Under "Update the project file", it states,

"A large number of NuGet packages aren't produced for ASP.NET Core
  3.0. Such package references should be removed from your project file"

The two given as an example are:

Microsoft.AspNetCore.App
Microsoft.AspNetCore.Razor.Design

Below that, you can expand to see all the packages that are  no longer being produced:

Microsoft.AspNetCore
Microsoft.AspNetCore.All
Microsoft.AspNetCore.App
Microsoft.AspNetCore.Antiforgery
Microsoft.AspNetCore.Authentication
Microsoft.AspNetCore.Authentication.Abstractions
Microsoft.AspNetCore.Authentication.Cookies
Microsoft.AspNetCore.Authentication.Core
Microsoft.AspNetCore.Authentication.OAuth
Microsoft.AspNetCore.Authorization.Policy
Microsoft.AspNetCore.CookiePolicy
Microsoft.AspNetCore.Cors
Microsoft.AspNetCore.Diagnostics
Microsoft.AspNetCore.Diagnostics.HealthChecks
Microsoft.AspNetCore.HostFiltering
Microsoft.AspNetCore.Hosting
Microsoft.AspNetCore.Hosting.Abstractions
Microsoft.AspNetCore.Hosting.Server.Abstractions
Microsoft.AspNetCore.Http
Microsoft.AspNetCore.Http.Abstractions
Microsoft.AspNetCore.Http.Connections
Microsoft.AspNetCore.Http.Extensions
Microsoft.AspNetCore.HttpOverrides
Microsoft.AspNetCore.HttpsPolicy
Microsoft.AspNetCore.Identity
Microsoft.AspNetCore.Localization
Microsoft.AspNetCore.Localization.Routing
Microsoft.AspNetCore.Mvc
Microsoft.AspNetCore.Mvc.Abstractions
Microsoft.AspNetCore.Mvc.Analyzers
Microsoft.AspNetCore.Mvc.ApiExplorer
Microsoft.AspNetCore.Mvc.Api.Analyzers
Microsoft.AspNetCore.Mvc.Core
Microsoft.AspNetCore.Mvc.Cors
Microsoft.AspNetCore.Mvc.DataAnnotations
Microsoft.AspNetCore.Mvc.Formatters.Json
Microsoft.AspNetCore.Mvc.Formatters.Xml
Microsoft.AspNetCore.Mvc.Localization
Microsoft.AspNetCore.Mvc.Razor
Microsoft.AspNetCore.Mvc.Razor.ViewCompilation
Microsoft.AspNetCore.Mvc.RazorPages
Microsoft.AspNetCore.Mvc.TagHelpers
Microsoft.AspNetCore.Mvc.ViewFeatures
Microsoft.AspNetCore.Razor
Microsoft.AspNetCore.Razor.Runtime
Microsoft.AspNetCore.Razor.Design
Microsoft.AspNetCore.ResponseCaching
Microsoft.AspNetCore.ResponseCaching.Abstractions
Microsoft.AspNetCore.ResponseCompression
Microsoft.AspNetCore.Rewrite
Microsoft.AspNetCore.Routing
Microsoft.AspNetCore.Routing.Abstractions
Microsoft.AspNetCore.Server.HttpSys
Microsoft.AspNetCore.Server.IIS
Microsoft.AspNetCore.Server.IISIntegration
Microsoft.AspNetCore.Server.Kestrel
Microsoft.AspNetCore.Server.Kestrel.Core
Microsoft.AspNetCore.Server.Kestrel.Https
Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions
Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets
Microsoft.AspNetCore.Session
Microsoft.AspNetCore.SignalR
Microsoft.AspNetCore.SignalR.Core
Microsoft.AspNetCore.StaticFiles
Microsoft.AspNetCore.WebSockets
Microsoft.AspNetCore.WebUtilities
Microsoft.Net.Http.Headers
Comment: That solves it, had to remove Microsoft.AspNetCore.Razor.Design.
Answer: I've had the same issue and it was solved by removing the following references:
"Microsoft.AspNetCore.Mvc" Version="2.2.0"

"Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.2.0"

Answer: This is kind of weird.
For me, the problem was because of 'Microsoft.AspNetCore.Mvc' package.
I uninstalled it and installed 'Microsoft.AspNetCore.Mvc.Core'.
I need to add that, I had installed 'Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation' too.


Linux namespace issue

Question: I am stuck with a network namespace issue.  I have a script which sets up a namespace.  It works on one Linux box but not the other.
The script:
function iface_up() {
  ip netns add riatans

  ip netns exec riatans ip addr add 127.0.0.1/8 dev lo
  ip netns exec riatans ip link set lo up

  ip link add riatavpn type veth peer name vpn1
  ip link set riatavpn up
  ip link set vpn1 netns riatans up

  ip addr add 10.211.211.1/24 dev riatavpn
  ip netns exec riatans ip addr add 10.211.211.2/24 dev vpn1
  ip netns exec riatans ip route add default via 10.211.211.1 dev vpn1

  iptables -t nat -A POSTROUTING -o $if_name -j MASQUERADE
  iptables -A FORWARD -i $if_name -o riatavpn -m state --state RELATED,ESTABLISHED -j ACCEPT
  iptables -A FORWARD -i riatavpn -o $if_name -j ACCEPT

  sysctl -q net.ipv4.ip_forward=1

  mkdir -p /etc/netns/riatans
  echo 'nameserver 184.108.40.206' > /etc/netns/riatans/resolv.conf

  ip netns exec riatans ping -c 1 www.google.com
}

On the box it works.
# ip netns list
riatans (id: 0)
# ip netns exec riatans ping www.google.com
PING www.google.com (220.127.116.11) 56(84) bytes of data.
64 bytes from lga25s62-in-f4.1e100.net (188.8.131.52): icmp_seq=1 ttl=54 time=12.3 ms
# ip netns exec riatans traceroute www.google.com
traceroute to www.google.com (184.108.40.206), 30 hops max, 60 byte packets
 1  10.211.211.1 (10.211.211.1)  0.064 ms  0.019 ms  0.015 ms
 2  10.7.7.1 (10.7.7.1)  0.360 ms  0.506 ms  0.461 ms
# ip netns exec riatans ip route
default via 10.211.211.1 dev vpn1
10.211.211.0/24 dev vpn1  proto kernel  scope link  src 10.211.211.2

On the box that doesn't work:
# ip netns list
riatans (id: 0)
# ip netns exec riatans ping www.google.com
PING www.google.com (220.127.116.11) 56(84) bytes of data.
64 bytes from lga25s56-in-f4.1e100.net (184.108.40.206): icmp_seq=1 ttl=54 time=36.3 ms
64 bytes from lga25s56-in-f4.1e100.net (220.127.116.11): icmp_seq=2 ttl=54 time=19.1 ms
^C
--- www.google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 19.158/27.776/36.394/8.618 ms
# ip netns exec riatans traceroute www.google.com
traceroute to www.google.com (220.127.116.11), 30 hops max, 60 byte packets
 1  10.211.211.1 (10.211.211.1)  0.029 ms  0.008 ms  0.007 ms
 2  10.211.211.1 (10.211.211.1)  0.010 ms !X  0.008 ms !X  0.008 ms !X
# ip netns exec riatans ip route
default via 10.211.211.1 dev vpn1
10.211.211.0/24 dev vpn1 proto kernel scope link src 10.211.211.2

I should mention that on box 2, outside of namespace, Internet works fine.  So while box 2 can ping www.google.com inside namespace riatans but can't do traceroute, ssh or vpnc.
What am I missing?  Why is the traceroute 2nd hop not 10.7.7.1 (my router)?
Thanks for any help.
Answer: The traceroute by default uses UDP packets, so the ping can works, but traceroute output can be differect.
The !X from the 10.211.211.1 host in the traceroute output means the ICMP communication administrative prohibited answer.
This is a firewall issue. Check the full rule set with iptables-save command.
When you configure the firewall rules for network namespace, you add the rules at the bottom of chains. Rules at the top of chains can block the UDP packets from your additional namespace.
Comment: Your rules are correct, but placed in the wrong position. The simplest way is just replace `-A` to `-I` to insert rules to the top of chains. The correct way is investigate the current rule set organization and the firewalld, and use the firewalld commands to allow packets from the namespace.
Comment: You are right on.  I disabled firewall and it worked.  Now that I think about it, box 1 is openSUSE LEAP 43.2 which uses old SuSEfirewall and box 2 is LEAP 15 which has transitioned to firewalld.  It must have been what firewalld is doing that SuSEfirewall wasn't.  Obviously I don't want to leave firewalld disabled.  What rule should I add?  Inside namespace, I am using 10.211.211.* and on the OS, my subnet is 10.7.0.0/16.  What am I opening on the firewall?  Thanks again for the help.
Comment: You, sir, are amazing.  That fixed it.

Linux namespace issue


Como retornar dados da api traduzidos com i18n?

Question: Minha API retorna dados serializados com active_model_serializers, alguns destes atributos são traduzidos no frontend utilizando angular-translate.
O dicionário contendo as traduções está cada vez maior, desejo fazer a tradução desses dados no backend e já retornar traduzido estes dados.
A forma que encontrei foi através da camada de serializers definindo métodos com cada atributo e os traduzindo.
Desejo a opinião de outros que efetivaram algo similar em seus projetos.
Obrigado
Answer: A forma que encontrei para resolver a questão, foi definindo método por método para cada atributo. Veja abaixo o código:
# frozen_string_literal: true
class User
  class RolesSerializer < ApplicationSerializer # :nodoc:
    attributes :name

    def name
      I18n.t object.name, scope: 'roles'
    end
  end
end

Comment: Gostaria muito de uma forma mais eficaz para essa questão.
Answer: Utilizando o comando do ruby eval você consegue criar os métodos de maneira dinâmica dentro da aplicação...
Crie as traduções normalmente, e utilize este método dentro da sua classe para retorná-las...
Por exemplo...
name = ['traducao 1', 'traducao 2']
name.each do |name|
 eval("def #{name}?
   I18n.t('name')
 end")
end

Acho que isso ajuda, se eu pensar em outra solução posto aqui, valeu!!


Arrange string by character placement in all possible ways

Question: Lets say that I have a an alphanumeric sting
$string = 'abcdefghijklmnopqrstuvwxyz012345678';

The characters in the above string could be arranged in a many number of ways simply by switch the placement of two or more of them.
I can't seem to find a mathematical way to write all of the possible ways in which a given collection of string can be arranged.
I started off with this:
<?php
     //Get the length of the string
     $length = strlen($string);

     //Create an empty array that will store each character
     $chars = array();

     for($i=0;$i<$length;$i++) {
         //Get each letter
         $part = substr($string, $i, 1);
         array_push($chars, $part);
     }

     for($i=0;$i<count($chars);$i++) {
         $current = $chars[$i];

     }

I'm having writers block solving this dilemma. Seems so easy to visualize but I can't seem to represent it in the text editor.
Comment: What's the end result you're after? The nr of combinations for a given string?
Comment: Are you trying to get all the possible outputs or are you trying to calculate the number of possible outcomes?
Comment: I'm trying to get all of the possible outputs
Comment: You will very soon reach astronomic numbers as the nr of combinations are calculated !n...so collecting them and outputting them seems impossible for even remotely long strings...
Answer: Here is the logic for that.
Reference Permutate a string
<?php
    function allString($string, $initial, $length){

        if($initial == $length){
            echo $string. "
";
        }else{
            for ($next=$initial; $next < $length ; $next++) {
                swap($string, $initial, $next);
                allString($string, $initial+1, $length);
                swap($string, $initial, $next);// backtrack
            }
        }
    }
    function swap(&$string, $initial, $next){
        $temp = $string[$initial];
        $string[$initial] = $string[$next];
        $string[$next] = $temp;
    }
    $string = "ABC";
    allString($string, 0, strlen($string));
?>

This illustrate the permutation of the string. It is using the Backtrack Method. I think you're looking for the same.
Comment: That's really interesting. Clears a lot up. Let's say that I wanted find out the number of times that all of those characters could be used (over again if needed) to populate a string that is 8 characters long. How would that be done?
Comment: @Lance can you tell me the number sequence will be same always means in a sequence of 012345678... or something else ?
Comment: I'm not sure what you're trying to ask me. But, this formula assumes that that length of the possible combos must be the length of the string. Let's that that each character in an 8 character string can be  either `A`, `B`, or `C`
Comment: @Lance You can remove the integer part from the string and then calculate the length. then Iterate over or vice versa
Comment: What integer part from the string? the `$initial+1`?
Comment: @Lance `$str = 'abcdefghijklmnopqrstuvwxyz012345678';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);` this will output `012345678` count the length of the `$matches` then iterate the loop. I should not write the whole answer for you. :P


Appoitment Module

Question: I'm working on a site in which I'd like a simple calendar that people can choose a day, then choose a time-slot to schedule an appointment. Pretty simple. Doesn't have to be robust or very configurable. I haven't had any luck in finding something like this. Does anyone know of one that exists?
Comment: Perhaps the http://drupal.org/project/calendar could be what you want.
Answer: Calendar module with the signup module worked perfect. Signup module is key.
Answer: Date module does the job ;)
But if you want more flexible solution can use calendar (as Krister Andersson commented) or Availability Calendars.

Appoitment Module


React - click data on table returns wrong index of row and column

Question: I am writing a simple datatable using react. After clicking a table cell, i need function to know exact row index and column index of it. In my case, i have a 3x3 table, with indexing from 0 - 2.
function getTable(){
    let rowIndex = 0;

    this.tableData.forEach(row => {
      const rowValues = Object.values(row);
      let colIndex = 0;

        let rowData = [];
        rowValues.forEach(colVal => {
          rowData.push(
             this.enableEdit(rowIndex, colIndex)}>
              {colVal}

          );
          console.log("row: " + rowIndex + ", column: " + colIndex);
          colIndex++;
        });

        bodyRows.push(
{rowData}
);

      rowIndex++;
    });

      return (

{headColumns}

{bodyRows}

    );

}

    enableEdit(row, col){
       console.log(row, col);
    }

Console log, does everything right. My results of it go like:
row: 0, column: 0
row: 0, column: 1
row: 0, column: 2
row: 1, column: 0,
row: 1, column: 1,
row: 1, column: 2
...

Keys work well too, they are all unique as intended:

But, enableEdit() function returns 3, 3 after clicking any cell (I guess its 3 because, that's the same value I get if i console.log after loops) , and that's my problem.
So what am I doing wrong? Why I don't get my expected results?
Comment: Glad you got it !
Comment: When you are iterating using `forEach` you are increasing your col and row index for every iteration. So the value `3,3` is expected.

You probably should move your `bodyRows` to local react state in which each cell will have its own row and col index.

Currently your `this.enableEdit(rowIndex, colIndex)` sends overwritten values of indices.
Comment: @UtsavPatel Sorry, i don't seem to understand. Why are keys unique and console log right, but onClick's parameters are of post-iteration? https://stackoverflow.com/questions/40044861/get-key-index-on-click-es6-react Judging by this link, they are doing something similar and successfully, am i right? he is using some arbitrary value of index for key as well as for onClick argument.
Comment: You have defined your `rowIndex` and `colIndex` outside the `forEach` respectively and in each iteration you are increasing them by 1.
So in your function `enableEdit` `rowIndex` and `colIndex` are both passed as 3.

The console logs show correct value because they were printed during the iteration and same goes for keys.
Comment: @UtsavPatel Oh, now i got it. onClick event isn't attached to it on every iteration right?
Comment: It is attached to the respective ``it is rendering.
Comment: @UtsavPatel thanks, i think i understood. What do you think would be best way for me to get cell row/col indices?
Comment: @UtsavPatel nevermind i got it. I will post an answer but credit you so much
Answer: UtsavPatel helped me much to understand what happened. After ForEach iteration rowIndex and colIndex values are 3, 3. We can even see that if we console.log after loop.
So what i did is just create a new object and store data that won't be touched there, like this:
    rowValues.forEach(colVal => {
      const indexDat = { rowIndex, colIndex };
      rowData.push(
         this.enableEdit(indexDat)}>
          {colVal}

      );
      console.log("row: " + rowIndex + ", column: " + colIndex);
      colIndex++;
    });


SQL Server 2008 sub-query caching?

Question: If I run the following query multiple times on SQL Server 2008 does it cache the result of the inner query (my complicated select query) after first time?
Or is it running that query every time with a new n and m values?
<code>SELECT * FROM (
   SELECT *, ROW_NUMBER() OVER (ORDER BY x.id) AS rowID
   FROM (*My complicated select Query* ORDER BY id) x
 ) y WHERE y.rowID BETWEEN n AND m
</code>
Comment: I can't imagine it's caching results. Query-plans, probably. But what if the table changes between query executions? It can't really safely cache a result-set.
Answer: This will depend on a variety of factors, including settings for parameterization (simple/forced etc), the "optimize for ad hoc workloads" setting, amount of memory, complexity of query, what's in the cache, how often plans get cycled out, etc. Note that there is a big difference between "caching the result" (which doesn't happen) and "caching and re-using a plan" (which can). Caching the results doesn't really make sense unless your database (or the filegroup where this table has been created) has been set to read only.

SQL Server 2008 sub-query caching?


Como efetuar um split da string após contar 50 carateres

Question: Tenho que contar 50 caracteres e efetuar um split em duas variáveis. O ideal seria efetuar o split no ultimo espaço antes dos 50 caracteres. Isto é para conseguir colocar a morada em duas linhas na base dados.
tenho isto assim:
Dim Morada As String = "Avenida luis de camoes, travessa de santa rita numero 588"
Dim CountMorada As Integer = Len(Morada)  'resultado de 57 carateres

Queria cortar antes de numero e colocar em duas variáveis.
Comment: Tem algum critério específico, ou é só pegar os 50 primeiros?
Comment: pegar no ultimo espaço, antes dos 50 caracteres, e colocar numa variavel e o restante numa 2 variavel
Answer: Dá pra fazer um pouco melhor, mas a pergunta não dá detalhes. Precisa pegar até o limite estabelecido onde tiver espaço. Tem função pronta para isto (LastIndexOf()).
Imports System

Public Module Module1
    Public Sub Main()
        For Each texto in CropText("Avenida luis de camoes, travessa de santa rita numero 588", 50)
            Console.WriteLine(texto)
        Next
        For Each texto in CropText("Avenida luis de camoes, travessa de santa rita", 50)
            Console.WriteLine(texto)
        Next
        For Each texto in CropText("Avenidaluisdecamoes,travessadesantaritanumero588teste", 50)
            Console.WriteLine(texto)
        Next
    End Sub

    Public Function CropText(text As String, limit As Integer) As String()
        If text.Length < limit
            Return New String() {text}
        Else
            Dim position As Integer = text.LastIndexOf(" ", limit)
            If position = -1
                Return New String() {text}
            Else
                return New String() {text.Substring(0, position), text.Substring(position + 1)}
            End If
        End If
    End Function
End Module

Veja funcionando no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: @SergioTeixeira veja agora.


Migration NServiceBus from 7.5 to 8: Dependency using WindsorContainer

Question: We are using NServiceBus version 7.5 and Windsor Container. We load dependencies to a Windsor container. The dependencies are (for example) from loading FromAssemblyContaining. We load existing Windsor container like that:
endpointConfiguration.UseContainer<WindsorBuilder>(c => c.ExistingContainer(container));.
Everything works quite well. But now we need to migrate NServiceBus to version 8. Where UseContainer is not supported any more. In NServiceBus 8, we have to load dependencies through AddSingleton, AddScoped or AddTransient.
How do I load all necessary dependencies (the existing container). Listing all Services in the old code (load from FromAssemblyContaining) is impossible.
Thank you very much!
I tried something as here https://docs.particular.net/nservicebus/upgrades/7to8/dependency-injection:
var endpointConfiguration = new EndpointConfiguration("EndpointName");
_endpointCustomization.Customize(endpointConfiguration); //setup things for endpoint
var serviceCollection = new ServiceCollection();
var container =  _endpointCustomization.Container()  // my function to load existing Windsor container
var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, serviceCollection);
var startableEndpoint = EndpointWithExternallyManagedContainer.Create(endpointConfiguration, serviceCollection);
var _endpointInstance = await startableEndpoint.Start(serviceProvider);
await _endpointCustomization.Start(_endpointInstance);

It throws exception at the first await call "No component for supporting the service NServiceBus.Unicast.Messages.MessageMetadataRegistry was found" Castle.MicroKernel.ComponentNotFoundException
Answer: Your approach is finalizing the Windsor container already before calling EndpointWithExternallyManagedContainer.Create(endpointConfiguration, serviceCollection);. Create will add NServiceBus specific registration to the ServiceCollection which will then not be reflected to the service provider instance that you already created. Try the following instead:
var endpointConfiguration = new EndpointConfiguration("EndpointName");
_endpointCustomization.Customize(endpointConfiguration); //setup things for endpoint

var serviceCollection = new ServiceCollection();
var startableEndpoint = EndpointWithExternallyManagedContainer.Create(endpointConfiguration, serviceCollection);

var container =  _endpointCustomization.Container()  // my function to load existing Windsor container
var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, serviceCollection);
var _endpointInstance = await startableEndpoint.Start(serviceProvider);
await _endpointCustomization.Start(_endpointInstance);

Since I don't know what your _endpointCustomization instance is doing exactly, I don't know whether that will solve the issues but this suggestion represents the order the endpoint should be configured (also documented here: https://docs.particular.net/nservicebus/upgrades/7to8/dependency-injection#externally-managed-container-mode-migrating-to-externally-managed-mode-castle-windsor)
Comment: Thank you very much for the help. Now I am able to use my existing Windsor container (with loading dependencies) from our NServiceBus 7.5 to use in NServiceBus 8.
I think I missed nuget package, Castle.Windsor.MsDependencyInjection, in my project. After adding nuget Castle.Windsor.MsDependencyInjection to the project, it now can start the container with dependencies


File field breaks AJAX form in Drupal 7 form API

Question: This is a really strange one, I've created a custom form using the multi step form method. So there are various AJAX calls to handler functions that return certain sections of the form back to containers and replace the HTML.
My form works great has a lot of complexity to it and the speed is fantastic. A recent addition to said form is to be able to upload a PDF, simple I thought! Added my manged_file field and all looked great. However I'd missed that now my page was reloading, AJAX requests were no longer in the Firebug console and instead seemed to be in the POST somehow. I don't fully understand how the AJAX is still working but it is slower that's for sure!
This is a problem I think we could live with a bit of slowness but then I noticed on a full form submission it was breaking a second form outside of this form. Basically it's too big of an issue to live with now.
I've tried a few things, one a standard file field, two a markup field with a raw
<input type="file" />

just to see what happened and I experienced the exact same issue as using the form API. This confirms to me that this is not caused by some added javascript from Drupal but a problem with the input itself.
So my question is why does a file field break the AJAX in my form?
Rather awkwardly I can't just paste all my code here as the data is protected and technically not my property. I'm not sure it's needed but I've thrown together a quick bit of code that should demonstrate my issue.
function vv_test_menu(){
    $items = array();
    $items['vvtest'] = array(
        'page callback' => 'vv_test_page',
        'access arguments' => array('access content'),
        'page arguments' => array(false),
        'description' => t('Test page for code.'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function vv_test_page(){
    $content = 'This demonstrates the file field breaking the AJAX.';
    $content .= render(drupal_get_form('vv_test_form'));
    return $content;
}

function vv_test_form($form, &$form_state){
    $form['#tree'] = TRUE;
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['job_number'] = array(
        '#type' => 'textfield',
        '#title' => t('Job number'),
        '#required' => TRUE
    );

    if($form_state['triggering_element']['#ajax']['callback'] == t('vv_test_call')){
        $form['result'] = array(
            '#markup' => '
You entered: '.print_r($form_state['values']['job_number'], true).'
'
        );
    }

    // - Comment this field in and out to see the problem
    $form['pdf'] = array(
        '#type' => 'file',
        '#title' => t('A file field')
    );

    $form['sync'] = array(
        '#type' => 'button',
        '#name' => 'sync',
        '#value' => t('Sync'),
        '#ajax' => array(
            'callback' => 'vv_test_call',
            'wrapper' => 'container'
        )
    );

    return $form;
}

function vv_test_call($form, &$form_state){
    $form_state['rebuild'] = FALSE;
    return $form;
}

Comment: Managed file should never reload on it's own. Can you repeat it with minimal form with only managed file element in it?
Comment: Molot I think you've misunderstood it doesn't do anything on its own. Simply having the managed_file field in the form stops AJAX working in the traditional sense. If you've got an environment try the code and you'll see what I mean.
Comment: Are you getting any JS errors in the debug console?
Comment: Nope, first place I looked.
Answer: I experienced the exact same: Drupal 7, custom AJAX form, multiple pages, all working fine. After adding a managed file field it broke the AJAX functionality. Or that was what it looked like...
The past couple of days I spent quite some time digging around misc/drupal.js, misc/ajax.js and modules/file/file.js to turn the managed file field into a single customizable "Select & upload file" button with client side file size validation and auto submit functionality.
After reading your question and remark about that the problem even occurred when manually inserting a plain non Form API file field it dawned to me that I read the following in misc/ajax.js > Drupal.ajax.prototype.beforeSend:

For forms with file inputs, the jQuery Form plugin uses the browser's normal form submission mechanism, but captures the response in a hidden IFRAME.

I tested this on the dev site and it appeared that AJAX only "broke" after visiting a form page which contained a plain file field. Though the requests felt less snappy and in Chrome and Firefox loading throbbers appear in the browser tabs and the status bar showed a new page was being requested, it seemed to not harm my forms.
But the jQuery Form plugin for Drupal 7.28 has version number 2.52, see misc/jquery.form.js. The jQuery update module 7.x-2.4 ships with path/to/jquery_update/replace/misc/jquery.form.min.js with version number 2.69, though the latest version is 3.51, see http://malsup.com/jquery/form/#download. This latest version appears to use another technique for file uploads which feels like AJAX (or maybe ís using AJAX), see http://malsup.com/jquery/form/#file-upload. I tried this version on the dev site and so far with success!
Download the latest version to your module or theme and use ie. hook_js_alter() to replace the old script for the new one. I implemented this hook for the site's theme:
/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Define path to old jQuery Form plugin, alter to your needs.
  $old_path = drupal_get_path('module', 'jquery_update') . '/replace/misc/jquery.form.min.js';

  // The script does not get loaded on every page, so check the $js array.
  if (isset($js[$old_path])) {
    // Define path to newer jQuery Form plugin, alter to your needs.
    $new_path = drupal_get_path('theme', 'YOURTHEME') . '/js/jquery.form.min.js';

    // Copy data from old javascript to new and remove old javascript.
    $js[$new_path] = $js[$old_path];
    unset($js[$old_path]);

    // Set new path as data property and alter version number.
    $js[$new_path]['data'] = $new_path;
    $js[$new_path]['version'] = '3.51.0';
  }
}

Or see how jquery_update_library_alter() did it and apply this method to your module.


Integral $ \int \frac{1}{x^{1+a} (1-x)^{1-a}} dx~,~a \gt 0$

Question: The following integral is part of a large problem I'm trying to solve and I'm stuck. I'd appreciate some guidance.
I would like to know how to compute integrals of the form

$$ \int \frac{1}{x^{1+a} (1-x)^{1-a}} dx~,~a \gt 0$$

This is the answer WolframAlpha gives.
Answer: Rewrite the integral as:
$$ \int \frac{1}{x(1-x)}\left(\frac{1-x}{x}\right)^a\,dx = \int \frac{1}{x^2}\left(\frac{1-x}{x}\right)^{a-1}\,dx$$
and notice that:
$$\frac{d}{dx}\frac{x-1}{x} = \frac{1}{x^2}.$$
Answer: $$
\int \frac{1}{x^{1+a}(1-x)^{1-a}}dx = \int \frac{1}{x(1-x)}\left(\frac{1-x}{x}\right)^adx
$$
let $u = \frac{1-x}{x} = \frac{1}{x}-1\implies du = -\frac{1}{x^2}dx$
$$
-\int \frac{x}{x-1}u^adu = -\int \frac{1}{u}u^a du = -\int u^{a-1}du
$$
Answer: Substitute
$$
y = \frac{1-x}{x} \\
x = \frac{1}{y+1} \\
dx = -(y+1)^{-2}dy
$$
The integral becomes
$$
-\int y^{a-1} dy = -\frac{1}{a}y^a = -\frac{1}{a} (1-x)^a x^{-a}
$$


Laravel Eloquent: How to order results of related models?

Question: I have a model called School and it has many Students .
Here is the code in my model:
public function students()
{
    return $this->hasMany('Student');
}

I am getting all the students with this code in my controller:
$school = School::find($schoolId);

and in the view:
@foreach ($school->students as $student)

Now I want to order the Students by some field in the students table. How can I do that?
Comment: @JaredFarrish orderBy there would affect query on the `schools` table, not `students`, and obviously would throw an error, unless you join the tables.
Answer: You have a few ways of achieving this:
// when eager loading
$school = School::with(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);

// when lazy loading
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}]);

// or on the collection
$school = School::find($schoolId);
// asc
$school->students->sortBy('whateverProperty');
// desc
$school->students->sortByDesc('whateverProperty');

// or querying students directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();

Comment: How to sort collections by multiple properties of the model? For example, I want to sort by class and then by their name. `$school->students->sortBy('whateverProperty')->sortBy('anotherProperty');` does not work. It only sorts the collection by 'anotherProperty'.
Comment: Here is a solution which works. It uses the closure. http://stackoverflow.com/a/25451441/225790
Comment: Yes, Mark Baker's linked solution is neat. Another solution would be `usort`.
Comment: @SajeebAhamed `xToOne` doesn't make sense to sort related models, so what is your question actually?
Comment: sortBy is perfect for me, still didn't need to use join... the only thing that I'm worried about is I'm doing sortBy in the views at the foreach
Comment: SortBy has saved me! I have it inside a foreach, the use is as classic SQL:  @foreach ($carts->sortBy('attribute.product_id') as $cartItem) ... where 'attribute' is a hasOne Eloquent relation
Answer: you can add orderBy to your relation, so the only thing you need to change is
public function students()
{
    return $this->hasMany('Student');
}

to
public function students()
{
    return $this->hasMany('Student')->orderBy('id', 'desc');
}

Comment: This is wrong. What if I want to orderBy 2 things in student, need to change the relationship.
Answer: To answer the original question, the students dynamic property can also be accessed as a relationship method.
So you have this to fetch all students:
$students = $school->students;

Now as a relationship method, this is equivalent:
$students = $school->students()->get();

Given this, you can now add in some ordering:
$students = $school->students()->orderBy('students.last_name')->get();

Since eloquent will be performing a join, make sure to include the table name when referencing the column to order by.
You can also add this to your students method if you want to set a default order that $school->students will always return. Check out the documentation for hasMany() to see how this works.
Answer: For Many to one relation I found one answer on:
https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship
$order = 'desc';
$users = User::join('roles', 'users.role_id', '=', 'roles.id')
  ->orderBy('roles.label', $order)
  ->select('users.*')
  ->paginate(10);

this can save day... of anyone
Answer: You can use this like this:
$students = $school->students()->orderBy('id', 'desc');

You can also use
$students = $school->students()->orderBy('id', 'desc')->paginate(10);


Volume of revolution qustion

Question: Sketch the region enclosed by $f(x)=\cos(2x)$ and the $x$-axis on the interval $[0,\pi/2]$. Find the volume of solid of revolution of this region about the axis $y=-1$.
The answer should be approximately $6.283$, but I have no idea how to get that answer. I would appreciate some help.
My professor used the following method:
$$V_1=\pi \int_0^{\pi/4} (1-\cos 2x)^2 dx -\pi\cdot\frac{\pi}4, \quad V_2= \pi\cdot\frac{\pi}4 -\int_{\pi/4}^{\pi/2}(1-\cos 2x)^2 dx\\ \implies V= V_1+V_2$$
I don't understand this method
Comment: You could start by making the sketch, then trying to recall what you know about volume of solids of revolution. Perhaps a review of your textbook or class notes would help. Then edit the question to show what you have done (and I mean _show_ it, don't just _say_ you did it).
Comment: I believe my professor made mistake and that in V2 it should be (-1-cos(2x)) when i do this i get an answer of 6.283 when adding V2 to V1
Answer: The volume of $y=f(x)$ around x axis is:
$v=\pi\int_{x_1}^{x_2}y^2 dx$
The point $(\frac{\pi}{2}, -1)$ is minimum of the function, that is the line the curve rotates about passes the minimum point on the curve. When we say 'around x axis' it means 'around line $y=o$, in your question it is around $y=-1$.so we first transform the equation, that is we have:
$y= \ cos 2x  ; Y → y-1 ⇒Y=1- \cos 2x  $
⇒ $v=\pi\int_{x_1}^{x_2}(1- \ cos 2x)^2 dx$
Now value of integral is positive above x axis i.e from $\pi/4$(where the curve crosses x axis)to $0$ and is negative below x axis i.e. from $\pi/2$ to $\pi/4$ so we split the interval into $[\pi/4 , 0]$ and $[\pi/2, \pi/4]$to find the sum of volumes.
Comment: Thank you for the explanation, but I get a negative number in V2 and when I add it to V1 I get 0 does this make any sense ?
Comment: The area between the curve and y and x axis is concerned. the area with negative value is between x axis and curve and as you can see in figure(I hope you have sketched it) so it must be subtracted:$-(-v_2)=+v_2$
Answer: I'm working this out in detail because I think your professor's formula
is rather badly broken.
First we have to figure out what is meant by "the region enclosed by $f(x)=\cos(2x)$ and the $x$-axis on the interval $[0,\pi/2]$."
Here's a possible sketch:

There are two parts of this region, because the graph of $y = \cos(2x)$
is sometimes above the $x$-axis and sometimes below.
If we revolve just the first part (between $x=0$ and $x=\frac\pi4$)
around the line $y = -1,$ we get an object of diameter $4$
(along the line $x = 0$) with a cylindrical hole of diameter $2$
(that is, radius $1$) in the middle.
The hole has volume $\pi r^2 h = \pi \cdot \frac\pi4,$
so it makes sense that you would subtract $\pi \cdot \frac\pi4$
from an integral as your professor did in calculating $V_1.$
But
$$
\pi \int_0^{\pi/4} (1-\cos(2x))^2\, dx = \pi\left(\frac38\pi - 1\right)
< \pi \cdot \frac\pi4,
$$
so your professor's formula for $V_1$ gives a negative number,
which surely is not correct.
The outer radius of the solid of revolution at any $x$ should be the
magnitude of the difference between $\cos(2x)$ and $-1,$
that is $\lvert (-1) - \cos(2x)\rvert,$
and squaring this we get $(-1 - \cos(2x))^2 = (1 + \cos(2x))^2.$
It turns out that
$$
\pi \int_0^{\pi/4} (1+\cos(2x))^2\, dx = \pi\left(\frac38\pi + 1\right),
$$
which leads to the conclusion that
$$V_1 = \pi\left(\frac38\pi + 1\right) - \pi \cdot \frac\pi4
=\frac18\pi^2 + \pi.$$
What you get by integrating $(1-\cos(2x))^2$ is a solid of revolution
of the region between $y = \cos(2x)$ and $y = 1$ around the line $y = 1.$
It is clear that the volume of that solid is much less than that of a
cylinder of radius $1$ and height $\frac\pi4,$ which the integral confirms.
Revolving the second part of the region (between $x=\frac\pi4$
and $x=\frac\pi2$) around the line $y = -1,$
we get a cylinder of radius $1$ that is partly hollowed out.
The part that is removed has radius $\lvert -1 - \cos(2x)\rvert$
at each value of $x.$ This is (of course) the same formula as the one for the outer radius of the solid of revolution between $x=0$ and $x=\frac\pi4.$
The volume removed is
$$
\pi \int_{\pi/4}^{\pi/2} (1+\cos(2x))^2\, dx
= \pi\left(\frac38\pi - 1\right),
$$
which is subtracted from the volume of the cylinder, with the result
that
$$V_2 = \pi \cdot \frac\pi4 - \pi\left(\frac38\pi - 1\right)
= \pi - \frac18\pi^2.$$
If we were to integrate $(1-\cos(2x))^2$ here instead of $(1+\cos(2x))^2,$
the integral would be much greater than $\pi \cdot \frac\pi4$ and we
would end up with a negative value for $V_2.$
Finally, using the correct results for the volumes of $V_1$ and $V_2,$ it is easy to see that $V_1 + V_2 = 2\pi.$
Comment: Thank you very much for the clarification

Volume of revolution qustion


Image uploading not working in server

Question: In a content type have a field image upload.its image upload type is jpg,png,gif.
When we upload these image type of images an error is coming :

The selected file Chrysanthemum.jpg could not be uploaded. The file is
  not a known image format.

But its running in local not in server. What is the problem ?
Please help me.
Thanks
Answer: Below are the two ways. I hope help you to solve your issue.
1.
Your files via FTP into the image_import directory aren't being given the correct permissions. You have to provide the permission i.e. chmod 660 * on them in the image_import directory the files were recognized correctly and the import worked.
OR
2.
In /includes/image.inc, change line 117 from:
  if (!is_file($file)) {

to:
if (!is_file($file) && !is_uploaded_file($file)) {

Then check is your issue is solved or not. If not then try once updating below with second way :
On the admin/settings/file-system, try changing C:\WINDOWS\Temp to sites/default/files/temp (also made sure it was writeable by the web server).
Answer: Have you tried with other images? Do you get the same error with other .jpg files? Or .gif files? Perhaps Chrysanthemum.jpg is a corrupt file.
Can you upload other files? Are /tmp permissions set correctly?
If so, it could be a PHP issue, and not a Drupal issue. Check whether the FileInfo module is installed:
pecl install fileinfo

Or if you run Apache, check if the libjpeg.so module is enabled.
Comment: i tried but got same error.
Comment: I amended my answer with more detail, see if that helps.

Image uploading not working in server


Jquery An ajax WIth html.dropdown

Question: Situation is : when i select a value from a html.dropdown then i need corresponding values stored in another table at database with in the same view in any manner (keep dropdown visible).My consideration:: Firstly i need to pass selected value of dropdown to some controller action(using jquery handler). then that controller action must return a partial view which i can display on dropdownlist view with the help of Ajax........need some code
Comment: I am using viewbag/viewdata to fill dropdownlist
Answer: You could use javascript to subscribe to the .change event of the dropdown list and trigger an AJAX request sending the selected value to the server. For example assuming you have the following dropdown (with an unique id so that it can be referenced more easily from your javascript files and an HTML5 data-* attribute pointing to the server controller action that will be invoked when the value changes):
<code>@Html.DropDownListFor(
    x => x.SomeProperty,
    Model.Items,
    new {
        data_url = Url.Action("Foo", "SomeController"),
        id = "myddl"
    }
)
</code>
in a separate javascript file you could subscribe to the change event:
<code>$(function() {
    // When the DOM is loaded subscribe to the .change event of the dropdown list
    // with id="myddl"
    $('#myddl').click(function() {
        // when the value of the dropdown changes fetch the new value
        var selectedValue = $(this).val();

        // fetch the url
        var url = $(this).data('url');

        // send the selected value to the server using a AJAX POST request
        $.post(url, { value: selectedValue }, function(result) {
           // will be called when the AJAX succeeds. Here you could process
           // any eventual results sent by the server. For example the server could
           // return some JSON object indicating whether the operation succeeded or not
        });
    });
});
</code>
which would invoke the corresponding action:
<code>[HttpPost]
public ActionResult Foo(string value)
{
    // at this stage value will equal the selected dropdown value
    // so that you can update your database and do whatever you want with it
    ...
}
</code>

Jquery An ajax WIth html.dropdown


IOError: [Errno 22] invalid mode ('r') or filename App Engine

Question: I followed the steps exactly as in this tutorial:
http://www.mkyong.com/google-app-engine/google-app-engine-python-hello-world-example-using-eclipse/
When i try to run in i get this error:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\dev_appserver.py", line 83, in
    _run_file(__file__, globals())
  File "C:\Program Files (x86)\Google\google_appengine\dev_appserver.py", line 79, in _run_file
    execfile(_PATHS.script_file(script_name), globals_)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 1033, in
    main()
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 1026, in main
    dev_server.start(options)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 752, in start
    options.config_paths, options.app_id)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\application_configuration.py", line 795, in __init__
    module_configuration = ModuleConfiguration(config_path, app_id)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\application_configuration.py", line 123, in __init__
    self._config_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\application_configuration.py", line 391, in _parse_configuration
    with open(configuration_path) as f:
IOError: [Errno 22] invalid mode ('r') or filename: '\x93D:\\Helloworld/src\x93'

I followed the steps exactly.
helloworld.py:
<code>from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):

def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello, webapp World!')

application = webapp.WSGIApplication([('/', MainPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
</code>
app.yaml:

application: feebe-1096
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: helloworld.py

I have no idea why this is happening. I literaly just installed eclipse, PyDev plugin and the app engine SDK just before trying this.
Answer: Notice the \x93 in the error message: IOError: [Errno 22] invalid mode ('r') or filename: '\x93D:\Helloworld/src\x93'
\x93 is the code of the " symbol. You (very likely) entered a string with "-s where there should be none. Please check your configurations. And remove the "-s
Comment: Thank you for the quick reply. I had put quotes around the path directory in the arguments.


Ruby rails add field to form with JavaScript

Question: I am using ruby on rails and JavaScript. I want to create a form in which one field can have more than one "object". In my example an employee can add multiple formations.
Just to let you know, I don't know much in JavaScript and I am not an expert in Web languages. So please explain to me what are my problems in the following code.
This is the code in my employe _form.html.erb

Add Formations

this is my code in employeFormation.js
$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
<input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

and this is my code in application.js
//= require employeFormation

what I actually want is that when I click on addFormation its add a field below the other and I can remove it and is added to my object when I create the new employee
Thanks you for your answer.
Edit: corrected some typo in the code (thanks to KKK). But its still not working
Answer: The problem in your code was that you refer a wrong id in javascript. In your HTML the id is FormationSet and in javascript you try to append form into formationSet div. Change the id in HTML and it works fine.

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
<input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

Add Formations
Comment: No, you don't need it. (I hope you have already included jQuery in your app). I included this so that the code snippet works here. Unless it won't work since we need jQuery to run the code.
Comment: Thanks for the correction. But I was wondering what this line do : `` Do I need it?
Answer: Above ruby 4.0 aparently $(document).ready dont get notify as before. So I had to change it like this:
var ready = function() {
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
 <%=     f.label :email %> \n <%= f.text_field :email %>' +

        '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
};

$(document).ready(ready);
$(document).on('page:change', ready);