text:
import site
import os.path
site.addsitedir(os.path.join(os.path.dirname(__file__), 'lib'))

redpajama_set_name: RedPajamaGithub


text:
import json
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
# 导入登录,认证
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile, EmialVertifiedRecode
from django.db.models import Q
from django.views.generic.base import View
from forms import LoginForm, RegisterForm, ForgetPasswordForm, ModifyPwdForm, UploadImageForm, UpdatePwdForm, \
	UpdateUserInfoForm
from django.contrib.auth.hashers import make_password
from utils.emial_send import send_register_email
from utils.mixin_utils import LoginRequiredMixin
from operation.models import UserCourse, UserFavorite, UserMessage
from course.models import Course, Teacher
from origanization.models import CourseOrg
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

# 退出的View
class LayoutView(View):
	def get(self,request):
		# 登出
		logout(request)
		# 重定向
		# 将url名称反解成url地址
		from django.core.urlresolvers import reverse
		return HttpResponseRedirect(reverse('index'))

# 用户中心 消息提示
class MyMessageView(View):
	def get(self, request):
		all_messages = UserMessage.objects.filter(user=request.user.id).order_by('-add_time')
		try:
			page = request.GET.get('page', 1)
		except PageNotAnInteger:
			page = 1
		o = Paginator(all_messages, 2, request=request)
		all_messages = o.page(page)
		return render(request, 'usercenter-message.html', {'all_messages': all_messages})

# 用户中心 我的课程
class MyCourseView(View):
	def get(self, request):
		my_courses = UserCourse.objects.filter(user=request.user)
		return render(request, 'usercenter-mycourse.html', {
			'my_courses': my_courses
		})

# 收藏的课程
class MyFavCourses(View):
	def get(self, request):
		fav_courses = []
		ufs = UserFavorite.objects.filter(user=request.user, fav_type=1)
		for uf in ufs:
			c = Course.objects.get(id=uf.fav_id)
			fav_courses.append(c)
		return render(request, 'usercenter-fav-course.html', {'fav_courses': fav_courses})

# 收藏的讲师
class MyFavTeachers(View):
	def get(self, request):
		fav_teachers = []
		uts = UserFavorite.objects.filter(user=request.user, fav_type=2)
		for ut in uts:
			t = Teacher.objects.get(id=ut.fav_id)
			fav_teachers.append(t)
		return render(request, 'usercenter-fav-teacher.html', {'fav_teachers': fav_teachers})

# 收藏的机构
class MyFavOrgsView(View):
	def get(self, request):
		fav_orgs = []
		uos = UserFavorite.objects.filter(user=request.user, fav_type=2)
		for uo in uos:
			o = CourseOrg.objects.get(id=uo.fav_id)
			fav_orgs.append(o)
		return render(request, 'usercenter-fav-org.html', {'fav_orgs': fav_orgs})

# 更新个人信息的View
class UpdateUserInfoView(View):
	def post(self, request):
		updateuserinfoform = UpdateUserInfoForm(request.POST, instance=request.user)
		if updateuserinfoform.is_valid():
			request.user.save()
			return HttpResponse(json.dumps({
				'status': 'success'
			}), content_type='application/json')
		else:
			return HttpResponse(json.dumps(updateuserinfoform.errors), content_type='application/json')

# 用户中心重置邮箱的view(发送验证码)
class SendEmailView(LoginRequiredMixin, View):
	def get(self, request):
		email = request.GET.get('email', '')
		if UserProfile.objects.filter(email=email):
			return HttpResponse(json.dumps({
				'email': '邮箱已存在',
				'status': 'failure'
			}), content_type='application/json')
		else:
			send_register_email(email, send_type='reset_email')
			return HttpResponse(json.dumps({
				'status': 'success'
			}), content_type='application/json')

# 修改个人邮箱的View
class UpdateEmailView(View):
	def post(self, request):
		email = request.POST.get('email', '')
		code = request.POST.get('code', '')
		recode = EmialVertifiedRecode.objects.get(email=email, code=code, send_type='reset_email')
		if recode:
			request.user.email = email
			request.user.save()
			return HttpResponse(json.dumps({
				'status': 'success',
			}), content_type='application/json')
		else:
			return HttpResponse(json.dumps({
				'status': 'failure',
				'email': '邮箱或验证码错误'
			}), content_type='application/json')

# 用户中心重置密码的view
class UpdatePwdView(LoginRequiredMixin, View):
	def post(self, request):
		updatepwdform = UpdatePwdForm(request.POST)
		if updatepwdform.is_valid():
			pwd1 = request.POST.get('password1', '')
			pwd2 = request.POST.get('password2', '')
			if pwd1 == pwd2:
				request.user.password = make_password(pwd1)
				request.user.save()
				return HttpResponse(json.dumps({
					'status': 'success',
				}), content_type='application/json')
		else:
			return HttpResponse(json.dumps(updatepwdform.errors), content_type='application/json')

# 用户上传图片的view
class UploadImageView(LoginRequiredMixin, View):
	def post(self, request):
		# 验证文件的类型
		image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
		if image_form.is_valid():
			request.user.save()
			return HttpResponse('{"status":"success"}', content_type='application/json')
		else:
			return HttpResponse('{"status":"fail"}', content_type='application/json')

# 用户中心 用户信息
class UserInfoView(LoginRequiredMixin, View):
	def get(self, request):
		return render(request, 'usercenter-info.html')

# 自定义 auth 登录认证类
class CustomBackend(ModelBackend):
	def authenticate(self, username=None, password=None, **kwargs):
		try:
			# , 交集  | 是并集 Q(username=username)|Q(email=username),Q(password=password)
			user = UserProfile.objects.get(Q(username=username) | Q(email=username))
			if user.check_password(password):
				return user
		except Exception as e:
			return None

# 重置密码的 view
class ResetPwdView(View):
	def get(self, request, reset_code):
		all_code = EmialVertifiedRecode.objects.filter(code=reset_code)
		if all_code:
			for recode in all_code:
				email = recode.email
				return render(request, 'password_reset.html', {'email': email})
		else:
			return HttpResponse('验证失败')

# 修改用户密码的view
class ModifyView(View):
	def post(self, request):
		modifyform = ModifyPwdForm(request.POST)
		if modifyform.is_valid():
			password = request.POST.get('password', '')
			password2 = request.POST.get('password2', '')
			email = request.POST.get('email')
			if password == password2:
				user = UserProfile.objects.filter(email=email)
				if user:
					user.password = make_password(password)
					user.save()
					return render(request, 'login.html', {})
				else:
					return HttpResponse('重置密码错误')
			else:
				return render(request, 'password_reset.html', {'msg': '两次输入密码不一致'})

# 找回密码的view
class ForgetPwdView(View):
	def get(self, request):
		forgetpasswordform = ForgetPasswordForm()
		return render(request, 'forgetpwd.html', {'forget_form': forgetpasswordform})

	def post(self, request):
		forgetpasswordform = ForgetPasswordForm(request.POST)
		if forgetpasswordform.is_valid():
			email = request.POST.get('email', '')
			user = UserProfile.objects.filter(email=email)
			if user:
				send_register_email(email=email, send_type='forget')
				return HttpResponse('邮件已发送,请查收')
			else:
				return HttpResponse('该邮箱未注册!')
		else:
			return render(request, 'forgetpwd.html', {'forget_form': forgetpasswordform})

# 激活用户的类
class ActiveUserView(View):
	def get(self, request, active_code):
		all_code = EmialVertifiedRecode.objects.filter(code=active_code)
		if all_code:
			for recode in all_code:
				email = recode.email
				user = UserProfile.objects.get(email=email)
				user.is_active = True
				user.save()
		else:
			return HttpResponse('连接错误,验证失败!')
		return render(request, 'login.html')

	def post(self, request):
		pass

# 注册的 Views
class RegisterView(View):
	def get(self, request):
		register_form = RegisterForm()
		return render(request, 'register.html', {'register_form': register_form})

	def post(self, request):
		register_form = RegisterForm(request.POST)
		if register_form.is_valid():
			username = request.POST.get('email', '')
			password = request.POST.get('password', '')
			user = UserProfile()
			user.username = username
			user.email = username
			if UserProfile.objects.filter(email=username):
				return render(request, 'register.html', {'register_form': register_form, 'msg': '用户已存在'})
			user.password = make_password(password)
			# 表明用户未激活
			user.is_active = False
			user.save()
			send_register_email(email=username, send_type='register')
			return render(request, 'login.html', {})
		else:
			return render(request, 'register.html', {'register_form': register_form})

# 基于类的 view
# 登录的 View
class LoginView(View):
	# 自动调用 get或者 get
	def get(self, request):
		return render(request, 'login.html', {})

	def post(self, request):
		# 声明 form 的实例
		login_form = LoginForm(request.POST)
		if login_form.is_valid():
			username = request.POST.get('username', '')
			password = request.POST.get('password', '')
			# auth 登录验证
			user = authenticate(username=username, password=password)
			if user is not None:
				# 注意不要和默认函数名称重合
				if user.is_active:
					login(request, user)
					return render(request, 'index.html')
				else:
					return render(request, 'login.html', {'msg': '账号未激活'})
			else:
				return render(request, 'login.html', {'msg': '账号或密码错误'})
		else:
			return render(request, 'login.html', {'login_form': login_form})

# Create your views here.
# def user_login(request):
# 	if request.method == 'POST':
# 		username = request.POST.get('username', '')
# 		password = request.POST.get('password', '')
# 		# auth 登录验证
# 		user = authenticate(username=username, password=password)
# 		if user is not None:
# 			# 注意不要和默认函数名称重合
# 			login(request, user)
# 			return render(request, 'index.html')
# 		else:
# 			return render(request, 'login.html', {'msg': '账号或密码错误!'})
#
# 	elif request.method == 'GET':
# 		return render(request, 'login.html', {})


text:
import pymxs
import MaxPlus
from anima.render.mat_converter import ConversionManagerBase, NodeCreatorBase

