get random password with puppet function - ruby

I have a function that allow me to generate random password. My function is working well without a puppetmaster. When I tried with a master an error appear when I called the function :
Error 400 on SERVER: bad value for range
Here is my function:
module Puppet::Parser::Functions
newfunction(:get_random_password, :type => :rvalue, :doc => <<-EOS
Returns a random password.
EOS
) do |args|
raise(Puppet::ParseError, "get_random_password(): Wrong number of arguments " +
"given (#{args.size} for 1)") if args.size != 1
specials = ((33..33).to_a + (35..38).to_a + (40..47).to_a + (58..64).to_a + (91..93).to_a + (95..96).to_a + (123..125).to_a).pack('U*').chars.to_a
numbers = (0..9).to_a
alphal = ('a'..'z').to_a
alphau = ('A'..'Z').to_a
length = args[0]
CHARS = (alphal + specials + numbers + alphau)
pwd = CHARS.sort_by { rand }.join[0...length]
return pwd
end
end
The function is called in both case with $pwd = get_random_password(10).
When I specified the length directly in the function to 10 for example. The password is well generated in master mode.
Have you any idea why I can't specify the length value?

It's unclear why this works for puppet apply (if that's what you're insinuating), but the error is most likely a typing issue.
Try
length = args[0].to_i

To my Knowledge,For situations like this I use the puppet generate() function to create the random password and store it in a persistent data store on the master.
For instance,an SQLITE database or something. This way, the password is generated randomly if it does not exist and the same password is used if it does already exist.
It's important to have the resource always be managed, that way if the password is changed on the managed node Puppet will realize this, change it to the value you're managing, and report that it did so.

Related

How to create a Roblox game where the player has to guess a randomly generated pin?

