下面的简单函数迭代地应用给定的monadic函数,直到它命中Nothing,此时它返回最后一个非Nothing值.它做我需要的,我理解它是如何工作的.
lastJustM :: (Monad m) => (a -> m (Maybe a)) -> a -> m a
lastJustM g x = g x >>= maybe (return x) (lastJustM g)
Run Code Online (Sandbox Code Playgroud)
作为我在Haskell的自我教育的一部分,我试图尽可能避免明确的递归(或至少理解如何).在这种情况下,似乎应该有一个简单的非显式递归解决方案,但我无法搞清楚.
我不希望像一个一元版本的takeWhile,因为它可以收集所有没有预值昂贵,反正我不关心他们.
我检查了Hoogle的签名,没有任何显示.这个m (Maybe a)位让我觉得monad变换器在这里可能很有用,但我真的不具备我需要提出细节的直觉(还).
这可能要么是令人尴尬地容易做到这一点,要么令人尴尬地容易理解为什么不能或不应该这样做,但这不是我第一次将自我尴尬作为一种教学策略.
更新:我当然可以提供谓词而不是使用Maybe:类似(a -> Bool) -> (a -> m a) -> a(返回谓词为真的最后一个值)也可以正常工作.我感兴趣的是使用标准组合器编写没有显式递归的任一版本的方法.
背景:这是一个简化的上下文工作示例:假设我们对单位广场中的随机游走感兴趣,但我们只关心退出点.我们有以下步骤功能:
randomStep :: (Floating a, Ord a, Random a) =>
a -> (a, a) -> State StdGen (Maybe (a, a))
randomStep s (x, y) …Run Code Online (Sandbox Code Playgroud) 我在代码审查中遇到了以下方法.在循环内部,Resharper告诉我这if (narrativefound == false)是不正确的,因为narrativeFound总是如此.我不认为是这种情况,因为为了设置narrativeFound为true,它必须首先传递条件字符串比较,那么它怎么总是真的呢?我错过了什么吗?这是Resharper或我们的代码中的错误吗?
public Chassis GetChassisForElcomp(SPPA.Domain.ChassisData.Chassis asMaintained, SPPA.Domain.ChassisData.Chassis newChassis)
{
Chassis c = asMaintained;
List<Narrative> newNarrativeList = new List<Narrative>();
foreach (Narrative newNarrative in newChassis.Narratives)
{
bool narrativefound = false;
foreach (Narrative orig in asMaintained.Narratives)
{
if (string.Compare(orig.PCode, newNarrative.PCode) ==0 )
{
narrativefound = true;
if (newNarrative.NarrativeValue.Trim().Length != 0)
{
orig.NarrativeValue = newNarrative.NarrativeValue;
newNarrativeList.Add(orig);
}
break;
}
if (narrativefound == false)
{
newNarrativeList.Add(newNarrative);
}
}
}
c.SalesCodes = newChassis.SalesCodes;
c.Narratives = newNarrativeList;
return c; …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过Interop.Word(11.0)使用Word Automation为Word文档编写查找/替换代码.我的文档都有各种字段(没有显示在Document.Fields中),用括号括起来,例如,<DATE>需要替换DateTime.Now.Format("MM/dd/yyyy").查找/替换工作正常.但是,一些被替换的文本是右对齐的,并且在替换时,文本将换行到下一行.当我执行替换时,有什么方法可以保持理由吗?代码如下:
using Word = Microsoft.Office.Interop.Word;
Word.Application wordApp = null;
try
{
wordApp = new Word.Application {Visible = false};
//.... open the document ....
object unitsStory = Word.WdUnits.wdStory;
object moveType = Word.WdMovementType.wdMove;
wordApp.Selection.HomeKey(ref unitsStory, ref moveType);
wordApp.Selection.Find.ClearFormatting();
wordApp.Selection.Find.Replacement.ClearFormatting(); //tried removing this, no luck
object replaceTextWith = DateTime.Now.ToString("MM/dd/yyyy");
object textToReplace = "<DATE>";
object replaceAll = Word.WdReplace.wdReplaceAll;
object typeMissing = System.Reflection.Missing.Value;
wordApp.Selection.Find.Execute(ref textToReplace, ref typeMissing,
ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing,
ref typeMissing, ref typeMissing, ref …Run Code Online (Sandbox Code Playgroud) 我有一个asp.net网站,它将生成一些包含7-8张数据的excel文件.到目前为止,最好的解决方案似乎是NPOI,这可以创建excel文件而无需在服务器上安装excel,并且有一个很好的API simillar到excel互操作.
但是,我无法找到一种方法来转储excel中的整个数据表类似于 CopyFromRecordset
关于如何做到这一点的任何提示,或者比NPOI更好的解决方案?
SQLAlchemy中是否可以有多级多态?这是一个例子:
class Entity(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
entity_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_on': entity_type}
class File(Entity):
__tablename__ = 'files'
id = Column(None, ForeignKey('entities.id'), primary_key=True)
filepath = Column(Unicode(255), nullable=False)
file_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_identity': u'file', 'polymorphic_on': file_type)
class Image(File):
__mapper_args__ = {'polymorphic_identity': u'image'}
__tablename__ = 'images'
id = Column(None, ForeignKey('files.id'), primary_key=True)
width = Column(Integer)
height = Column(Integer)
Run Code Online (Sandbox Code Playgroud)
当我调用时Base.metadata.create_all(),SQLAlchemy会引发以下错误:
IntegrityError: (IntegrityError) entities.entity_type may not be NULL`.
Run Code Online (Sandbox Code Playgroud)
如果我删除Image模型和 …
我有一个项目资源,有很多任务.我想确保每个任务都有一个project_id添加validates_presence_of :project_id到任务模型.
但是,在使用任务创建新项目时,在记录保存之前,project_id将不可用,因此我无法使用validates_presence_of :project_id.
所以我的问题是,如何在任务模型中验证project_id的存在?我想确保每个任务都有父母.
...
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
accepts_nested_attributes_for :tasks, :allow_destroy => true
Run Code Online (Sandbox Code Playgroud)
...
class Task < ActiveRecord::Base
belongs_to :project
validates_presence_of :project_id
Run Code Online (Sandbox Code Playgroud) 使用Factory方法检索注入的对象是不错的做法,还是只使用DI框架中的工厂方法?
我正在使用结构图,我应该只使用ObjectFactory.GetInstance();还是应该创建工厂类并在此类中调用ObjectFactory.GetInstance();? 因为如果我调用ObjectFactory.GetInstance(); 在我的课程中,我将创建与DI框架的耦合?抱歉,如果我无知,我对这个概念不熟悉.谢谢!
我在python中读取由制表符分隔的csv文件时遇到问题.我使用以下功能:
def csv2array(filename, skiprows=0, delimiter='\t', raw_header=False, missing=None, with_header=True):
"""
Parse a file name into an array. Return the array and additional header lines. By default,
parse the header lines into dictionaries, assuming the parameters are numeric,
using 'parse_header'.
"""
f = open(filename, 'r')
skipped_rows = []
for n in range(skiprows):
header_line = f.readline().strip()
if raw_header:
skipped_rows.append(header_line)
else:
skipped_rows.append(parse_header(header_line))
f.close()
if missing:
data = genfromtxt(filename, dtype=None, names=with_header,
deletechars='', skiprows=skiprows, missing=missing)
else:
if delimiter != '\t':
data = genfromtxt(filename, dtype=None, names=with_header, delimiter=delimiter, …Run Code Online (Sandbox Code Playgroud) 我正在做一个小程序,我想用这个食谱分发它:
__main__.py在其中#!/usr/bin/env python问题是在这个包中我还有额外的文件(我使用pygtk工具包,我需要图像和ui xml文件).当我尝试访问这些文件时,我遇到资源不可用的错误(我尝试打开的路径类似于file.zip/gui/gui.ui).
我该如何处理这种情况?
是否有一种干净的方法让您的fabfile接受命令行参数?我正在为一个工具编写一个安装脚本,我希望能够通过命令行指定一个可选的目标目录.
我写了一些代码来测试如果我传入一些命令行参数会发生什么:
# fabfile.py
import sys
def install():
_get_options()
def _get_options():
print repr(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
几个运行:
$ fab install
['install']
Done.
$ fab install --electric-boogaloo
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
fab: error: no such option: --electric-boogaloo
Run Code Online (Sandbox Code Playgroud) c# ×4
python ×4
.net ×3
.net-3.5 ×1
asp.net ×1
csv ×1
datatable ×1
excel ×1
fabric ×1
haskell ×1
matplotlib ×1
models ×1
monads ×1
ms-word ×1
nested-forms ×1
npoi ×1
numpy ×1
packaging ×1
resharper ×1
scipy ×1
sqlalchemy ×1
structuremap ×1
validation ×1