CONVERSION_SPEC_SHEET = {
    "VRayMtl": {
        "node_type": MaxPlus.Mtl,
        "secondary_type": "Redshift Material",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "diffuse": "diffuse_color",
            "diffuse_roughness": "diffuse_roughness",
            "selfIllumination": "emission_color",
            # 'selfIllumination_gi': '',
            "selfIllumination_multiplier": "emission_weight",
            "reflection": {
                "refl_color": lambda x: x,
                "refl_weight": lambda x, y: get_refl_weight(x, y),
            },
            "reflection_glossiness": "refl_roughness",
            # 'hilight_glossiness': '',
            # 'reflection_subdivs': {
            #     'refl_samples': lambda x: 16,
            # },
            # 'reflection_fresnel': '',
            "reflection_maxDepth": "refl_depth",
            # 'reflection_exitColor': '',
            # 'reflection_useInterpolation': '',
            "reflection_ior": "refl_ior",
            # 'reflection_lockGlossiness': '',
            # 'reflection_lockIOR': '',
            # 'reflection_dimDistance': '',
            # 'reflection_dimDistance_on': '',
            # 'reflection_dimDistance_falloff': '',
            # 'reflection_affectAlpha': '',
            "refraction": {
                "refr_color": lambda x: x,
                "refr_weight": lambda x, y: get_refr_weight(x, y),
            },
            "refraction_glossiness": {
                "refr_roughness": lambda x: x,
                "refr_isGlossiness": True,
            },
            # 'refraction_subdivs': '',
            "refraction_ior": "refr_ior",
            # 'refraction_fogColor': '',
            # 'refraction_fogMult': '',
            # 'refraction_fogBias': '',
            # 'refraction_affectShadows': '',
            # 'refraction_affectAlpha': '',
            "refraction_maxDepth": "refr_depth",
            # 'refraction_exitColor': '',
            # 'refraction_useExitColor': '',
            # 'refraction_useInterpolation': '',
            # 'refraction_dispersion': 'refr_abbe',
            "refraction_dispersion_on": {
                "refr_abbe": lambda x, y: y.ParameterBlock.refraction_dispersion.Value
                if ((x - 1.0) / 149.0)
                else 0  # VRay uses a value between 1-150
                # fit it in to 0-100 range
            },
            # 'translucency_on': '',
            # 'translucency_thickness': '',
            # 'translucency_scatterCoeff': '',
            # 'translucency_fbCoeff': '',
            "translucency_scatterCoeff": {
                "transl_weight": lambda x, y: (
                    1 if y.ParameterBlock.translucency_on.Value else 0
                )
                * x
            },
            "translucency_color": "transl_color",
            "brdf_type": {
                "refl_brdf": lambda x: {0: 0, 1: 0, 2: 2, 4: 1}[x],
            },
            "anisotropy": "refl_aniso",
            "anisotropy_rotation": "refl_aniso_rotation",
            # 'anisotropy_derivation': '',
            # 'anisotropy_axis': '',
            # 'anisotropy_channel': '',
            # 'soften': '',  # Couldn't find it in the UI
            # 'brdf_fixDarkEdges': '',
            # 'gtr_gamma': '',
            # 'gtr_oldGamma': '',
            "brdf_useRoughness": {
                "refl_isGlossiness": lambda x: not x,
            },
            # 'option_traceDiffuse': '',
            # 'option_traceReflection': '',
            # 'option_traceRefraction': '',
            # 'option_doubleSided': '',
            # 'option_reflectOnBack': '',
            # 'option_useIrradMap': '',
            # 'refraction_fogUnitsScale_on': '',
            # 'option_traceDiffuseAndGlossy': '',
            "option_cutOff": {
                "refl_cutoff": lambda x: x,
                "refr_cutoff": lambda x: x,
            },
            "preservationMode": {"energyCompMode": lambda x: 1 - x},
            # 'option_environment_priority': '',
            # 'effect_id': '',  # There should have been a material_id but
            # like the one in Maya, but I couldn't find it
            # 'override_effect_id': '',
            # 'option_clampTextures': '',
            # 'option_opacityMode': '',  # May be related with the
            # affects_alpha option
            # 'option_glossyFresnel':,
            "texmap_diffuse": "diffuse_color_map",
            "texmap_diffuse_on": "diffuse_color_mapenable",
            "texmap_diffuse_multiplier": "diffuse_color_mapamount",
            "texmap_reflection": "refl_color_map",
            "texmap_reflection_on": "refl_color_mapenable",
            "texmap_reflection_multiplier": "refl_color_mapamount",
            "texmap_refraction": "refr_color_map",
            "texmap_refraction_on": "refr_color_mapenable",
            "texmap_refraction_multiplier": "refr_color_mapamount",
            "texmap_bump": {
                "bump_input_map": lambda x: create_bump_node(x),
            },
            "texmap_bump_on": "bump_input_mapenable",
            "texmap_bump_multiplier": "bump_input_mapamount",
            "texmap_reflectionGlossiness": "refl_roughness_map",
            "texmap_reflectionGlossiness_on": "refl_roughness_mapenable",
            "texmap_reflectionGlossiness_multiplier": "refl_roughness_mapamount",
            "texmap_refractionGlossiness": "refr_roughness_map",
            "texmap_refractionGlossiness_on": "refr_roughness_mapenable",
            "texmap_refractionGlossiness_multiplier": "refr_roughness_mapamount",
            "texmap_refractionIOR": "refr_ior_map",
            "texmap_refractionIOR_on": "refr_ior_mapenable",
            "texmap_refractionIOR_multiplier": "refr_ior_mapamount",
            "texmap_displacement": {
                "displacement_input_map": lambda x: create_displacement_node(x),
            },
            "texmap_displacement_on": "displacement_input_mapenable",
            "texmap_displacement_multiplier": "displacement_input_mapamount",
            "texmap_translucent": "transl_color_map",
            "texmap_translucent_on": "transl_color_mapenable",
            "texmap_translucent_multiplier": "transl_color_mapamount",
            # 'texmap_environment': '',
            # 'texmap_environment_on': '',
            #
            # 'texmap_hilightGlossiness': '',
            # 'texmap_hilightGlossiness_on': '',
            # 'texmap_hilightGlossiness_multiplier': '',
            "texmap_reflectionIOR": "refl_ior_map",
            "texmap_reflectionIOR_on": "refl_ior_mapenable",
            "texmap_reflectionIOR_multiplier": "refl_ior_mapamount",
            "texmap_opacity": "opacity_color_map",
            "texmap_opacity_on": "opacity_color_mapenable",
            "texmap_opacity_multiplier": "opacity_color_mapamount",
            "texmap_roughness": "diffuse_roughness_map",
            "texmap_roughness_on": "diffuse_roughness_mapenable",
            "texmap_roughness_multiplier": "diffuse_roughness_mapamount",
            "texmap_anisotropy": "refl_aniso_map",
            "texmap_anisotropy_on": "refl_aniso_mapenable",
            "texmap_anisotropy_multiplier": "refl_aniso_mapamount",
            "texmap_anisotropy_rotation": "refl_aniso_rotation_map",
            "texmap_anisotropy_rotation_on": "refl_aniso_rotation_mapenable",
            "texmap_anisotropy_rotation_multiplier": "refl_aniso_rotation_mapamount",
            # 'texmap_refraction_fog': '',
            # 'texmap_refraction_fog_on': '',
            # 'texmap_refraction_fog_multiplier': '',
            "texmap_self_illumination": "emission_color_map",
            "texmap_self_illumination_on": "emission_color_mapenable",
            "texmap_self_illumination_multiplier": "emission_color_mapamount",
            # 'reflect_minRate': '',
            # 'reflect_maxRate': '',
            # 'reflect_interpSamples': '',
            # 'reflect_colorThreshold': '',
            # 'reflect_normalThreshold': '',
            # 'refract_minRate': '',
            # 'refract_maxRate': '',
            # 'refract_interpSamples': '',
            # 'refract_colorThreshold': '',
            # 'refract_normalThreshold': '',
        },
    },
    "VRayBlendMtl": {
        "node_type": MaxPlus.Mtl,
        "secondary_type": "Redshift Material Blender",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "baseMtl": "baseColor_map",
            "coatMtl_enable": {
                "layerColor1_mapenable": lambda x: x[0],
                "layerColor2_mapenable": lambda x: x[1],
                "layerColor3_mapenable": lambda x: x[2],
                "layerColor4_mapenable": lambda x: x[3],
                "layerColor5_mapenable": lambda x: x[4],
                "layerColor6_mapenable": lambda x: x[5],
            },
            "coatMtl": {
                "layerColor1_map": lambda x: x[0],
                "layerColor2_map": lambda x: x[1],
                "layerColor3_map": lambda x: x[2],
                "layerColor4_map": lambda x: x[3],
                "layerColor5_map": lambda x: x[4],
                "layerColor6_map": lambda x: x[5],
            },
            "blend": {
                "blendColor1": lambda x: x[0],
                "blendColor2": lambda x: x[1],
                "blendColor3": lambda x: x[2],
                "blendColor4": lambda x: x[3],
                "blendColor5": lambda x: x[4],
                "blendColor6": lambda x: x[5],
            },
            "texmap_blend": {
                "blendColor1_map": lambda x: x[0],
                "blendColor2_map": lambda x: x[1],
                "blendColor3_map": lambda x: x[2],
                "blendColor4_map": lambda x: x[3],
                "blendColor5_map": lambda x: x[4],
                "blendColor6_map": lambda x: x[5],
            },
            # 'texmap_blend_multiplier': '',
            "additiveMode": [
                "additiveMode1",
                "additiveMode2",
                "additiveMode3",
                "additiveMode4",
                "additiveMode5",
                "additiveMode6",
            ],
        },
    },
    "VRayColor": {
        # Convert it to 3ds Max's Color Correction node
        "node_type": MaxPlus.Texmap,
        "secondary_type": "Color Correction",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "red": {
                "lightnessMode": 1,
                "exposureMode": 0,
                "enableR": True,
                "gainR": lambda x: x * 100,
            },
            "green": {
                "lightnessMode": 1,
                "exposureMode": 0,
                "enableG": True,
                "gainG": lambda x: x * 100,
            },
            "blue": {
                "lightnessMode": 1,
                "exposureMode": 0,
                "enableB": True,
                "gainB": lambda x: x * 100,
            },
            "rgb_multiplier": {
                "gammaRGB": lambda x: x * 100,
            },
            # 'alpha', # can do nothing
            "color": "color",
            "color_gamma": "gammaRGB",
        },
    },
    "VRayDirt": {
        "node_type": MaxPlus.Texmap,
        "secondary_type": "Redshift Ambient Occlusion",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "radius": "maxDistance",
            "occluded_color": "dark",
            "unoccluded_color": "bright",
            "distribution": "spread",
            "falloff": "fallOff",
            "subdivs": "numSamples",
            "bias": "bias",
            "affect_alpha": "occlusionInAlpha",
            # ignore_for_gi
            "consider_same_object_only": "sameObjectOnly",
            # double_sided
            "invert_normal": "invert",
            # work_with_transparency
            # environment_occlusion
            "mode": {
                "reflective": lambda x: min(1, x),
            },
            # reflection_glossiness
            # affect_reflection_elements
            "texmap_radius": "maxDistance_map",
            "texmap_radius_on": "maxDistance_mapenable",
            # texmap_radius_multiplier
            "texmap_occluded_color": "dark_map",
            "texmap_occluded_color_on": "dark_mapenable",
            # texmap_occluded_color_multiplier
            "texmap_unoccluded_color": "bright_map",
            "texmap_unoccluded_color_on": "bright_mapenable",
            # texmap_unoccluded_color_multiplier
            # texmap_reflection_glossiness
            # texmap_reflection_glossiness_on
            # texmap_reflection_glossiness_multiplier
            # subdivs_as_samples
        },
    },
    "VRayLightMtl": {
        "node_type": MaxPlus.Mtl,
        "secondary_type": "Redshift Incandescent",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "color": "color",
            "multiplier": "intensity",
            "texmap": "color_map",
            "texmap_on": "color_mapenable",
            "twoSided": "doublesided",
            "compensate_exposure": "applyExposureCompensation",
            # 'opacity_multiplyColor'
            "opacity_texmap": "alpha_map",
            "opacity_texmap_on": "alpha_mapenable",
            # directLight_on
            # directLight_subdivs
            # directLight_cutoffThreshold
            # displacement_multiplier
            # displacement_texmap
            # displacement_texmap_on
            # texmap_resolution
            # texmap_adaptiveness
        },
    },
    "VRayFastSSS2": {
        "node_type": MaxPlus.Mtl,
        "secondary_type": "Redshift Sub-Surface Scatter",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            # 'preset': '',
            "scale": "scale",
            "IOR": "ior",
            # 'multiple_scattering': '',
            # 'prepass_rate': '',
            # 'prepass_id': '',
            # 'auto_calculate_density': '',
            # 'samples_per_unit_area': '',
            # 'surface_offset': '',
            # 'preview_samples': '',
            # 'max_distance': '',
            # 'background_color': '',
            # 'samples_color': '',
            # 'overall_color': '',
            # 'diffuse_color': '',
            "diffuse_amount": "diffuse_amount",
            # 'color_mode': '',
            "sub_surface_color": "sub_surface_color",
            "scatter_color": "scatter_color",
            "scatter_radius": "scatter_radius",
            "phase_function": "phase",
            "specular_color": "refl_color",
            "specular_amount": "reflectivity",
            "specular_glossiness": "refl_gloss",
            "specular_subdivs": "refl_gloss_samples",
            "trace_reflections": {
                "refl_hl_only": lambda x: not x,
            },
            "reflection_depth": "refl_depth",
            "single_scatter": {
                "singleScatter_on": lambda x: True if x > 0 else False,
            },
            "single_scatter_subdivs": "ss_samples",
            "refraction_depth": "refr_depth",
            # 'front_lighting': '',
            # 'back_lighting': '',
            # 'scatter_gi': '',
            # 'prepass_LOD_threshold': '',
            # 'interpolation_accuracy': '',
            # 'legacy_mode': '',
            # 'prepass_blur': '',
            "cutoff_threshold": ["refl_cutoff", "refr_cutoff"],
            # 'prepass_mode': '',
            # 'prepass_fileName': '',
            "texmap_bump": {
                "bump_input_map": lambda x: create_bump_node(x),
            },
            "texmap_bump_on": "bump_input_mapenable",
            "texmap_bump_multiplier": "bump_input_mapamount",
            # 'texmap_opacity': '',
            # 'texmap_opacity_on': '',
            # 'texmap_opacity_multiplier': '',
            # 'texmap_overall_color': '',
            # 'texmap_overall_color_on': '',
            # 'texmap_overall_color_multiplier': '',
            # 'texmap_diffuse_color': '',
            # 'texmap_diffuse_color_on': '',
            # 'texmap_diffuse_color_multiplier': '',
            "texmap_diffuse_amount": "diffuse_amount_map",
            "texmap_diffuse_amount_on": "diffuse_amount_mapenable",
            "texmap_diffuse_amount_multiplier": "diffuse_amount_mapamount",
            "texmap_specular_color": "refl_color_map",
            "texmap_specular_color_on": "refl_color_mapenable",
            "texmap_specular_color_multiplier": "refl_color_mapamount",
            "texmap_specular_amount": "reflectivity_map",
            "texmap_specular_amount_on": "reflectivity_mapenable",
            "texmap_specular_amount_multiplier": "reflectivity_mapamount",
            "texmap_specular_glossiness": "refl_gloss_map",
            "texmap_specular_glossiness_on": "refl_gloss_mapenable",
            "texmap_specular_glossiness_multiplier": "refl_gloss_mapamount",
            "texmap_sss_color": "sub_surface_color_map",
            "texmap_sss_color_on": "sub_surface_color_mapenable",
            "texmap_sss_color_multiplier": "sub_surface_color_mapamount",
            "texmap_scatter_color": "scatter_color_map",
            "texmap_scatter_color_on": "scatter_color_mapenable",
            "texmap_scatter_color_multiplier": "scatter_color_mapamount",
            "texmap_scatter_radius": "scatter_radius_map",
            "texmap_scatter_radius_on": "scatter_radius_mapenable",
            "texmap_scatter_radius_multiplier": "scatter_radius_mapamount",
            "texmap_displacement": {
                "displacement_input_map": lambda x: create_displacement_node(x)
            },
            "texmap_displacement_on": "displacement_input_mapenable",
            "texmap_displacement_multiplier": "displacement_input_mapamount",
        },
    },
    "Normal Bump": {
        "node_type": MaxPlus.Texmap,
        "secondary_type": "Redshift Normal Map",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "mult_spin": "scale",
            # 'bump_spin': '',
            "normal_map": {
                "tex0": lambda x: set_bitmap_value(x),
            },
            # 'bump_map': '',
            # 'map1on': '',
            # 'map2on': '',
            "method": {
                "tspace_id": lambda x: x + 1,
            },
            # 'flipred': '',
            "flipgreen": "flipY",
            # 'swap_rg': '',
        },
    },
    "VRayNormalMap": {
        "node_type": MaxPlus.Texmap,
        "secondary_type": "Redshift Normal Map",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "normal_map": {
                "tex0": lambda x: set_bitmap_value(x),
                # 'unbiasedNormalMap': ,
                # 'eccmax': ,
                # 'alt_x': ,
                # 'alt_y': ,
                # 'repeats_x': ,
                # 'repeats_y': ,
                # 'wrapU': ,
                # 'wrapV': ,
                # 'min_uv_x': ,
                # 'min_uv_y': ,
                # 'max_uv_x': ,
                # 'max_uv_y': ,
            },
            # 'normal_map_on': '',
            "normal_map_multiplier": "scale",
            # 'bump_map': '',
            # 'bump_map_on': '',
            # 'bump_map_multiplier': '',
            "map_channel": "tspace_id",
            # 'flip_red': '',
            "flip_green": "flipY",
            # 'swap_red_and_green': '',
            # 'map_rotation': '',
        },
    },
    "VRayOverrideMtl": {
        "node_type": MaxPlus.Mtl,
        "secondary_type": "Redshift Ray Switch",
        # 'call_after': # write the code here to assign this material to
        # all of the objects that is using the VRayMtl
        "attributes": {
            "baseMtl": "cameraColor_map",
            "baseMtl_on": "cameraColor_mapenable",
            "giMtl": "giColor_map",
            "giMtl_on": "giColor_mapenable",
            "reflectMtl": "reflectionColor_map",
            "reflectMtl_on": "reflectionColor_mapenable",
            "refractMtl": "refractionColor_map",
            "refractMtl_on": "refractionColor_mapenable",
            # 'shadowMtl':
            # 'shadowMtl_on'
        },
    },
}