So, I've been working on this for the past week. I have tried everything (based on the knowledge I know) and yet nothing... my code didn't work the first time, the second time, the third time... the forth... etc... at the end, I let frustration take control of me and I ended up deleting the whole script. Luckily not the parts and models, otherwise I'm really screwed...
I need to create a game in which I have to create a keypad of sorts, at first I thought GUI would work... no, it needs to be SurfaceGUI, which I don't know how to handle well... Anyway, I needed to create a keypad using SurfaceGUI, and display it on a separate screen, as a typical keypad would...
The Player would first have to enter an "initial" number, meaning in order to enter the randomly generated number he first needed to input the static pin in order to "log in," after that, then he would try to guess the number...
I've literally tried everything I could but nothing... It's mainly because of my lack of experience in LUA, I'm more advanced in Python and barely know a thing in Java... If someone could assist me on how to do this, I would appreciate it greatly
First, download this and put it in a ScreenGui in StarterGui. Then, use the following LocalScript placed inside the PIN frame:
-- Script settings
local len = 4 -- replace this as needed...
local regen = false -- determines whether PIN will regenerate after a failed attempt
local regmes = "Enter PIN..." -- start message of PIN pad
local badmes = "Wrong PIN!" -- message displayed when PIN is wrong
local success = "Correct PIN!" -- message displayed when PIN is right
-- Script workings
local pin = script.Parent
local top = pin.Top
local txt = top.Numbers
local nums = top.NumKeys
local pin
local stpin
local nms
txt.Text = regmes
local see = game:GetStorage("ReplicatedStorage").PINActivate
local function activate()
if pin.Visible then
pin.Visible = false
for _, btn in pairs(nums:GetChildren()) do
btn.Active = false
end
return
else
pin.Visible = true
for _, btn in pairs(nums:GetChildren()) do
btn.Active = true
end
return
end
end
local function rand()
math.randomseed(os.time) -- better random numbers this way
return tostring(math.floor(math.random(0,9.9)))
end
local function gen()
nms = {rand()}
for i=2, len, 1 do
nms[#nms+1]=rand()
end
stpin = nms[1]
for i=2, #nms, 1 do
stpin = stpin..nms[i]
end
pin = tonumber(stpin) -- converts the number string into an actual number
end
gen()
local function activate(str)
if tonumber(str) ~= pin then
txt.Text = badmes
wait(2)
txt.Text = regmes
if regen then
gen()
wait(0.1)
end
return
else
txt.Text = success
wait(2)
activate()
-- insert code here...
end
end
for _, btn in pairs(nums:GetChildren()) do
btn.Activated:Connect(function()
if txt.Text == "Wrong PIN!" then return end
txt.Text = txt.Text..btn.Text
if string.len(txt.Text) >= len then
activate(txt.Text)
end
wait(0.1)
end)
end
see.OnClientEvent:Connect(activate)
And in a Script put this:
local Players = game:GetService("Players")
local see = game:GetService("ReplicatedStorage").PINActivate
local plr
-- replace Event with something like Part.Touched
Event:Connect(function(part)
if part.Parent.Head then
plr = Players:GetPlayerFromCharacter(part.Parent)
see:FireClient(plr)
end
end)
What this will do is bring up a ScreenGui for only that player so they can enter the PIN, and they can close it as well. You can modify as needed; have a great day! :D
There is an easier way, try this
First, Create a GUI in StarterGui, then, Create a textbox and postion it, after that, create a local script inside and type this.
local Password = math.random(1000, 9999)
print(Password)
game.ReplicatedStorage.Password.Value = Password
script.Parent.FocusLost:Connect(function(enter)
if enter then
if script.Parent.Text == tostring(Password) then
print("Correct!")
script.Parent.BorderColor3 = Color3.new(0, 255, 0)
Password = math.random(1000, 9999)
game.ReplicatedStorage.Correct1:FireServer()
print(Password)
game.ReplicatedStorage.Password.Value = Password
else
print("wrong!")
print(script.Parent.Text)
script.Parent.BorderColor3 = Color3.new(255, 0, 0)
end
end
end)
That's all in the textbox.
Or if you want a random username script, create a textlabel, then, create a local script in the textlabel and type in this.
local UserText = script.Parent
local Username = math.random(1,10)
while true do
if Username == 1 then
UserText.Text = "John"
elseif Username == 2 then
UserText.Text = "Thomas"
elseif Username == 3 then
UserText.Text = "Raymond"
elseif Username == 4 then
UserText.Text = "Ray"
elseif Username == 5 then
UserText.Text = "Tom"
elseif Username == 6 then
UserText.Text = "Kai"
elseif Username == 7 then
UserText.Text = "Lloyd"
elseif Username == 8 then
UserText.Text = "Jay"
elseif Username == 9 then
UserText.Text = "User"
else
UserText.Text = "Guest"
end
wait()
end
All of those if statments are checking what username has been chosen. I have made a roblox game like this recently, so I just took all the script from the game.
If you want to check out my game, Click Here

Scan/Match incorrect input error messages

I am trying to count the correct inputs from the user. An input looks like:
m = "<ex=1>test xxxx <ex=1>test xxxxx test <ex=1>"
The tag ex=1 and the word test have to be connected and in this particular order to count as correct. In case of an invalid input, I want to send the user an error message that explains the error.
I tried to do it as written below:
ex_test_size = m.scan(/<ex=1>test/).size # => 2
test_size = m.scan(/test/).size # => 3
ex_size = m.scan(/<ex=1>/).size # => 3
puts "lack of tags(<ex=1>)" if ex_test_size < ex_size
puts "Lack of the word(test)" if ex_test_size < test_size
I believe it can be written in a better way as the way I wrote, I guess, is prone to errors. How can I make sure that all the errors will be found and shown to the user?
You might use negative lookarounds:
#⇒ ["xxx test", "<ex=1>"]
m.scan(/<ex=1>(?!test).{,4}|.{,4}(?<!<ex=1>)test/).map do |msg|
"<ex=1>test expected, #{msg} got"
end.join(', ')
We scan the string for either <ex=1> not followed by test or vice versa. Also, we grab up to 4 characters that violate the rule for the more descriptive message.

web app is sharing the same memory storage [duplicate]

This question already has answers here:
Computing Result on server side but session data not isolated per user
(3 answers)
Closed 8 years ago.
I working in a app that i use to compute user details. But somehow, the values of a user alter that of another user.
Below is a fragment of the code
def Compute_UserScore(self, details, ques_no):
try:
if(HomePage.answer_.strip() == ""):
self.response.write("""<script type = "text/javascript">
alert("Dear User, You can not answer same answer twice.. Take test Again !");
</script>""")
self.redirect('/otherPages/subjectSelect.html')
else:
count = 0
HomePage.ans_no = 0
HomePage.unans_no = 0
HomePage.correct_no = 0
HomePage.wrong_no = 0
HomePage.failed_ques = list()
HomePage.answer_ = HomePage.answer_.strip()
question_1 = HomePage.question_.split(" gcdc_split_format ")
while (count != (ques_no)):
user_answer = str(details[count]).strip().capitalize()
real_answer = str(HomePage.answer_[count]).strip().capitalize()
if (len(str(user_answer).strip()) == 1):
HomePage.ans_no = HomePage.ans_no + 1
if(user_answer.strip() == real_answer.strip()):
HomePage.correct_no = HomePage.correct_no + 1
else:
HomePage.wrong_no = HomePage.wrong_no + 1
HomePage.failed_ques.append(str("No. " + str(int((count + 1))) + " " + str(question_1[count])))
else:
HomePage.unans_no = HomePage.unans_no + 1
count = count + 1
HomePage.answer_ = ""
except:
self.redirect('/')
return " "
and this is how my homepage looks like
class HomePage(webapp2.RequestHandler):
percentage = None
subject_answered = None
username_ = None
email_ = None
super_date = None
answer_ = " "
question_ = " "
failed_ques = list()
wrong_no = 0
correct_no = 0
ans_no = 0
unans_no = 0
The problem is, when a user A, take a test, He sees the result of another user B.
Read about Using instance variable, but still have not figure ouut how to make it work
Solution is simple: Stop setting class variables in web development! :)
Web requests are stateless, it's mean you never know what's happen between requests - between setting class variable and redirect.
Use database to store temporary data with user login/name (or use hashing/random for security) or send values by parameters (hidden or after '?') to other html page.
Using database is better, if you don't want this then send values (hidden in html) over http. Here is one version of solution (without database):
1.Use normal html form and write handler for this form - question page.
2.In handler write get method like this:
def post(self, some_parameters):
...
self.render('homepage.html', {'ans_no': ans_no,\
'uans_no': uans_no ...})
3.homepage.html have to be template for showing results

