示例#1
0
 it("should typecheck propOr", () => {
   const x: string | number = _.propOr(2, "a", { b: 2, c: "dd" });
   const x1: string | number = _.propOr(2, "a")({ b: 2 });
   const x2: string | number = _.propOr(2)("a", { b: 2 });
   const x3: string | number = _.propOr(2)("a")({ b: 2, c: "dd" });
   //$ExpectError
   const x4: number = _.propOr("a")("a")({ b: 2 });
 });
 const DOM = ass$.map(ass =>
   div('.list-item', [
     div('.content-xcol-sm-4', [
       div('.title', pathOr('err', ['team', 'name'], ass)),
       div('.subtitle', 'Team'),
     ]),
     div('.content-xcol-sm-4', [
       div('.title', propOr('no time', 'startTime', ass)),
       div('.subtitle', 'Start Time'),
     ]),
     div('.content-xcol-sm-4', [
       div('.title', propOr('no time', 'endTime', ass)),
       div('.subtitle', 'End Time'),
     ]),
   ])
 isConditional() {
   const conditionsAreEmpty = R.pipe(
     R.propOr([], 'conditions'),
     R.isEmpty
   )(this.automationAction);
   return R.not(conditionsAreEmpty);
 }
示例#4
0
const rawUpdate = _.curry((db, sql, params) => {

  return runNoCache(db, sql, params)

  .then(_.propOr(null, 'affectedRows'))

});
示例#5
0
export const composer = ({context, sessionId, questionId}, onData) => {
  const {Collections, Meteor} = context();
  const question = Collections.Questions.findOne(questionId);
  const responses = Collections.Responses.find({questionId}).fetch();
  const users = Meteor.users.find().fetch();
  const userId = Meteor.userId();

  // Helper function
  const merge = compose(
    values,
    propMerge('_id', 'owner')
  );

  // Helper function
  const findByAndProp = compose(
    propOr(-1, 'selected'),
    find(propEq('owner', userId))
  );

  // Helper function
  const groupSelected = compose(
    sortByOr([], 'students', 'selected', [ '0', '1', '2', '3' ]),
    objToColl('selected', 'students'),
    map(pluck('displayName')),
    groupBy(prop('selected'))
  );

  const responsesWithUsers = merge(users, responses);
  const ownSelected = findByAndProp(responsesWithUsers);
  const responsesGroup = groupSelected(responsesWithUsers);

  onData(null, {question, ownSelected, responsesGroup});
};
export const getKeysFromIfplId = ifplId => R.pipe(
  getKeys,
  R.propOr(null, ifplId),
  R.unless(
    R.isNil,
    R.assoc('ifplId', ifplId),
  ),
);
示例#7
0
 guess: (state) => (stim) =>
   !stim ? ''
     : compose(
       propOr(null, 0),
       reduce(tr, null),
       toPairs,
       prop(stim.id)
     )(state),
示例#8
0
const getDistrbutionURLFromConfig = (config) => {
  const distName = getMatchingDistributionName();
  const distURL = R.propOr(null, distName, config);

  if (!distURL) {
    return Promise.reject(new Error("No matching distribution for this operating system"));
  }
  return Promise.resolve(distURL);
};
示例#9
0
  constructor(props: Props) {
    super(props);

    const { client } = props;

    this.state = {
      clientType: R.propOr('cwp', 'type', client),
    };
  }
示例#10
0
  (val, key) => {

    let _normalize = R.identity

    if(typeof(map[key]) == 'function')
      _normalize = R.propOr(_normalize, 'normalize', map[key](val))

    return _normalize(val)
  }
示例#11
0
const convertResponse = (axiosResponse) => {
  return {
    problem: responseToProblem(axiosResponse),
    ok: R.pipe(R.propOr(0, 'status'), in200s)(axiosResponse),
    status: axiosResponse.status || null,
    headers: axiosResponse.headers || null,
    config: axiosResponse.config || null,
    data: axiosResponse.data || null
  }
}
const SuccessfulSignUp = ({ personal_details }) => {
  return (
    <div>
      <h4>The sign up process is now complete. Welcome to the Friends!</h4>
      <h4>
        Your membership number is {propOr('', 'value', personal_details.id)}
        {propOr('', 'value', personal_details.membership_type).match(/annual/)
          ? ` and your subscription becomes due on the ${personal_details.due_date.value} of each year.`
          : '.'
        }
      </h4>
      <h4>
        If you wish to pay the initial subscription charge you can click the 'Make a Payment'
        tab at the top. We’d encourage you to pay by Credit Card or PayPal because it makes
        life easier both for you and for the volunteers who run the Friends .
      </h4>
    </div>
  )
}
示例#13
0
const allLabels = period =>
  [].concat(
    originalLabel(period),
    R.pipe(
      R.propOr({}, 'localizedLabels'),
      R.mapObjIndexed((labels, languageTag) =>
        labels.map(label => ({ label, languageTag }))),
      R.values,
      R.unnest
    )(period)
  )
  const checkResponseStatus = b2bResponse => {
    const status = R.propOr('UNKNOWN', 'status', b2bResponse);

    if(status === 'OBJECT_NOT_FOUND') {
      throw new B2BErrorNotFound();
    } else if(status !== 'OK') {
      throw new B2BError(`Invalid response status : ${status}`, {b2bResponse});
    }

    return b2bResponse;
  };
示例#15
0
  constructor ({ host, port, options }) {
    this.host = host
    this.port = port
    this.ssl = false
    this.bufferedAmount = 0
    this.readyState = 'connecting'
    this.binaryType = propOr('arraybuffer', 'binaryType')(options)

    if (this.binaryType !== 'arraybuffer') {
      throw new Error('Only arraybuffers are supported!')
    }

    this._ca = options.ca
    this._useTLS = propOr(false, 'useSecureTransport')(options)
    this._useSTARTTLS = false
    this._socketId = 0
    this._useLegacySocket = false
    this._useForgeTls = false

    // handles writes during starttls handshake, chrome socket only
    this._startTlsBuffer = []
    this._startTlsHandshakeInProgress = false

    chrome.runtime.getPlatformInfo(platformInfo => {
      if (platformInfo.os.indexOf('cordova') !== -1) {
        // chrome.sockets.tcp.secure is not functional on cordova
        // https://github.com/MobileChromeApps/mobile-chrome-apps/issues/269
        this._useLegacySocket = false
        this._useForgeTls = true
      } else {
        this._useLegacySocket = true
        this._useForgeTls = false
      }

      if (this._useLegacySocket) {
        this._createLegacySocket()
      } else {
        this._createSocket()
      }
    })
  }
示例#16
0
文件: from-api.js 项目: dmsnell/wrnc
const mapNoticon = key => propOr( 'star', key, {
	'\uf814': 'mention',
	'\uf300': 'comment',
	'\uf801': 'add',
	'\uf455': 'info',
	'\uf470': 'lock',
	'\uf806': 'stats',
	'\uf805': 'reblog',
	'\uf408': 'star',
	'\uf804': 'trophy',
	'\uf414': 'warning'
} );
示例#17
0
文件: requester.js 项目: younker/ynkr
export default (naiveSpec, builderArgs) => {
  let { errors, spec } = initializeSpec(naiveSpec, builderArgs);

  let { error: pathError, path } = buildPath(spec.path, builderArgs);
  errors = errors.concat(pathError);

  let { errors: argErrors, requestArgs } = extractRequestArgsFromSpec(spec);
  errors = errors.concat(argErrors);

  const host = R.propOr('unknown', 'host', spec);
  const url = R.join('', [host, path]);
  const method = R.propOr('unknown', 'method', spec);
  const endpoint = `${method.toUpperCase()} ${spec.path}`;

  // Because we blindly concat errors from each build step
  errors = R.reject(R.isNil, errors);

  // To make things easier, make errors undefined when no errors exist. This
  // matches a desired pattern of simply returning `{ data }` when no error
  // exist thus making `error` undefined when the caller destructures it.
  errors = R.isEmpty(errors) ? undefined : errors;

  const requester = async function() {
    if (errors) {
      const msg = 'You are attempting to perform an http request against ' +
        'a spec which could not be compiled cleanly, failing with the ' +
        `following error(s): ${R.toString(errors)}`;

      return { error: { message: msg, code: INVALID_SPEC_ERROR } };
    }

    return await performHttpRequest({
      endpoint,
      url,
      ...requestArgs,
    });
  };

  return { errors, requester };
}
示例#18
0
 render () {
   const
     { confirm_add_donation
     , add_donation
     , cancel_donation
     , personal_details: { membership_type }
     , update_member_user
     , user_payments: { payment_type, donation_pending, donation_made, membership_changed }
     } = this.props
   return payment_type
     ? component_mapper[payment_type](this.props)
     : (<div>
         <div className='u_alter-payment'>
           { membership_changed
             ? SuccessfulMembershipChange(propOr('annual-single', 'value')(membership_type))
             : ChangeMembershipForm (update_member_user, propOr('annual-single', 'value')(membership_type))
           }
           {donation_made ? SuccessfulDonation() : DonationForm(add_donation, confirm_add_donation, donation_pending, cancel_donation)}
         </div>
         <PaymentAmount {...this.props}/>
       </div>)
 }
示例#19
0
const convertResponse = (startedAt, axiosResponse) => {
  const end = RS.toNumber(new Date())
  const duration = (end - startedAt)
  return {
    duration,
    problem: responseToProblem(axiosResponse),
    ok: R.pipe(R.propOr(0, 'status'), in200s)(axiosResponse),
    status: axiosResponse.status || null,
    headers: axiosResponse.headers || null,
    config: axiosResponse.config || null,
    data: axiosResponse.data || null
  }
}
示例#20
0
const rawInsert = _.curry((db, sql, params) => {

  return runNoCache(db, sql, params)

  .then(_.ifElse(
    _.compose(_.propOr(null, 'insertId'))

  , _.prop('insertId')

  , () => throwInsertFailedError(sql, params)

  ));

});
示例#21
0
  render() {
    const {
      shouldDisplayMessage,
      shouldDisplayList,
      hasPendingAction,
      client,
      sectors,
    } = this.props;

    // Show filter controls only when we have sectors
    const showFilterControl = !R.isEmpty(sectors);
    // Show advanced controls only when we're a supervisor or a developer
    const showSupervisorControl = R.pipe(
      R.propOr(null, 'type'),
      R.equals('supervisor'),
    )(client) || process.env.NODE_ENV === 'development';

    // We have sectors bound, we must redirect to dashboard after a while
    // But only if we don't have notifications
    const shouldRedirectToDashboard = !R.isEmpty(sectors) && !hasPendingAction;

    const showFlightListControl = showFilterControl || showSupervisorControl;

    return (
      <div>
        {shouldRedirectToDashboard && <RedirectToDashboard />}
        {showFlightListControl && [
          <FlightListControls
            key="flight-list-controls-0"
            showFilterControl={showFilterControl}
            showSupervisorControl={showSupervisorControl}
          />,
          <Divider key="flight-list-controls-1" />,
        ]}
        {shouldDisplayMessage && [
          <StatusMessage
            key="status-message-0"
            style={{textAlign: 'center', margin: 0, padding: 10}}
          />,
          <Divider
            key="status-message-1"
          />,
        ]
        }
        {shouldDisplayList && <FlightList />}
      </div>
    );
  }
示例#22
0
 showValidationError = (
   fieldName: string,
   ignoreVisibility: boolean = false
 ): ?React$Element<*> => {
   const {
     channelDialog: { validationErrors, validationVisibility }
   } = this.props
   const isVisible = R.propOr(false, fieldName)
   const val = validationErrors[fieldName]
   if (
     (isVisible(validationVisibility) && val !== undefined) ||
     ignoreVisibility
   ) {
     return <span className="validation-error">{val}</span>
   }
 }
示例#23
0
          {mapIndex(({image, images, type}, key) => {
            if (equals(type, 'card')) {
              return (
                <Flex
                  width={getWidthFor(type)}
                  maxWidth={getMaxWidthFor(type)}
                  flexDirection="column"
                  key={key}
                >
                  {mapIndex((image, key) => {
                    return (
                      <Box key={key} pt={['6vw', '8vw']} pl={['6vw', '8vw']}>
                        <img className={style.image} src={image} />
                      </Box>
                    )
                  }, images)}
                </Flex>
              )
            }

            const fluid = prop('fluid', image)
            const imageEl = has('fluid', image) ? (
              <Img
                className={cx(style.image, prop(type, style))}
                fluid={fluid}
              />
            ) : (
              <img
                className={cx(style.image, propOr(null, type, style))}
                src={image}
              />
            )

            return (
              <Box
                width={getWidthFor(type)}
                key={key}
                maxWidth={getMaxWidthFor(type)}
                pt={['6vw', '8vw']}
                pl={['6vw', '8vw']}
              >
                {imageEl}
              </Box>
            )
          }, images)}
示例#24
0
  render() {
    const platform = propOr('unknown', Constants, 'platform');

    return (
      <View style={styles.container}>
        <Video
          resizeMode={Video.RESIZE_MODE_CONTAIN}
          source={this.props.video}
          style={[
            {
              width: '100%',
              height: '100%'
            },
            platform === 'ios' && { backgroundColor: 'transparent' }
          ]}
          useNativeControls
          shouldPlay
          onPlaybackStatusUpdate={this.onPlaybackStatusUpdate}
        />
      </View>
    );
  }
示例#25
0
文件: requester.js 项目: younker/ynkr
function buildPath(path, args) {
  if (R.isNil(path)) {
    return { error: missingArgumentError('path') };
  }

  let compiled;
  try {
    compiled = pathToRegex.compile(path)(args);
  } catch (e) {
    return { error: compilePathError(e) };
  }

  if (!compiled) {
    return { error: invalidArgumentError('path', path) };
  }

  const qp = stringify(R.propOr(undefined, 'queryParams', args));
  if (!R.isEmpty(qp)) {
    compiled = `${compiled}?${qp}`;
  }

  // Note the multiple returns above. If you made it here, it was successful
  return { path: compiled };
}
示例#26
0
const run = _.curry((req, middleware) => {
  const current   = _.head(middleware);
  const spec      = getSpec(req)(current);
  const io        = getIO(current);
  const transform = getTransform(current);
  const cur_data  = _.propOr({}, 'data', req);

  return spec(req)

  .then((data) => Bluebird.props(_.merge(cur_data, io(req, data) ))) 

  .then(transform.bind(current, req))

  .then(_.compose(_.merge(req), _.objOf('data')))

  .then((new_req) => {
    if (_.length(middleware) > 1) {
      return run(new_req, _.tail(middleware));
    }

    return new_req.data;
  })

});
const ooo = { a: 1, b: 2, A: 3, B: 4 };
const isUpperCase = (val, key) => key.toUpperCase() === key;
const pb: Object = _.pickBy(isUpperCase, ooo);

const ppp: ?number = _.prop("x", { x: 100 });
//$ExpectError
const ppp1: ?number = _.prop("y", { x: 100 });

const alice = {
  name: "ALICE",
  age: 101
};

//$ExpectError
const favoriteWithDefault = _.propOr("Ramda", "favoriteLibrary");
const fav = favoriteWithDefault(alice);

const nameWithDefault = _.propOr("Ramda", "name");
const nm: number | string = nameWithDefault(alice);

const pss: Array<?number | boolean> = _.props(["x", "y"], { x: true, y: 2 });
//$ExpectError
const pssE: Array<?number | boolean> = _.props(["d", "y"], { x: true, y: 2 });

const top: Array<["a" | "b" | "c", number]> = _.toPairs({ a: 1, b: 2, c: 3 });

//$ExpectError
const topE: Array<["a" | "b" | "c" | "z", number]> = _.toPairs({
  a: 1,
  b: 2,
示例#28
0
const attrHighlight = a => R.map(prefixToken(["string.attribute-value", a.name]), R.propOr([],'attr', a));
示例#29
0
const throwMiddlewareEmpty = () => {
  throw TypeError('You must provide at least one middleware');
};

const defaultSpec = _.always(_.compose(
  Bluebird.resolve
, _.prop('data')
))


const getSpec = (req) => _.compose(
  _.ifElse(_.is(Function), awesomize(req), defaultSpec)
, _.prop('awesomize')
);

const getIO = _.propOr((req, data) => data, 'io');


const getTransform = _.propOr((req, data) => data, 'transform');


const run = _.curry((req, middleware) => {
  const current   = _.head(middleware);
  const spec      = getSpec(req)(current);
  const io        = getIO(current);
  const transform = getTransform(current);
  const cur_data  = _.propOr({}, 'data', req);

  return spec(req)

  .then((data) => Bluebird.props(_.merge(cur_data, io(req, data) ))) 
示例#30
0
        href: '/chemical-supplier'
      }, h('i.fa.fa-plus', {
        title: '创建化学品供应商'
      })),
      h('.search', nameSearchBox)
    ]),
    table,
    tableHints,
    h('.paginator-container', paginator),
  ]);
};


const $$nameSearchBox = $$searchBox({
  defaultText: '输入名称或者缩写',
  $$searchText: $$queryObj.trans(R.propOr('', 'kw')),
  onsearch(kw) {
    $$queryObj.patch({ kw, page: 1 });
  },
  getHints(kw) {
    return chemicalSupplierStore.getHints(kw);
  }
});

export default {
  page: {
    get $$view() {
      let $$page = $$queryObj.map(R.prop('page'));
      let $$pageSize = $$queryObj.map(R.prop('page_size'));
      return $$.connect(
        [$$loading, $$nameSearchBox, $$table, $$tableHints({