def get_refl_weight(value, source_node):
    """Returns the reflection weight for Redshift Material

    :param value:
    :param source_node:
    :return:
    """
    refl_color_map = source_node.ParameterBlock.texmap_reflection.Value
    refl_color_map_name = None
    try:
        refl_color_map_name = refl_color_map.GetName()
    except RuntimeError:
        pass

    if value.GetIntensity() > 0.0 or refl_color_map_name is not None:
        return 1.0
    else:
        return 0.0

def get_refr_weight(value, source_node):
    """Returns the refraction weight for Redshift Material

    :param value:
    :param source_node:
    :return:
    """
    refr_color_map = source_node.ParameterBlock.texmap_refraction.Value
    refr_color_map_name = None
    try:
        refr_color_map_name = refr_color_map.GetName()
    except RuntimeError:
        pass

    if value.GetIntensity() > 0.0 or refr_color_map_name is not None:
        return 1.0
    else:
        return 0.0

def set_bitmap_value(value, y=None, z=None):
    """sets bitmap value

    :param value:
    :param y:
    :param z:
    :return:
    """
    value_class_name = value.GetClassName()
    if value_class_name == "VRayNormalMap":
        value = value.ParameterBlock.normal_map.Value
    elif value_class_name == "Redshift Normal Map":
        return value.ParameterBlock.tex0.Value

    return value.ParameterBlock.bitmap.Value

def create_bump_node(source_value):
    """Creates a bump map

    :param source_value:
    :return:
    """
    try:
        source_value.GetName()
        rs_bump_map = NodeCreator.create_node_by_type(
            MaxPlus.Texmap, "Redshift Bump Map"
        )
        rs_bump_map.ParameterBlock.input_map.Value = source_value
        return rs_bump_map
    except RuntimeError:
        return None

def create_displacement_node(source_value):
    """Creates a bump map

    :param source_value:
    :return:
    """
    try:
        source_value.GetName()
        rs_displacement_map = NodeCreator.create_node_by_type(
            MaxPlus.Texmap, "Redshift Displacement Map"
        )
        rs_displacement_map.ParameterBlock.texMap_map.Value = source_value
        return rs_displacement_map
    except RuntimeError:
        return None

def use_front_material(source_node):
    """A helper function for VRay2SidedMtl. It will assign the front material
    to the nodes using this material.

    :param source_node:
    :return:
    """
    front_material = source_node.ParameterBlock.frontMtl.Value

    # connect to the outputs of the source_node
    for parent, param, i in ConversionManager.outputs(source_node):
        # param.Value = front_material
        ConversionManager.connect_attr(
            front_material, parent, "%s[%i]" % (param.GetName(), i)
        )

    # also assign the front material to all of the dependencies.
    while True:
        try:
            source_node.FindDependentNode().Material = front_material
        except RuntimeError:
            break

