I've tried this on different links and it would work but specifically on this link it won't work:
ticker = 'SBUX'
url = urlfetch.fetch('http://stockcharts.com/h-sc/ui?s=' + ticker +
'&p=D&yr=1&mn=0&dy=0&id=p97813671848')
# Parses the HTML
tree = etree.HTML(url.content)
# Converts the DOM into a string
result = etree.tostring(tree, pretty_print=True, method="html")
self.response.out.write(result)
I don't know why it cannot fetch the stockcharts link?
Could it be that stockcharts blocks google?
Weird. Seems to work with urllib though ...
ticker = 'SBUX'
uri = 'http://stockcharts.com/h-sc/ui?s=' + ticker + '&p=D&yr=1&mn=0&dy=0&id=p97813671848'
response = urllib2.urlopen(uri)
html = response.read()
Related
I have list of images = list of byte arrays like below :
List<byte[]> imageBytesList = new List<byte[]>();
for (int pageId = 0; pageId < documentPageNumber; pageId++)
{
string preprossed_path = System.IO.Directory.GetParent(document.Path) + "\\" + documentId + "_" + pageId.ToString() + "_preprocessed.tif";
if (File.Exists(preprossed_path))
{
var imageBytes = File.ReadAllBytes(preprossed_path);
imageBytesList.Add(imageBytes);
}
}
And I want to send these list of images with json data to a http server.but I am not sure how can I put this list of byte[] to my json object. Normally, when I had one image, I would go like this:
var imageBytesStr = Convert.ToBase64String(imageBytes);
dict.Add("base64encoded", imageBytesStr);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dict,Newtonsoft.Json.Formatting.Indented);
I couldn't directly convert from imageBytesList to base64 string so that I can put json dictionary. What am I missing here ?
I am a beginner in Angular and Rest and I have a problem. I have a form in Django template and I want to pass data with Angular, receive it with Rest and process it. Angular knows to pass (post) the data by url to:
url(r'^api/nowyPacjent/$', CreateNewPatient.as_view(), name="api_tempPatient"),
The CreateNewPatient class looks like this:
class CreateNewPatient(generics.ListCreateAPIView):
model = TempPatient
queryset = TempPatient.objects.all()
serializer_class = CreateNewPatientSerializer
and the serializer looks like this:
class CreateNewPatientSerializer(serializers.Serializer):
name = serializers.CharField(max_length=30)
surname = serializers.CharField(max_length=70)
phone = serializers.CharField(max_length=15, required=False)
age = serializers.IntegerField(max_value=99, min_value=1, required=False)
company = serializers.PrimaryKeyRelatedField(many=False, queryset=Company.objects.all())
therapyStart = serializers.DateField(required=False)
def create(self, validated_data):
if 'therapyStart' in validated_data:
therapy_start = validated_data['therapyStart']
else:
therapy_start = datetime.date.today()
if 'age' in validated_data:
patient_age = validated_data['age']
else:
patient_age = 1;
if 'phone' in validated_data:
patient_phone = validated_data['phone']
else:
patient_phone = ''
newTempPatient = TempPatient(
name = validated_data['name'],
surname = validated_data['surname'],
company = validated_data['company'],
therapyStart = therapy_start,
age = patient_age,
phone = patient_phone
)
newTempPatient.save()
newPatient = Patient(
name=validated_data['name'],
surname=validated_data['surname'],
phone=patient_phone,
age=patient_age
)
newPatient.save()
user=None
request = self.context.get('request')
if request and hasattr(request,"user"):
user=request.user
newTherapyGroup = TherapyGroup.objects.create(
start = therapy_start,
patient = newPatient,
therapist = Therapist.objects.get(user = user),
company = validated_data['company']
)
newTherapyGroup.save()
return newTempPatient
Everything is fine - after submitting the template form the patient is created - until the code tries to get logged user from the request (just after the last if statement of the serializer). Then I receive the 'AnonymousUser' error and cannot create final model instance. I've tried to pass the data to the Django views and then use the Rest's serializer. However, the error occurred again. I've searched for the answer but nothing was helpful. Please, notice that I don't want to authenticate the logged user but to get data about him.
I think the problem is that Angular somehow loose information about CSRF token and log session and that is the reason of both errors (that is only my assumption).
Below is how Angular config looks like. NewPatientCtrl is responsible for mentioned form and model is one of the form element (and it works fine).
angular.module('pacjent', ['ngMessages', 'ui.bootstrap', 'datetime'])
.constant('companyListApi','http://localhost:8000/finanse/api/list/')
.constant('tempPatientApi','http://localhost:8000/pacjent/api/nowyPacjent/')
.factory('ModelUtils', ModelUtils)
.factory('newPatientFormApi',newPatientFormApi )
.factory('companyApi', companyApi)
.factory('mySharedService', mySharedService)
.controller('PacjentCtrl', PacjentCtrl)
.controller('NewPatientCtrl', NewPatientCtrl)
.controller('ModalInstanceCtrl', ModalInstanceCtrl)
.config(function($interpolateProvider, $httpProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
})
The interesting thing is that this code works perfect on my colleague's system (Windows 7, Chrome) - the user data is gathered perfectly. However, I've tested it on three different systems (Windows 7 x64, Xubuntu 14.04, Ubuntu 14) and several browsers (Firefox, Chromium) on my PCs and the same error occurs.
Thank you a lot for any comments and advice. Sorry also for any non-professional statements.
it is because of this line:
user=request.user
# ...
therapist = Therapist.objects.get(user = user),
you are trying to get a therapist from your database with an Anynomous user in your ORM - it means a user who is not logged in.
you need is_authenticated() in your check:
if request and hasattr(request,"user") and request.user.is_authenticated():
user=request.user
newTherapyGroup = TherapyGroup.objects.create(
start = therapy_start,
patient = newPatient,
therapist = Therapist.objects.get(user=user),
company = validated_data['company']
)
newTherapyGroup.save()
To get an event from an Exchange calendar by ICalUId, you can use the FindItem-operation, using the UId base64-encoded as value to the Extended property identified by
DistinguishedPropertySetId=Meeting, PropertyId=3 and PropertyType=Binary.
This works great for events that are created in the Exchange calendar, where ICalUIds look like the following: 040000008200E00074C5B7101A82E00800000000A7C552582821D1010000000000000000100000002550ED442EB2CF4287FD94D10A4F331D
However, this does not work when trying to get the event with a Google Calendar UId, which looks like the following:
tp90m1srk847n1oa4jtp9ofou0#google.com
Not even using the substring before #google.com works, sadly.
Is there a way to get Google Events in the Exchange Calendar with EWS?
The GlobalObjectId is generated from the UID in this case using the formula defined in https://msdn.microsoft.com/en-us/library/ee157690(v=exchg.80).aspx . So if all you have is the UID you will need to generate the GlobalObjectId to search using your own algorithm. eg
String UId = "k5abv4oduaidu8knel4088iq8c#google.com";
String Header = "040000008200E00074C5B7101A82E008";
String Padding = "0000000000000000000000000000000000000000";
String Prefix = "7643616C2D55696401000000";
String DataString = Prefix + BitConverter.ToString(ASCIIEncoding.ASCII.GetBytes(UId)).Replace("-", "") + "00";
String BigEndianlength = (DataString.Length / 2).ToString("X8");
String LittleEndianlength = BigEndianlength.Substring(6, 2) + BigEndianlength.Substring(4, 2) + BigEndianlength.Substring(2, 2) + BigEndianlength.Substring(0, 2);
String GlobalUidHex = Header + Padding + LittleEndianlength + DataString;
If you then conver the HexString to Base64 String that should work.
Cheers
glen
I have created an array which is being used to store a series of .gif images and I'm just trying to test everything out by using document.getElementById to change the .src value but when I change it and load the page the image stays the same as it was before.
function setImage()
{
var images = new Array();
images[0] = anemone.gif;
images[1] = ball.gif;
images[2] = crab.gif;
images[3] = fish2.gif;
images[4] = gull.gif;
images[5] = jellyfish.gif;
images[6] = moon.gif;
images[7] = sail.gif;
images[8] = shell.gif;
images[9] = snail.gif;
images[10] = sun.gif;
images[11] = sunnies.gif;
images[12] = whale.gif;
var slots = new Array();
slots[0] = document.getElementById("slot" + 0);
slots[1] = document.getElementById("slot" + 1);
slots[2] = document.getElementById("slot" + 2);
slots[0].src = "snail.gif";
document.getElementById('slot0').src = images[0];
alert(images.length);
}
I can't understand why the image wont change, but I know it has to be something very simple. I've been wasting hours trying to get this one thing to change but nothing works. can anyone please point out the error of my ways?
There are a couple of issues with your code:
Your filenames need to be Strings, so they'll have to be quoted (also you can simplify the Array creation):
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];
Also make sure you are getting your slot-elements right, quote all the attributes like:
<img id="slot0" class="slot" src="crab.gif" width="120" height="80">
When you create the slots-Array you can do it like this (no need to concat the ID string):
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
Finally make sure you call your function when the document has loaded / the DOM is ready. If you don't want to use a framework like jQuery your easiest bet is probably still using window.onload:
window.onload = setImage; //note that the parens are missing as you want to refer to the function instead of executing it
Further reading on Arrays, window.onload and DOMReady:
https://developer.mozilla.org/de/docs/DOM/window.onload
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
javascript domready?
Well, i have this code that is supposed to check if the html is changed by first checking and downloading the html into a string, then checking again every two seconds and printing html if it has changed. The problem is that the script says it has changed all the time, and keeps giving me the same html code back.
#!/usr/bin/env python
import time
start = time.time()
from urllib.request import urlopen
data = str
html = str
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
html = data
def secondcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
if not html == data:
print(data)
while True:
secondcheck()
time.sleep(2)
print ("it took", time.time() - start, "seconds.")
Thanks in advance;)
You need to tell the interpreter to set the global html variable in the firstcheck() function.
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
global html
html = data
Right now the secondcheck() function is checking against the html value "str".
It doesn't look like you are calling firstcheck at all, so html is always going to be str. You could make it work by replacing the block inside the while True with:
while True:
firstcheck()
secondcheck()
but it would be cleaner to have a script that looked something like this
while True:
hogniergay = urlopen(url)
result = hogniergay.read()
hogniergay.close()
if result != current:
print (result)
current = result
time.sleep(2)