Cucumber and variables internal to methods called indirectly

Please note: I am new to TDD & cucumber, so the answer may be very easy.
I am creating a basic image editor for a test (the image is just a sequence of letters).
I have written a Cucumber story:
Scenario Outline: edit commands
Given I start the editor
And a 3 x 3 image is created
When I type the command <command>
Then the image should look like <image>
The step
Scenarios: colour single pixel
| command | image |
| L 1 2 C | OOOCOOOOO |
always fails, returning
expected: "OOOCOOOOO"
got: " OOOOOOOO" (using ==) (RSpec::Expectations::ExpectationNotMetError)
This is the step code:
When /^I type the command (.*)$/ do |command|
#editor.exec_cmd(command).should be
end
The function exec_cmd in the program recognizes the command and launches the appropriate action. In this case it will launch the following
def colorize_pixel(x, y, color)
if !#image.nil?
x = x.to_i
y = y.to_i
pos = (y - 1) * #image[:columns] + x
#image[:content].insert(pos, color).slice!(pos - 1)
else
#messenger.puts "There's no image. Create one first!"
end
end
However, this always fails unless I hardcode the values of the two local variables (pos and color) in the function in the program itself.
Why? It doesn's seem I'm doing anything wrong in the program itself: the function does what it's supposed to do and those two variables are only useful locally. So I'd think this is a problem with my use of cucumber. How do I properly test this?
---edit---
def exec_cmd(cmd = nil)
if !cmd.nil?
case cmd.split.first
when "I" then create_image(cmd[1], cmd[2])
when "S" then show_image
when "C" then clear_table
when "L" then colorize_pixel(cmd[1], cmd[2], cmd[3])
else
#messenger.puts "Incorrect command. " + "Commands available: I C L V H F S X."
end
else
#messenger.puts "Please enter a command."
end
end
When /^I type the command (.*)$/ do |command|
#output = #editor.exec_cmd(command)
end
Then /^the image should look like (.)*$/ do |expected_image|
#output.should == expected_image
end
Hope this may help you.
It's not a cucumber issue.
The problem was that, in exec_cmd, split was called only in the "case" clause, not in the "when"s. This meant that, since the command's format was "a 1 2 b", cmd[1] in the "when" would call the second character of the string, a space, not the second value of the array, and the other functions would convert that to_i, returning 0.
I changed exec_cmd like this:
def exec_cmd(cmd = nil)
if !cmd.nil?
cmd = cmd.split
case cmd.first
when "I" then create_image(cmd[1], cmd[2])
[...]
end
which fixed the issue.

FireWatir TextField set : Very Slow

When calling the set method of a text_field in ruby, the text is being entered at a very slow rate in the browser, roughly at 1 character / second.
Environment Information:
Ubuntu 10.10
FireFox 3.6.13
JSSh 0.9
Ruby 1.9.2p136
FireWatir 1.7.1
Kindly advice. Thanks in advance.
It is a known bug: WTR-397
Workaround is to use watir-webdriver or to use value= instead of set. Example:
browser.text_field(how => what).value= "string"
solve slow key type issue on firewatir:
need to edit the file text_field.rb
enter to the folder
#>cd /usr/lib/ruby/gems/1.8/gems/firewatir-1.7.1/lib/firewatir/elements/ make it writeable
#>chmod 777 text_field.rb edit the proc def doKeyPress( value )
put # in front of #o.fireEvent("onKeyDown") and #o.fireEvent("onKeyPress") and #o.fireEvent("onKeyPress")
instead enter fire_key_events
def doKeyPress( value )
begin
max = maxlength
if (max > 0 && value.length > max)
original_value = value
value = original_value[0...max]
element.log " Supplied string is #{suppliedValue.length} chars, which exceeds the max length (#{max}) of the field. Using value: #{value}"
end
rescue
# probably a text area - so it doesnt have a max Length
end
for i in 0..value.length-1
#sleep element.typingspeed # typing speed
c = value[i,1]
#element.log " adding c.chr " + c #.chr.to_s
#o.value = "#{(#o.value.to_s + c)}" #c.chr
fire_key_events #add this
##o.fireEvent("onKeyDown")
##o.fireEvent("onKeyPress")
##o.fireEvent("onKeyUp")
end
now it should work faster

Resources