def print_out_node_info(source_value, source_node, target_node, template=""):
    """prints out node info

    :param source_value:
    :param source_node:
    :param target_node:
    :param str template:
    :return:
    """
    print(
        template.format(
            source_value=source_value, source_node=source_node, target_node=target_node
        )
    )

class NodeCreator(NodeCreatorBase):
    """Creates nodes according to the given specs"""

    def create(self):
        """creates the node"""
        node_class = self.specs.get("node_type")
        secondary_class = self.specs.get("secondary_type")

        new_node = self.create_node_by_type(node_class, secondary_class)

        # add it to Material manager slot
        MaxPlus.MaterialManager.PutMtlToMtlEditor(new_node, 0)
        return new_node

    @classmethod
    def create_node_by_type(cls, node_class, secondary_class_name):
        """Creates nodes by type name

        :param node_class: The MaxPlus class object (ex: MaxPlus.MtlBase)
        :param str secondary_class_name: A string for the node type name
        :return:
        """
        # get the class, its id and its super class id
        class_ = ConversionManager.get_class_by_name(secondary_class_name)

        class_id = class_.ClassId
        super_class_id = class_.SuperClassId

        # create an animatable
        animatable = MaxPlus.Factory.CreateAnimatable(super_class_id, class_id, False)

        # and cast it to the node_type
        new_node = node_class._CastFrom(animatable)

        return new_node

class ConversionManager(ConversionManagerBase):
    """Manages the conversion from VRay to RedShift"""

    def __init__(self):
        super(ConversionManager, self).__init__()
        self.conversion_spec_sheet = CONVERSION_SPEC_SHEET
        self.node_creator_factory = NodeCreator

    def auto_convert(self):
        """finds and converts all the nodes in the current scene"""
        # pre condition the scene
        #
        # First run the conversion script only for VRay2SidedMtl
        # because it is causing a problem
        for node in self.get_node_by_class("VRay2SidedMtl"):
            use_front_material(node)

        # then call the super
        return super(ConversionManager, self).auto_convert()

    def rename_node(self, node, new_name):
        """Renames the node

        :param node:
        :param new_name:
        :return:
        """
        node.SetName(MaxPlus.WStr(new_name))

    def get_node_name(self, node):
        """Returns the node name

        :param node:
        :return:
        """
        return node.GetName()

    def get_node_inputs(self, node, attr=None):
        """returns the node inputs

        :param node:
        :param attr:
        :return:
        """
        inputs = []
        if attr is None:
            # return all connected nodes
            for param in node.ParameterBlock.Parameters:
                value = param.GetValue()
                # TODO: This one doesn't consider that the parameter is a multi
                # parameter.
                if isinstance(value, MaxPlus.Animatable) and str(value) != "None":
                    inputs.append(value)
        else:
            param = node.ParameterBlock.GetParamByName(attr)
            value = param.GetValue()
            if isinstance(value, MaxPlus.Animatable) and str(value) != "None":
                inputs.append(value)

        return inputs

    @classmethod
    def connect_attr(cls, source_node, target_node, target_parameter):
        """creates a connection from source_attr to target_attr target_node

        :param source_node:
        :param target_node:
        :param str target_parameter:
        :return:
        """
        # param = target_node.ParameterBlock.GetParamByName(target_attr)
        # param.Value = source_attr

        # do it with pymxs
        MaxPlus.MaterialManager.PutMtlToMtlEditor(source_node, 0)
        source_node_pymxs = pymxs.runtime.getMEditMaterial(1)

        # get the parent node
        MaxPlus.MaterialManager.PutMtlToMtlEditor(target_node, 1)
        target_node_pymxs = pymxs.runtime.getMEditMaterial(2)

        # Then execute the connection script
        exec("target_node_pymxs.%s = source_node_pymxs" % target_parameter)
        # This should've worked!

    @classmethod
    def get_class_by_name(cls, class_name):
        """returns the class_id from the given class_name

        :param str class_name: The class name
        :return MaxPlus.Class_ID:
        """
        for c in MaxPlus.PluginManager.GetClassList().Classes:
            if c.Name == class_name:
                return c

    @classmethod
    def get_class_id_by_name(cls, class_name):
        """returns the class_id from the given class_name

        :param str class_name: The class name
        :return MaxPlus.Class_ID:
        """
        c = cls.get_class_by_name(class_name)
        return c.ClassId

    @classmethod
    def get_super_class_id_by_name(cls, class_name):
        """returns the super class id of the given class

        :param str class_name: Class Name
        :return:
        """
        c = cls.get_class_by_name(class_name)
        return c.SuperClassId

    @classmethod
    def get_class_name(cls, class_id):
        """returns the class_name from the given class_id

        :param class_id:
        :return:
        """
        for cd in MaxPlus.PluginManager.GetClassList().Classes:
            if cd.ClassId == class_id:
                return cd.Name

    def get_node_type(self, node):
        """returns the node type name

        :param node:
        :return:
        """
        return self.get_class_name(node.ClassID)

    def list_nodes(self, type_):
        """list nodes of given type

        :param type_:
        :return:
        """
        # just return materials for now
        mat_lib = MaxPlus.MaterialLibrary.GetSceneMaterialLibrary()

        # nodes_to_return = []
        nodes_to_return = {}

        num_materials = mat_lib.GetNumMaterials()
        for i in range(num_materials):
            mat = mat_lib.GetMaterial(i)
            class_name = mat.GetClassName()
            if class_name == type_:
                nodes_to_return[mat.GetFullName()] = mat

            # try to get it from the material hierarchy
            for parent_mat, param, sub_mat, index in self.walk_material_hierarchy(mat):
                try:
                    class_name = sub_mat.GetClassName()
                except RuntimeError:
                    pass
                else:
                    if class_name == type_:
                        nodes_to_return[sub_mat.GetFullName()] = sub_mat

        return nodes_to_return.values()

    def get_node_by_name(self, node_name):
        """Finds and returns the node with the given name

        :param node_name:
        :return:
        """
        # just return materials for now
        mat_lib = MaxPlus.MaterialLibrary.GetSceneMaterialLibrary()

        num_materials = mat_lib.GetNumMaterials()
        nodes_to_return = []
        for i in range(num_materials):
            mat = mat_lib.GetMaterial(i)
            if mat.GetName() == node_name:
                nodes_to_return.append(mat)
                return nodes_to_return

            # try to get it from the material hierarchy
            for parent_mat, param, sub_mat, index in self.walk_material_hierarchy(mat):
                try:
                    sub_mat_name = sub_mat.GetName()
                except RuntimeError:
                    pass
                else:
                    if sub_mat_name == node_name:
                        nodes_to_return.append(sub_mat)
        return nodes_to_return

    def get_node_by_class(self, node_class_name):
        """Finds and returns the node with the given name

        :param string node_class_name:
        :return:
        """
        # just return materials for now
        mat_lib = MaxPlus.MaterialLibrary.GetSceneMaterialLibrary()

        num_materials = mat_lib.GetNumMaterials()
        nodes_to_return = []
        for i in range(num_materials):
            mat = mat_lib.GetMaterial(i)
            if mat.GetClassName() == node_class_name:
                nodes_to_return.append(mat)
                return nodes_to_return

            # try to get it from the material hierarchy
            for parent_mat, param, sub_mat, index in self.walk_material_hierarchy(mat):
                try:
                    sub_mat_class_name = sub_mat.GetClassName()
                except RuntimeError:
                    pass
                else:
                    if sub_mat_class_name == node_class_name:
                        nodes_to_return.append(sub_mat)
        return nodes_to_return

    def get_attr(self, node, attr):
        """returns node attribute value

        :param node:
        :param attr:
        :return:
        """
        return node.ParameterBlock.GetParamByName(attr).GetValue()

    def set_attr(self, node, attr, value):
        """sets parameter value

        :param node:
        :param attr:
        :param value:
        :return:
        """
        if str(value) != "None":
            node.ParameterBlock.GetParamByName(attr).SetValue(value)

    def walk_hierarchy(self, node):
        """this is a generator that yields all dag nodes in the current scene"""
        for c in node.Children:
            yield c
            for gc in self.walk_hierarchy(c):
                yield gc

    @classmethod
    def walk_material_hierarchy(cls, node):
        """Walks through the material hierarchy through their parameters

        :param node:
        :return:
        """
        for p in node.ParameterBlock.Parameters:
            # decide what to do by looking at the parameter type of the p param
            param_type_name = MaxPlus.FPTypeGetName(p.GetParamType())
            value = p.Value
            if param_type_name in ["MtlTab", "TexmapTab"]:
                # it contains multiple materials
                for i, v in enumerate(value):
                    yield (node, p, v, i)
                    try:
                        v.GetName()
                        for pp in cls.walk_material_hierarchy(v):
                            yield pp
                    except (RuntimeError, AttributeError):
                        pass
            else:
                try:
                    value.GetName()
                    yield (node, p, value, -1)
                    if isinstance(value, MaxPlus.MtlBase):
                        for pp in cls.walk_material_hierarchy(value):
                            yield pp
                except (RuntimeError, AttributeError):
                    pass

    # @classmethod
    # def inputs(cls, node):
    #     """return the inputs of the given node
    #     :param node:
    #     :return:
    #     """
    #     # traverse parameters
    #     for p in node.ParameterBlock.Parameters:
    #         if p.GetParamType()

    @classmethod
    def outputs(cls, node):
        """return the node and the parameter that this node is connected to

        :param node:
        :return:
        """
        inode = node.FindDependentNode()
        try:
            top_mat = inode.Material
        except RuntimeError:
            # No inode just return
            return

        for parent, param, child, i in cls.walk_material_hierarchy(top_mat):
            try:
                if child.GetFullName() == node.GetFullName():
                    # we found our material but where did we come here
                    yield parent, param, i
            except RuntimeError:
                # This is not what you think it is...
                # so pass
                pass

    def clean_up(self, new_nodes):
        """A clean up stage for assigning materials to objects in the scene

        :param new_nodes: a list of lists of
            [[old_node, new_node], [old_node, new_node]...] style
        :return:
        """
        for old_node, new_node in new_nodes:
            # get the INodes using directly the old_node as material
            # Recursively assign the new material to the objects
            print("cleaning up: %s" % old_node.GetName())
            iteration = 0
            while True:
                iteration += 1
                inode = old_node.FindDependentNode()
                try:
                    inode_name = inode.GetName()
                    inode_mat = inode.GetMaterial()
                    print("updating material of (%i): %s" % (iteration, inode_name))
                except RuntimeError:
                    break
                if inode_mat.GetName() == old_node.GetName():
                    # directly assign the new_node as the material
                    try:
                        inode.SetMaterial(new_node)
                    except (TypeError, ValueError):
                        # the new_node is None
                        pass
                    # and fuck off
                else:
                    # then this node is used in a material network
                    # so update the referencing nodes to use the new node
                    # instead
                    for parent, param, i in self.outputs(old_node):
                        if i == -1:
                            param.Value = new_node
                        else:
                            try:
                                # unless this is is a Multi/Sub-Object node
                                # do it directly
                                if parent.GetClassName() == "Multi/Sub-Object":
                                    # convert it to a MaxPlus.Mtl object
                                    print(
                                        "using Mtl instead of MtlBase for "
                                        "Multi/Sub-Object"
                                    )
                                    # parent = MaxPlus.Mtl._CastFrom(parent)
                                    # # then use the SetSubMtl() method
                                    # parent.SetSubMtl(i, new_node)
                                    self.connect_attr(
                                        new_node,
                                        parent,
                                        "%s[%i]" % (param.GetName(), i),
                                    )
                                else:
                                    # do it with pymxs
                                    # I don't know any other way to pass the
                                    # Python material/texture to pymxs
                                    # so the best way I found was to use the
                                    # material editor
                                    print("using pymxs for complex connection!")
                                    print(
                                        "%s --> %s.%s[%s]"
                                        % (
                                            new_node.GetFullName(),
                                            parent.GetName(),
                                            param.GetName(),
                                            i,
                                        )
                                    )

                                    self.connect_attr(
                                        new_node,
                                        parent,
                                        "%s[%i]" % (param.GetName(), i),
                                    )

                                    # # put the material to slot 1. which is slot
                                    # # 0 in Python by the way
                                    # MaxPlus.MaterialManager.PutMtlToMtlEditor(
                                    #     new_node, 0
                                    # )
                                    # new_node_pymxs = \
                                    #     pymxs.runtime.getMEditMaterial(1)
                                    #
                                    # # get the parent node
                                    # MaxPlus.MaterialManager.PutMtlToMtlEditor(
                                    #     parent, 1
                                    # )
                                    # parent_pymxs = \
                                    #     pymxs.runtime.getMEditMaterial(2)
                                    #
                                    # # Then execute the connection script
                                    # exec(
                                    #     'parent_pymxs.%s[%i] = '
                                    #     'new_node_pymxs' % (param.GetName(), i)
                                    # )
                                    # # This should've worked!

                            except TypeError:
                                print(
                                    "Could not connect: %s --> %s.%s[%s]"
                                    % (
                                        new_node.GetFullName(),
                                        parent.GetName(),
                                        param.GetName(),
                                        i,
                                    )
                                )
                    # # do this only once
                    # break

    @classmethod
    def get_all_material_types_in_current_scene(cls):
        """returns all the material types in the current scene"""
        mat_types = {}
        mat_lib = MaxPlus.MaterialLibrary.GetSceneMaterialLibrary()
        mat_count = mat_lib.GetNumMaterials()
        for i in range(mat_count):
            mat = mat_lib.GetMaterial(i)
            mat_class_name = mat.GetClassName()
            if mat_class_name not in mat_types:
                mat_types[mat_class_name] = {"count": 0, "nodes": []}
            mat_types[mat_class_name]["count"] += 1
            mat_types[mat_class_name]["nodes"].append(mat)

            for parent, parameter, sub_mat, index in cls.walk_material_hierarchy(mat):
                try:
                    sub_mat_class_name = sub_mat.GetClassName()
                except RuntimeError:
                    continue
                if sub_mat_class_name not in mat_types:
                    mat_types[sub_mat_class_name] = {"count": 0, "nodes": []}
                mat_types[sub_mat_class_name]["count"] += 1
                mat_types[sub_mat_class_name]["nodes"].append(sub_mat)

        return mat_types

    def export_basic_material_attibutes(self, node):
        """exports basic material attributes to a json file.

        :return:
        """
        import os
        import tempfile

        json_file_path = os.path.join(tempfile.gettempdir(), "basic_material.json")

        data = {}

        exportable_types = [
            "Texmap",
            "Int",
            "PercentFraction",
            "Float",
            "FRgb",
            "Rgb",
            "Point3",
            "BOOL",
            "World",
        ]
        param_types = []
        for p in node.ParameterBlock.Parameters:
            param_type_name = MaxPlus.FPTypeGetName(p.GetParamType())
            # print(p.GetName(), )
            # data[p.GetName()] = p.Value;
            param_types.append(param_type_name)

        print(set(param_types))


text:
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin

admin.autodiscover()  # For Django 1.6

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^selectable/', include('selectable.urls')),
    url(r'', include('timepiece.urls')),

    # authentication views
    url(r'^accounts/login/$', auth_views.login,
        name='auth_login'),
    url(r'^accounts/logout/$', auth_views.logout_then_login,
        name='auth_logout'),
    url(r'^accounts/password-change/$',
        auth_views.password_change,
        name='change_password'),
    url(r'^accounts/password-change/done/$',
        auth_views.password_change_done),
    url(r'^accounts/password-reset/$',
        auth_views.password_reset,
        name='reset_password'),
    url(r'^accounts/password-reset/done/$',
        auth_views.password_reset_done),
    url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
        auth_views.password_reset_confirm),
    url(r'^accounts/reset/done/$',
        auth_views.password_reset_complete),
]


text:
package com.azure.resourcemanager.synapse.implementation;

import com.azure.resourcemanager.synapse.fluent.models.VulnerabilityAssessmentScanRecordInner;
import com.azure.resourcemanager.synapse.models.VulnerabilityAssessmentScanError;
import com.azure.resourcemanager.synapse.models.VulnerabilityAssessmentScanRecord;
import com.azure.resourcemanager.synapse.models.VulnerabilityAssessmentScanState;
import com.azure.resourcemanager.synapse.models.VulnerabilityAssessmentScanTriggerType;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.List;

public final class VulnerabilityAssessmentScanRecordImpl implements VulnerabilityAssessmentScanRecord {
    private VulnerabilityAssessmentScanRecordInner innerObject;

    private final com.azure.resourcemanager.synapse.SynapseManager serviceManager;

    VulnerabilityAssessmentScanRecordImpl(
        VulnerabilityAssessmentScanRecordInner innerObject,
        com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
    }

    public String id() {
        return this.innerModel().id();
    }

    public String name() {
        return this.innerModel().name();
    }

    public String type() {
        return this.innerModel().type();
    }

    public String scanId() {
        return this.innerModel().scanId();
    }

    public VulnerabilityAssessmentScanTriggerType triggerType() {
        return this.innerModel().triggerType();
    }

    public VulnerabilityAssessmentScanState state() {
        return this.innerModel().state();
    }

    public OffsetDateTime startTime() {
        return this.innerModel().startTime();
    }

    public OffsetDateTime endTime() {
        return this.innerModel().endTime();
    }

    public List<VulnerabilityAssessmentScanError> errors() {
        List<VulnerabilityAssessmentScanError> inner = this.innerModel().errors();
        if (inner != null) {
            return Collections.unmodifiableList(inner);
        } else {
            return Collections.emptyList();
        }
    }

    public String storageContainerPath() {
        return this.innerModel().storageContainerPath();
    }

    public Integer numberOfFailedSecurityChecks() {
        return this.innerModel().numberOfFailedSecurityChecks();
    }

    public VulnerabilityAssessmentScanRecordInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.synapse.SynapseManager manager() {
        return this.serviceManager;
    }
}


text:
.class public Lcom/android/systemui/recents/events/activity/DockedTopTaskFailedEvent;
.super Lcom/android/systemui/recents/events/EventBus$Event;
.source "DockedTopTaskFailedEvent.java"

# instance fields
.field public final appName:Ljava/lang/String;

# direct methods
.method public constructor <init>(Ljava/lang/String;)V
    .locals 0

    invoke-direct {p0}, Lcom/android/systemui/recents/events/EventBus$Event;-><init>()V

    iput-object p1, p0, Lcom/android/systemui/recents/events/activity/DockedTopTaskFailedEvent;->appName:Ljava/lang/String;

    return-void
.end method


text:
using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using Elastic.Transport;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable restore
namespace Elastic.Clients.Elasticsearch;
public sealed partial class GeoHashPrecision : Union<double, string>
{
	public GeoHashPrecision(double geohash_length) : base(geohash_length)
	{
	}

	public GeoHashPrecision(string distance) : base(distance)
	{
	}
}


text:
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Json.Extensions;

namespace Skybrud.Social.Instagram.BasicDisplay.Models.Authentication {

    /// <summary>
    /// Class with information about a short-lived access token.
    /// </summary>
    public class InstagramShortLivedToken : InstagramToken {

        #region Properties

        /// <summary>
        /// Gets the ID of the authenticated user.
        /// </summary>
        public long UserId { get; }

        #endregion

        #region Constructors

        private InstagramShortLivedToken(JObject json) : base(json) {
            UserId = json.GetInt64("user_id");
        }

        #endregion

        #region Static methods

        /// <summary>
        /// Parses the specified <paramref name="json"/> object into an instance of <see cref="InstagramShortLivedToken"/>.
        /// </summary>
        /// <param name="json">The instance of <see cref="JObject"/> to be parsed.</param>
        /// <returns>An instance of <see cref="InstagramLongLivedToken"/>.</returns>
        public static InstagramShortLivedToken Parse(JObject json) {
            return json == null ? null : new InstagramShortLivedToken(json);
        }

        #endregion

    }

}


text:
package org.axonframework.eventsourcing.eventstore.legacy.jdbc;

import org.axonframework.common.Assert;
import org.axonframework.common.jdbc.ConnectionProvider;
import org.axonframework.common.jdbc.PersistenceExceptionResolver;
import org.axonframework.common.transaction.TransactionManager;
import org.axonframework.eventsourcing.eventstore.TrackedEventData;
import org.axonframework.eventsourcing.eventstore.TrackingToken;
import org.axonframework.eventsourcing.eventstore.jdbc.EventSchema;
import org.axonframework.eventsourcing.eventstore.jdbc.JdbcEventStorageEngine;
import org.axonframework.eventsourcing.eventstore.legacy.GenericLegacyDomainEventEntry;
import org.axonframework.eventsourcing.eventstore.legacy.LegacyTrackingToken;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.upcasting.event.EventUpcasterChain;
import org.axonframework.serialization.xml.XStreamSerializer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;

/**
 * EventStorageEngine implementation that uses JDBC to store and fetch events in a way that is compatible with the event
 * store format of Axon version 2.x.
 *

 * By default the payload of events is stored as a serialized blob of bytes. Other columns are used to store meta-data
 * that allow quick finding of DomainEvents for a specific aggregate in the correct order.
 *
 * @author Rene de Waele
 */
public class LegacyJdbcEventStorageEngine extends JdbcEventStorageEngine {

    /**
     * Initializes an EventStorageEngine that uses JDBC to store and load events using the default {@link EventSchema}.
     * The payload and metadata of events is stored as a serialized blob of bytes using a new {@link XStreamSerializer}.
     *

     * Events are read in batches of 100. No upcasting is performed after the events have been fetched.
     *
     * @param connectionProvider The provider of connections to the underlying database
     * @param transactionManager The transaction manager used to set the isolation level of the transaction when loading
     *                           events
     */
    public LegacyJdbcEventStorageEngine(ConnectionProvider connectionProvider, TransactionManager transactionManager) {
        super(connectionProvider, transactionManager);
    }

    /**
     * Initializes an EventStorageEngine that uses JDBC to store and load events using the default {@link EventSchema}.
     * The payload and metadata of events is stored as a serialized blob of bytes using the given {@code serializer}.
     *

     * Events are read in batches of 100. The given {@code upcasterChain} is used to upcast events before
     * deserialization.
     *
     * @param serializer                   Used to serialize and deserialize event payload and metadata.
     * @param upcasterChain                Allows older revisions of serialized objects to be deserialized.
     * @param persistenceExceptionResolver Detects concurrency exceptions from the backing database. If {@code null}
     *                                     persistence exceptions are not explicitly resolved.
     * @param connectionProvider           The provider of connections to the underlying database
     * @param transactionManager           The transaction manager used to set the isolation level of the transaction
     *                                     when loading events
     */
    public LegacyJdbcEventStorageEngine(Serializer serializer, EventUpcasterChain upcasterChain,
                                        PersistenceExceptionResolver persistenceExceptionResolver,
                                        TransactionManager transactionManager, ConnectionProvider connectionProvider) {
        super(serializer, upcasterChain, persistenceExceptionResolver, transactionManager, connectionProvider);
    }

    /**
     * Initializes an EventStorageEngine that uses JDBC to store and load events.
     *
     * @param serializer                   Used to serialize and deserialize event payload and metadata.
     * @param upcasterChain                Allows older revisions of serialized objects to be deserialized.
     * @param persistenceExceptionResolver Detects concurrency exceptions from the backing database. If {@code null}
     *                                     persistence exceptions are not explicitly resolved.
     * @param transactionManager           The transaction manager used to set the isolation level of the transaction
     *                                     when loading events
     * @param batchSize                    The number of events that should be read at each database access. When more
     *                                     than this number of events must be read to rebuild an aggregate's state, the
     *                                     events are read in batches of this size. Tip: if you use a snapshotter, make
     *                                     sure to choose snapshot trigger and batch size such that a single batch will
     *                                     generally retrieve all events required to rebuild an aggregate's state.
     * @param connectionProvider           The provider of connections to the underlying database
     * @param dataType                     The data type for serialized event payload and metadata
     * @param schema                       Object that describes the database schema of event entries
     */
    public LegacyJdbcEventStorageEngine(Serializer serializer, EventUpcasterChain upcasterChain,
                                        PersistenceExceptionResolver persistenceExceptionResolver,
                                        TransactionManager transactionManager, Integer batchSize,
                                        ConnectionProvider connectionProvider, Class<?> dataType, EventSchema schema) {
        super(serializer, upcasterChain, persistenceExceptionResolver, transactionManager, batchSize,
              connectionProvider, dataType, schema);
    }

    @Override
    protected TrackingToken getTokenForGapDetection(TrackingToken token) {
        if (token == null) {
            return null;
        }
        Assert.isTrue(token instanceof LegacyTrackingToken, String.format("Token %s is of the wrong type", token));
        LegacyTrackingToken legacyToken = (LegacyTrackingToken) token;
        return new LegacyTrackingToken(legacyToken.getTimestamp(), legacyToken.getAggregateIdentifier(),
                                       legacyToken.getSequenceNumber());
    }

    @Override
    public PreparedStatement readEventData(Connection connection, TrackingToken lastToken) throws SQLException {
        Assert.isTrue(lastToken == null || lastToken instanceof LegacyTrackingToken,
                      String.format("Token [%s] is of the wrong type", lastToken));
        String selectFrom = "SELECT " + trackedEventFields() + " FROM " + schema().domainEventTable();
        String orderBy =
                " ORDER BY " + schema().timestampColumn() + " ASC, " + schema().sequenceNumberColumn() + " ASC, " +
                        schema().aggregateIdentifierColumn() + " ASC";
        if (lastToken == null) {
            return connection.prepareStatement(selectFrom + orderBy);
        } else {
            LegacyTrackingToken lastItem = (LegacyTrackingToken) lastToken;
            String where = " WHERE ((" + schema().timestampColumn() + " > ?) " + "OR (" + schema().timestampColumn() +
                    " = ? AND " + schema().sequenceNumberColumn() + " > ?) " + "OR (" + schema().timestampColumn() +
                    " = ? AND " + schema().sequenceNumberColumn() + " = ? " + "AND " +
                    schema().aggregateIdentifierColumn() + " > ?))";
            PreparedStatement statement = connection.prepareStatement(selectFrom + where + orderBy);
            writeTimestamp(statement, 1, lastItem.getTimestamp());
            writeTimestamp(statement, 2, lastItem.getTimestamp());
            statement.setLong(3, lastItem.getSequenceNumber());
            writeTimestamp(statement, 4, lastItem.getTimestamp());
            statement.setLong(5, lastItem.getSequenceNumber());
            statement.setString(6, lastItem.getAggregateIdentifier());
            return statement;
        }
    }

    @Override
    public TrackedEventData<?> getTrackedEventData(ResultSet resultSet) throws SQLException {
        return new GenericLegacyDomainEventEntry<>(resultSet.getString(schema().typeColumn()),
                                                   resultSet.getString(schema().aggregateIdentifierColumn()),
                                                   resultSet.getLong(schema().sequenceNumberColumn()),
                                                   resultSet.getString(schema().eventIdentifierColumn()),
                                                   readTimeStamp(resultSet, schema().timestampColumn()),
                                                   resultSet.getString(schema().payloadTypeColumn()),
                                                   resultSet.getString(schema().payloadRevisionColumn()),
                                                   readPayload(resultSet, schema().payloadColumn()),
                                                   readPayload(resultSet, schema().metaDataColumn()));
    }

    @Override
    protected Object readTimeStamp(ResultSet resultSet, String columnName) throws SQLException {
        return resultSet.getString(columnName);
    }

    @Override
    protected void writeTimestamp(PreparedStatement preparedStatement, int position,
                                  TemporalAccessor input) throws SQLException {
        preparedStatement.setString(position, Instant.from(input).toString());
    }

    @Override
    protected String trackedEventFields() {
        return domainEventFields();
    }
}


text:
package nom.bdezonia.zorbage.algebra;

/**
 *
 * @author Barry DeZonia
 *
 */
public interface OrderedIntegralDomain<T extends OrderedIntegralDomain<T,U,V>, U, V>
	extends
		IntegralDomain<T,U>,
		Ordered<U>,
		AbsoluteValue<U,V>
{
}


text:
<?php
namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * Site controller
 */
class SiteController extends Controller {
    /**
     * @inheritdoc
     */

    public function actions(){
    }

    public function actionIndex(){
        $this->layout = 'home';
        return $this->render('home');
    }

    public function actionLogin(){
        if (!\Yii::$app->user->isGuest) return $this->redirect(['user/profile']);
        $loginModel = new LoginForm(['scenario' => 'login']);
        $registerModel = new \common\models\User(['scenario' => 'register']);
        if ($loginModel->load(Yii::$app->request->post()) && $loginModel->login()) {
            Yii::$app->session->setFlash('msg', Yii::t('app/message','msg welcome back'));
            return $this->goBack();
        }
        else if($registerModel->load(Yii::$app->request->post()) && $registerModel->Register()) {
            Yii::$app->session->setFlash('msg', Yii::t('app/message','msg thanks for registration please login your email and password'));
            return $this->redirect(['site/login']);
        }

        $this->layout = 'login-register';
        return $this->render('login-register', [
            'loginModel' => $loginModel,
            'registerModel' => $registerModel,
        ]);
    }

    public function actionForgot_password(){
        if (!\Yii::$app->user->isGuest) return $this->goHome();
        $model = new LoginForm(['scenario' => 'forgot_password']);
        if ($model->load(Yii::$app->request->post()) && $model->forgotPassword()) {
            Yii::$app->session->setFlash('msg', Yii::t('app/message','msg password has been send to email please check inbox/spam'));
            return $this->redirect(Yii::$app->request->referrer);
        }
        $this->layout = 'login-register';
        return $this->render('forgot_password', [
            'model' => $model
        ]);
    }

    public function actionResetpassword($id=''){
        $query = \common\models\User::findOne(['auth_key' => $id,'auth_key_expired' => date('Y-m-d')]);
        if(!$query){
            Yii::$app->session->setFlash('msg', Yii::t('app/message','msg token reset password not valid'));
            return $this->redirect(['site/forgot_password']);
        }

        $this->layout = 'login-register';
        $model = new LoginForm(['scenario' => 'reset_password']);

        if ($model->load(Yii::$app->request->post()) && $model->resetPassword($id)) {
            Yii::$app->session->setFlash('msg', Yii::t('app/message','msg reset password has been send to email please check inbox/spam'));
            return $this->redirect(['site/login']);
        }

        return $this->render('reset_password', [
            'model' => $model,
            'query' => $query,
        ]);
    }

    public function actionLogout(){
        Yii::$app->user->logout();
        return $this->redirect(['site/index']);
    }

    public function actionRequestPasswordReset(){
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    public function actionTest(){
        Yii::$app->mail->send(['hendarsyahss@gmail.com'],'Invoice Vileo.co.id','invoice',[
            'data' => \common\models\Order::find()
                        ->select(['order.invoice_no','courier.name as courier_name','order.grand_total',
                                  'order.receiver','order.receiver_contact','order.address','order.town',
                                  'order.city','order.town','order.shipping_cost'])
                        ->joinWith('courier')
                        ->where(['order.id'=>21])
                        ->one(),
            'product' => \common\models\OrderProduct::find()
                        ->select(['product_id','product.sku','product.image as product_image','product.name as product_name','qty','product_price',
                                  'subtotal','product_weight'])
                        ->joinWith('product')
                        ->where(['order_id' => 21])
                        ->all(),
        ]);
    }

    public function actionNewsletter(){
        $formModel = new \common\models\Newsletter();
        if ($formModel->load(Yii::$app->request->post()) && $formModel->getSave()) {
            $formModel->refresh();
            Yii::$app->response->format = 'json';
            //set email
            return ['success' => true,'message' => Yii::t('app/message','msg thanks your email has been registered')];
        }
        else {
            Yii::$app->response->format = 'json';
            return ['success' => false,'message' => Yii::t('app/message','msg your email has been available registered')];
        }
    }

    public function actionError(){
        $this->layout = '404';
        return $this->render('error', [
        ]);
    }

    public function actionPage($id=1){
        $model = \common\models\Page::findOne($id);
        if(!$model) return $this->redirect(['site/error']);
        $this->layout = 'page';
        return $this->render('page',[
            'page' => $model
        ]);
    }

}


text:
package org.springframework.samples.jpetstore.service;

import org.springframework.remoting.jaxrpc.ServletEndpointSupport;
import org.springframework.samples.jpetstore.domain.Order;
import org.springframework.samples.jpetstore.domain.logic.OrderService;

/**
 * JAX-RPC OrderService endpoint that simply delegates to the OrderService
 * implementation in the root web application context. Implements the plain
 * OrderService interface as service interface, just like the target bean does.
 *
 *
This proxy class is necessary because JAX-RPC/Axis requires a dedicated
 * endpoint class to instantiate. If an existing service needs to be exported,
 * a wrapper that extends ServletEndpointSupport for simple application context
 * access is the simplest JAX-RPC compliant way.
 *
 *
This is the class registered with the server-side JAX-RPC implementation.
 * In the case of Axis, this happens in "server-config.wsdd" respectively via
 * deployment calls. The Web Service tool manages the lifecycle of instances
 * of this class: A Spring application context can just be accessed here.
 *
 *
Note that this class does not implement an RMI port interface,
 * despite the JAX-RPC spec requiring this for service endpoints. Axis and
 * other JAX-RPC implementations are known to accept non-RMI endpoint classes
 * too, so there's no need to maintain an RMI port interface in addition to
 * the existing non-RMI service interface (OrderService).
 *
 *
If your JAX-RPC implementation imposes a strict requirement on a service
 * endpoint class to implement an RMI port interface, then let your endpoint
 * class implement both the non-RMI service interface and the RMI port interface.
 * This will work as long as the methods in both interfaces just differ in the
 * declared RemoteException. Of course, this unfortunately involves double
 * maintenance: one interface for your business logic, one for JAX-RPC.
 * Therefore, it is usually preferable to avoid this if not absolutely necessary.
 *
 * @author Juergen Hoeller
 * @since 26.12.2003
 */
public class JaxRpcOrderService extends ServletEndpointSupport implements OrderService {

	private OrderService orderService;

	protected void onInit() {
		this.orderService = (OrderService) getWebApplicationContext().getBean("petStore");
	}

	public Order getOrder(int orderId) {
		return this.orderService.getOrder(orderId);
	}

}


text:
import os
from src.core import prep
from src.core import sg
from src.core import seqfs
from sgscanner import *

def SgEval(opts):
    str_nm = os.path.basename(opts.tdir)
    str_path_mdl = opts.sfunc
    str_proj = 'aux'
    str_path_proj = os.path.join(opts.tdir, str_proj)
    str_path_sg = None
    if not os.path.exists(str_path_proj):
        os.makedirs(str_path_proj)

    if  opts.sg is None:
        dict_drct = {'two-sided': 'b', 'pos': 'f', 'neg': 'r'}
        str_path_sgfq = os.path.join(str_path_proj, str_nm + '.sgfq')
        gn_sg = ExtractSg(opts.ref, opts.chrom, opts.beg, opts.end, dict_drct[opts.drct])
        FaToFq(gn_sg, str_path_sgfq)

        str_path_sgpsam = os.path.join(str_path_proj, str_nm + '.sgpsam')
        str_path_sgsam = os.path.join(str_path_proj, str_nm + '.sgsam')
        str_path_sg = os.path.join(opts.tdir, str_nm + '.sg')
        print('Mapping sgRNA seq to ref genome with Bwa...')
        prep.CallBWA(str_path_sgfq, '', opts.ref, str_path_sgpsam, False, opts.thrd)
        prep.FilterSam(str_path_sgpsam, str_path_sgsam, False)
        print('Done')
        print('Processing sgsam...')
        sg.OrganizeSgsam(str_path_sgsam, str_path_sg)
        print('Done')
    else:
        str_path_sg = opts.sg

    str_path_seq = os.path.join(str_path_proj, str_nm + '.seq')
    str_path_st = os.path.join(opts.tdir, str_nm + '.st')
    print('sgRNA Evaluating...')
    seqfs.FeatureEval(str_path_sg, str_path_mdl, opts.ref,
                      str_path_seq, str_path_st)
    print('Done')


text:
title: Docker y un sandbox Node.js
speakers: Aldo Vizcaino
categories: talks
date: 2014-12-12 18:30
repository: docker_node
video: https://www.youtube.com/watch?v=pWDfZMN7xWU&feature=autoshare
---


text:
layout: page
title: About
---

todo: Write something clever and witty about myself.


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.test.bpmn.iomapping;

import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.delegate.JavaDelegate;

/**
 * @author Thorben Lindhauer
 *
 */
public class VariableLogDelegate implements JavaDelegate, ExecutionListener {

  public static Map<String, Object> LOCAL_VARIABLES= new HashMap<String, Object>();

  public void execute(DelegateExecution execution) throws Exception {
    LOCAL_VARIABLES = execution.getVariablesLocal();
  }

  public static void reset() {
    LOCAL_VARIABLES = new HashMap<String, Object>();
  }

  public void notify(DelegateExecution execution) throws Exception {
    LOCAL_VARIABLES = execution.getVariablesLocal();
  }

}


text:
require 'simple-spreadsheet-extractor'

class DataFilesController < ApplicationController

  include IndexPager
  include SysMODB::SpreadsheetExtractor
  include MimeTypesHelper
  include DotGenerator

  include Seek::AssetsCommon

  before_filter :find_assets, :only => [ :index ]
  before_filter :find_and_authorize_requested_item, :except => [ :index, :new, :upload_for_tool, :upload_from_email, :create, :request_resource, :preview, :test_asset_url, :update_annotations_ajax]
  before_filter :find_display_asset, :only=>[:show,:explore,:download,:matching_models]
  skip_before_filter :verify_authenticity_token, :only => [:upload_for_tool, :upload_from_email]
  before_filter :xml_login_only, :only => [:upload_for_tool,:upload_from_email]

  #has to come after the other filters
  include Seek::Publishing::PublishingCommon

  include Seek::BreadCrumbs

  include Seek::DataciteDoi

  def convert_to_presentation
    @data_file = DataFile.find params[:id]
    @presentation = @data_file.to_presentation

    respond_to do |format|

      if !@presentation.new_record?
        disable_authorization_checks do
          # first reload all associations which are already assigned to the presentation. Otherwise, all associations will be destroyed when data file is destroyed
          @data_file.reload
          @data_file.destroy
        end

        ActivityLog.create :action=>"create",:culprit=>User.current_user,:activity_loggable=>@presentation,:controller_name=>controller_name.downcase
        flash[:notice]="#{t('data_file')} '#{@presentation.title}' is successfully converted to #{t('presentation')}"
        format.html { redirect_to presentation_path(@presentation) }
      else
        flash[:error] = "#{t('data_file')} failed to convert to #{t('presentation')}!!"
        format.html {
          redirect_to data_file_path @data_file
        }
      end
    end
  end

  def plot
    sheet = params[:sheet] || 2
    @csv_data = spreadsheet_to_csv(open(@data_file.content_blob.filepath),sheet,true)
    respond_to do |format|
      format.html
    end
  end

  def new_version
    if handle_upload_data
      comments=params[:revision_comment]

      respond_to do |format|
        if @data_file.save_as_new_version(comments)
          create_content_blobs
          #Duplicate studied factors
          factors = @data_file.find_version(@data_file.version-1).studied_factors
          factors.each do |f|
            new_f = f.dup
            new_f.data_file_version = @data_file.version
            new_f.save
          end
          flash[:notice] = "New version uploaded - now on version #{@data_file.version}"
          if @data_file.is_with_sample?
            bio_samples = @data_file.bio_samples_population @data_file.samples.first.institution_id if @data_file.samples.first
            if bio_samples && !bio_samples.errors.blank?
              flash[:notice] << "
 However, Sample database population failed."
              flash[:error] = bio_samples.errors.html_safe
            end
          end
        else
          flash[:error] = "Unable to save new version"
        end
        format.html {redirect_to @data_file }
      end
    else
      flash[:error]=flash.now[:error]
      redirect_to @data_file
    end
  end

  def new
    @data_file = DataFile.new
    @data_file.parent_name = params[:parent_name]
    @data_file.is_with_sample= params[:is_with_sample]
    @page_title = params[:page_title]
    respond_to do |format|
      if User.logged_in_and_member?
        format.html # new.html.erb
      else
        flash[:error] = "You are not authorized to upload new Data files. Only members of known projects, institutions or work groups are allowed to create new content."
        format.html { redirect_to data_files_path }
      end
    end
  end

  def upload_for_tool

    if handle_upload_data
      params[:data_file][:project_ids] = [params[:data_file].delete(:project_id)] if params[:data_file][:project_id]
      @data_file = DataFile.new params[:data_file]

      @data_file.policy = Policy.new_for_upload_tool(@data_file, params[:recipient_id])

      if @data_file.save
        @data_file.creators = [current_user.person]
        create_content_blobs
        #send email to the file uploader and receiver
        Mailer.file_uploaded(current_user,Person.find(params[:recipient_id]),@data_file,base_host).deliver

        flash.now[:notice] ="#{t('data_file')} was successfully uploaded and saved." if flash.now[:notice].nil?
        render :text => flash.now[:notice]
      else
        errors = (@data_file.errors.map { |e| e.join(" ") }.join("\n"))
        render :text => errors, :status => 500
      end
    end
  end

  def upload_from_email
    if current_user.is_admin? && Seek::Config.admin_impersonation_enabled
      User.with_current_user Person.find(params[:sender_id]).user do
        if handle_upload_data
          @data_file = DataFile.new params[:data_file]

          @data_file.policy = Policy.new_from_email(@data_file, params[:recipient_ids], params[:cc_ids])

          if @data_file.save
            @data_file.creators = [User.current_user.person]
            create_content_blobs

            flash.now[:notice] ="#{t('data_file')} was successfully uploaded and saved." if flash.now[:notice].nil?
            render :text => flash.now[:notice]
          else
            errors = (@data_file.errors.map { |e| e.join(" ") }.join("\n"))
            render :text => errors, :status => 500
          end
        end
      end
    else
      render :text => "This user is not permitted to act on behalf of other users", :status => :forbidden
    end
  end

  def create
    if handle_upload_data

      @data_file = DataFile.new params[:data_file]

      @data_file.policy.set_attributes_with_sharing params[:sharing], @data_file.projects

      assay_ids = params[:assay_ids] || []

      if @data_file.save
        update_annotations @data_file
        update_scales @data_file

        create_content_blobs

        update_relationships(@data_file,params)

          if !@data_file.parent_name.blank?
          render :partial => "assets/back_to_fancy_parent", :locals => {:child => @data_file, :parent_name => @data_file.parent_name, :is_not_fancy => true}
        else
          respond_to do |format|
            flash[:notice] = "#{t('data_file')} was successfully uploaded and saved." if flash.now[:notice].nil?
            #parse the data file if it is with sample data
            if @data_file.is_with_sample
              bio_samples = @data_file.bio_samples_population params[:institution_id]
              #@bio_samples = bio_samples
              #Rails.logger.warn "BIO SAMPLES ::: " + @bio_samples.treatments_text
              if bio_samples && bio_samples.errors.blank?
                 params[:assay_ids] = Array(params[:assay_ids]) | Array(bio_samples.instance_values["assay"].try(:id).try(:to_s))
              else
                flash[:notice] << "
 However, Sample database population failed."
                flash[:error] = bio_samples.errors.html_safe
              end

            end
            #the assay_id param can also contain the relationship type
            assay_ids, relationship_types = determine_related_assay_ids_and_relationship_types(params)
            update_assay_assets(@data_file,assay_ids,relationship_types)
            format.html { redirect_to data_file_path(@data_file) }
          end
        end
      else
        respond_to do |format|
          format.html {
            render :action => "new"
          }
        end

      end
    else
      handle_upload_data_failure
    end
  end

  def determine_related_assay_ids_and_relationship_types params
    assay_ids = []
    relationship_types = []
    (params[:assay_ids] || []).each do |assay_type_text|
      assay_id, relationship_type = assay_type_text.split(",")
      assay_ids << assay_id
      relationship_types << relationship_type
    end
    return assay_ids, relationship_types
  end

  def show
    # store timestamp of the previous last usage
    @last_used_before_now = @data_file.last_used_at

    @data_file.just_used

    #Rails.logger.warn "template in data_files_controller/show : #{params[:parsing_template]}"

    respond_to do |format|
      format.html #{render :locals => {:template => params[:parsing_template]}}# show.html.erb
      format.xml
      format.rdf { render :template=>'rdf/show'}
      format.json
    end
  end

  def edit

  end

  def update
    # remove protected columns (including a "link" to content blob - actual data cannot be updated!)
    data_file_params=filter_protected_update_params(params[:data_file])

    update_annotations @data_file
    update_scales @data_file

    respond_to do |format|
      @data_file.attributes = data_file_params

      if params[:sharing]
        @data_file.policy_or_default
        @data_file.policy.set_attributes_with_sharing params[:sharing], @data_file.projects
      end

      if @data_file.save

        update_relationships(@data_file,params)

        #the assay_id param can also contain the relationship type
        assay_ids, relationship_types = determine_related_assay_ids_and_relationship_types(params)
        update_assay_assets(@data_file,assay_ids,relationship_types)

        flash[:notice] = "#{t('data_file')} metadata was successfully updated."
        format.html { redirect_to data_file_path(@data_file) }

      else
        format.html {
          render :action => "edit"
        }
      end
    end
  end

  def data
    @data_file =  DataFile.find(params[:id])
    sheet = params[:sheet] || 1
    trim = params[:trim] || false
    content_blob = @data_file.content_blob
    mime_extensions = mime_extensions(content_blob.content_type)
    if !(["xls","xlsx"] & mime_extensions).empty?
      respond_to do |format|
        file = open(content_blob.filepath)
        format.html #currently complains about a missing template, but we don't want people using this for now - its purely XML
        format.xml {render :xml=>spreadsheet_to_xml(file) }
        format.csv {render :text=>spreadsheet_to_csv(file,sheet,trim) }
      end
    else
      respond_to do |format|
        flash[:error] = "Unable to view contents of this data file"
        format.html { redirect_to @data_file,:format=>"html" }
      end
    end
  end

  def explore
    if @display_data_file.contains_extractable_spreadsheet?
      respond_to do |format|
        format.html
      end
    else
     respond_to do |format|
        flash[:error] = "Unable to view contents of this data file"
        format.html { redirect_to data_file_path(@data_file,:version=>@display_data_file.version) }
      end
    end
  end

  def clear_population bio_samples
      specimens = Specimen.find_all_by_title bio_samples.instance_values["specimen_names"].values
      samples = Sample.find_all_by_title bio_samples.instance_values["sample_names"].values
      samples.each do |s|
        s.assays.clear
        s.destroy
      end
      specimens.each &:destroy
  end

  def matching_models
    #FIXME: should use the correct version
    @matching_model_items = @data_file.matching_models
    #filter authorization
    ids = @matching_model_items.collect &:primary_key
    models = Model.find_all_by_id(ids)
    authorised_ids = Model.authorize_asset_collection(models,"view").collect &:id
    @matching_model_items = @matching_model_items.select{|mdf| authorised_ids.include?(mdf.primary_key.to_i)}

    flash.now[:notice]="#{@matching_model_items.count} #{t('model').pluralize}  were found that may be relevant to this #{t('data_file')} "
    respond_to do |format|
      format.html
    end
  end

  protected

  def translate_action action
    action="download" if action=="data"
    action="view" if ["matching_models"].include?(action)
    super action
  end

  def xml_login_only
    unless session[:xml_login]
      flash[:error] = "Only available when logged in via xml"
      redirect_to root_url
    end
  end

end


text: CREATE TABLE stocks (trans text, symbol text, qty int, price real)


text:
package org.apache.nifi.lookup.script;

import org.apache.nifi.annotation.behavior.DynamicProperty;
import org.apache.nifi.annotation.behavior.Restricted;
import org.apache.nifi.annotation.behavior.Restriction;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.RequiredPermission;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.lookup.LookupFailureException;
import org.apache.nifi.lookup.LookupService;

import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * A Controller service that allows the user to script the lookup operation to be performed (by LookupRecord, e.g.)
 */
@Tags({"lookup", "record", "script", "invoke", "groovy", "python", "jython", "jruby", "ruby", "javascript", "js", "lua", "luaj"})
@CapabilityDescription("Allows the user to provide a scripted LookupService instance in order to enrich records from " +
        "an incoming flow file. Please note, that due to a bug in Jython that remains unresolved, it is not possible to use " +
        "Jython to write a script for this service in Python.")
@DynamicProperty(name = "Script Engine Binding property", value = "Binding property value passed to Script Runner",
        expressionLanguageScope = ExpressionLanguageScope.VARIABLE_REGISTRY,
        description = "Updates a script engine property specified by the Dynamic Property's key with the value specified by the Dynamic Property's value")
@Restricted(
        restrictions = {
                @Restriction(
                        requiredPermission = RequiredPermission.EXECUTE_CODE,
                        explanation = "Provides operator the ability to execute arbitrary code assuming all permissions that NiFi has.")
        }
)
public class ScriptedLookupService extends BaseScriptedLookupService implements LookupService<Object> {

    @Override
    @SuppressWarnings("unchecked")
    public Set<String> getRequiredKeys() {
        return lookupService.get().getRequiredKeys();
    }

    @Override
    public Class<?> getValueType() {
        // Delegate the getValueType() call to the scripted LookupService
        return lookupService.get().getValueType();
    }

    @Override
    @SuppressWarnings("unchecked")
    public Optional<Object> lookup(Map<String, Object> coordinates) throws LookupFailureException {
        // Delegate the lookup() call to the scripted LookupService
        return lookupService.get().lookup(coordinates);
    }
}


text:
package com.jwm.ir.index.workers;

import com.jwm.ir.index.service.Service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

class DatabaseStatsUpdateWorker implements Runnable {

	final private static Logger log = LogManager.getLogger(DatabaseStatsUpdateWorker.class);
	private Service service;
	public DatabaseStatsUpdateWorker(Service service) {
		this.service = service;
	}

	@Override
	public void run() {

		log.info("Beginning to run database summarizer");
		service.updateSummaries();
		log.info("Finished running database summarizer");
	}

}


text:
.class Lcom/android/server/AlarmManagerService$PriorityClass;
.super Ljava/lang/Object;
.source "AlarmManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/AlarmManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "PriorityClass"
.end annotation

# instance fields
.field priority:I

.field seq:I

.field final synthetic this$0:Lcom/android/server/AlarmManagerService;

# direct methods
.method constructor <init>(Lcom/android/server/AlarmManagerService;)V
    .locals 1

    .prologue
    .line 195
    iput-object p1, p0, Lcom/android/server/AlarmManagerService$PriorityClass;->this$0:Lcom/android/server/AlarmManagerService;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 196
    iget v0, p1, Lcom/android/server/AlarmManagerService;->mCurrentSeq:I

    add-int/lit8 v0, v0, -0x1

    iput v0, p0, Lcom/android/server/AlarmManagerService$PriorityClass;->seq:I

    .line 197
    const/4 v0, 0x2

    iput v0, p0, Lcom/android/server/AlarmManagerService$PriorityClass;->priority:I

    .line 198
    return-void
.end method