Coding Blosum62 in the source code - bioinformatics

I am trying to implement protein pairwise sequence alignment using "Global Alignment" algorithm by 'Needleman -Wunsch'.
I am not clear about how to include 'Blosum62 Matrix' in my source code to do the scoring or to fill the two-dimensional matrix?
I have googled and found that most people suggested to use flat file which contains the standard 'Blosum62 Matrix'. Does it mean that I need to read from this flat file and fill my coded "Blosum62 Martrix' ?
Also, the other approach could be is to use some mathematical formula and include it in your programming logic to construct 'Blosum62 Matrix'. But not very sure about this option.
Any ideas or insights are appreciated.
Thanks.

It would help to know what language you're working in so we can help you with the correct terms, but what I did was use a map of maps (or dictionaries if you're using Python).
Here's an example of my code in Groovy, but it's fairly portable to other languages:
def blosum62 = [
Cys:[Cys:9, Ser:-1, Thr:-1, Pro:-3, Ala:0, Gly:-3, Asn:-3, Asp:-3, Glu:-4, Gln:-3, His:-3, Arg:-3, Lys:-3, Met:-1, Ile:-1, Leu:-1, Val:-1, Phe:-2, Tyr:-2, Trp:-2],
Ser:[Cys:-1,Ser:4, Thr:1, Pro:-1, Ala:1, Gly:0, Asn:1, Asp:0, Glu:0, Gln:0, His:-1, Arg:-1, Lys:0, Met:-1, Ile:-2, Leu:-2, Val:-2, Phe:-2, Tyr:-2, Trp:-3],
Thr:[Cys:-1,Ser:1, Thr:4, Pro:1, Ala:-1, Gly:1, Asn:0, Asp:1, Glu:0, Gln:0, His:0, Arg:-1, Lys:0, Met:-1, Ile:-2, Leu:-2, Val:-2, Phe:-2, Tyr:-2, Trp:-3],
Pro:[Cys:-3,Ser:-1, Thr:1, Pro:7, Ala:-1, Gly:-2, Asn:-1, Asp:-1, Glu:-1, Gln:-1, His:-2, Arg:-2, Lys:-1, Met:-2, Ile:-3, Leu:-3, Val:-2, Phe:-4, Tyr:-3, Trp:-4],
Ala:[Cys:0, Ser:1, Thr:-1, Pro:-1, Ala:4, Gly:0, Asn:-1, Asp:-2, Glu:-1, Gln:-1, His:-2, Arg:-1, Lys:-1, Met:-1, Ile:-1, Leu:-1, Val:-2, Phe:-2, Tyr:-2, Trp:-3],
Gly:[Cys:-3,Ser:0, Thr:1, Pro:-2, Ala:0, Gly:6, Asn:-2, Asp:-1, Glu:-2, Gln:-2, His:-2, Arg:-2, Lys:-2, Met:-3, Ile:-4, Leu:-4, Val:0, Phe:-3, Tyr:-3, Trp:-2],
Asn:[Cys:-3,Ser:1, Thr:0, Pro:-2, Ala:-2, Gly:0, Asn:6, Asp:1, Glu:0, Gln:0, His:-1, Arg:0, Lys:0, Met:-2, Ile:-3, Leu:-3, Val:-3, Phe:-3, Tyr:-2, Trp:-4],
Asp:[Cys:-3,Ser:0, Thr:1, Pro:-1, Ala:-2, Gly:-1, Asn:1, Asp:6, Glu:2, Gln:0, His:-1, Arg:-2, Lys:-1, Met:-3, Ile:-3, Leu:-4, Val:-3, Phe:-3, Tyr:-3, Trp:-4],
Glu:[Cys:-4,Ser:0, Thr:0, Pro:-1, Ala:-1, Gly:-2, Asn:0, Asp:2, Glu:5, Gln:2, His:0, Arg:0, Lys:1, Met:-2, Ile:-3, Leu:-3, Val:-3, Phe:-3, Tyr:-2, Trp:-3],
Gln:[Cys:-3,Ser:0, Thr:0, Pro:-1, Ala:-1, Gly:-2, Asn:0, Asp:0, Glu:2, Gln:5, His:0, Arg:1, Lys:1, Met:0, Ile:-3, Leu:-2, Val:-2, Phe:-3, Tyr:-1, Trp:-2],
His:[Cys:-3,Ser:-1, Thr:0, Pro:-2, Ala:-2, Gly:-2, Asn:1, Asp:1, Glu:0, Gln:0, His:8, Arg:0, Lys:-1, Met:-2, Ile:-3, Leu:-3, Val:-2, Phe:-1, Tyr:2, Trp:-2],
Arg:[Cys:-3,Ser:-1, Thr:-1, Pro:-2, Ala:-1, Gly:-2, Asn:0, Asp:-2, Glu:0, Gln:1, His:0, Arg:5, Lys:2, Met:-1, Ile:-3, Leu:-2, Val:-3, Phe:-3, Tyr:-2, Trp:-3],
Lys:[Cys:-3,Ser:0, Thr:0, Pro:-1, Ala:-1, Gly:-2, Asn:0, Asp:-1, Glu:1, Gln:1, His:-1, Arg:2, Lys:5, Met:-1, Ile:-3, Leu:-2, Val:-3, Phe:-3, Tyr:-2, Trp:-3],
Met:[Cys:-1,Ser:-1, Thr:-1, Pro:-2, Ala:-1, Gly:-3, Asn:-2, Asp:-3, Glu:-2, Gln:0, His:-2, Arg:-1, Lys:-1, Met:5, Ile:1, Leu:2, Val:-2, Phe:0, Tyr:-1, Trp:-1],
Ile:[Cys:-1,Ser:-2, Thr:-2, Pro:-3, Ala:-1, Gly:-4, Asn:-3, Asp:-3, Glu:-3, Gln:-3, His:-3, Arg:-3, Lys:-3, Met:1, Ile:4, Leu:2, Val:1, Phe:0, Tyr:-1, Trp:-3],
Leu:[Cys:-1,Ser:-2, Thr:-2, Pro:-3, Ala:-1, Gly:-4, Asn:-3, Asp:-4, Glu:-3, Gln:-2, His:-3, Arg:-2, Lys:-2, Met:2, Ile:2, Leu:4, Val:3, Phe:0, Tyr:-1, Trp:-2],
Val:[Cys:-1,Ser:-2, Thr:-2, Pro:-2, Ala:0, Gly:-3, Asn:-3, Asp:-3, Glu:-2, Gln:-2, His:-3, Arg:-3, Lys:-2, Met:1, Ile:3, Leu:1, Val:4, Phe:-1, Tyr:-1, Trp:-3],
Phe:[Cys:-2,Ser:-2, Thr:-2, Pro:-4, Ala:-2, Gly:-3, Asn:-3, Asp:-3, Glu:-3, Gln:-3, His:-1, Arg:-3, Lys:-3, Met:0, Ile:0, Leu:0, Val:-1, Phe:6, Tyr:3, Trp:1],
Tyr:[Cys:-2,Ser:-2, Thr:-2, Pro:-3, Ala:-2, Gly:-3, Asn:-2, Asp:-3, Glu:-2, Gln:-1, His:2, Arg:-2, Lys:-2, Met:-1, Ile:-1, Leu:-1, Val:-1, Phe:3, Tyr:7, Trp:2],
Trp:[Cys:-2,Ser:-3, Thr:-3, Pro:-4, Ala:-3, Gly:-2, Asn:-4, Asp:-4, Glu:-3, Gln:-2, His:-2, Arg:-3, Lys:-3, Met:-1, Ile:-3, Leu:-2, Val:-3, Phe:1, Tyr:2, Trp:11]
]
Using this you can just call
def score = blosum62[Arg][Cys]
println("Substituting Arg by Cys gives " + score)

You can always download the matrix from NCBI web site:
ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM62
Other matrices are also available from the parent directory.
I never saw implementation of Needleman-Wunsch with matrix calculation. It's much easier just to include the matrix in the code or as a separate file.
You can find some details how BLOSUM matrices are calculated for example here: http://en.wikipedia.org/wiki/BLOSUM.

You can't infer a blosum matrix from another as you can do for PAM ones: all the blosum are calculated from a different set of data and are not correlated within theirselves.
For example, a PAM250 Matrix is just a PAM1 matrix multiplied 250 times by itself; but this is not true for BLOSUMs, and you can't infer BLOSUM80 from BLOSUM64, for example.

Yes, you can implement a blosum matrix as hardwired piece of code, you might gain some speed with this. But definitely you loose flexibility. I would recommend writing a reader for NCBI format, e.g returning SubstitutionMatrix data type. Then you can pass around such a matrix as an object.
SubstitutionMatrix object may hold a 2D matrix and "something" responsible for decoding amino acid names, e.g. a hashing array. Depending on the language you choose, you may also use enums to represent amino acid types. In such a case you can use them directly to address the 2D array.
Hopefully this is clear, I can write more details if you like/need.

Here is example of parsing the blosum62 file from this link ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM62 in Java.
Create class Parsing:
private String[] rowData;
private final int MARTRIX_SIZE = 24;
private String[][] matrix = new String[MARTRIX_SIZE][MARTRIX_SIZE];
private HashMap<String, Integer> index = new HashMap<>();
private String filePath = "blosum62.txt";
public void blosumMartix() {
File fileObj = new File(filePath);
Scanner input;
boolean readLine = true;
int rowCounter = 0;
try {
input = new Scanner(fileObj);
while (input.hasNext()) {
String lineReader = input.nextLine().replaceAll(" ", " ");
if (!lineReader.substring(0, 1).equals("#")) {
if (readLine) {
readLine = false;
continue;
}
rowData = lineReader.split(" ");
for (int i = 1; i < rowData.length; i++) {
matrix[rowCounter][i - 1] = rowData[i];
}
index.put(rowData[0], rowCounter);
rowCounter++;
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
Now you want to calculate the the cost of example A and * which returns -4 you should write method for this:
public int getDistance(String strS1, String strS2) {
try {
return getDistance(matrixIndex.get(strS1), matrixIndex.get(strS2));
} catch (Exception ex) {
System.out.println("Key out of range, check your string input");
System.exit(0);
}
return 0;
}
private int getDistance(int charS1, int charS2) {
if (charS1 < 0 || charS1 > matrix[0].length) {
System.out.println("Gap out of range");
System.exit(1);
}
if (charS2 < 0 || charS2 > matrix[0].length) {
System.out.println("Gap out of range");
System.exit(2);
}
return Integer.parseInt(matrix[charS1][charS2]);
}
Finally in main method
Parsing parsing = new Parsing();
parsing.blosumMartix();
String result = parsing.getDistance("A", "*");
System.out.print(result);
This will print -4.

Related

Extremely large SVG file when using Golang Draw2d

I have been using the library draw2d with go-nexrad, and I am able to generate PNG and SVG files. However, the SVG files that are generated are enormous, with a less than 10MB PNG file becoming a 28MB SVG file with the same options. Here is the code:
func render(out string, radials []*archive2.Message31, label string) {
width := float64(imageSize)
height := float64(imageSize)
PNGcanvas := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
draw.Draw(PNGcanvas, PNGcanvas.Bounds(), image.Black, image.ZP, draw.Src)
PNGgc := draw2dimg.NewGraphicContext(PNGcanvas)
SVGcanvas := draw2dsvg.NewSvg()
SVGcanvas.Width = strconv.Itoa(int(width)) + "px"
SVGcanvas.Height = strconv.Itoa(int(width)) + "px"
SVGgc := draw2dsvg.NewGraphicContext(SVGcanvas)
xc := width / 2
yc := height / 2
pxPerKm := width / 2 / 460
firstGatePx := float64(radials[0].ReflectivityData.DataMomentRange) / 1000 * pxPerKm
gateIntervalKm := float64(radials[0].ReflectivityData.DataMomentRangeSampleInterval) / 1000
gateWidthPx := gateIntervalKm * pxPerKm
t := time.Now()
log.Println("rendering radials")
// valueDist := map[float32]int{}
for _, radial := range radials {
// round to the nearest rounded azimuth for the given resolution.
// ex: for radial 20.5432, round to 20.5
azimuthAngle := float64(radial.Header.AzimuthAngle) - 90
if azimuthAngle < 0 {
azimuthAngle = 360.0 + azimuthAngle
}
azimuthSpacing := radial.Header.AzimuthResolutionSpacing()
azimuth := math.Floor(azimuthAngle)
if math.Floor(azimuthAngle+azimuthSpacing) > azimuth {
azimuth += azimuthSpacing
}
startAngle := azimuth * (math.Pi / 180.0) /* angles are specified */
endAngle := azimuthSpacing * (math.Pi / 180.0) /* clockwise in radians */
// start drawing gates from the start of the first gate
distanceX, distanceY := firstGatePx, firstGatePx
if vectorize == "png" {
PNGgc.SetLineWidth(gateWidthPx + 1)
} else if vectorize == "svg" {
SVGgc.SetLineWidth(gateWidthPx + 1)
}
if vectorize == "png" {
PNGgc.SetLineCap(draw2d.ButtCap)
} else if vectorize == "svg" {
SVGgc.SetLineCap(draw2d.ButtCap)
}
var gates []float32
switch product {
case "vel":
gates = radial.VelocityData.ScaledData()
case "sw":
gates = radial.SwData.ScaledData()
case "rho":
gates = radial.RhoData.ScaledData()
default:
gates = radial.ReflectivityData.ScaledData()
}
numGates := len(gates)
for i, v := range gates {
if v != archive2.MomentDataBelowThreshold {
//fmt.Println(gateWidthPx)
if i == 0 {
SVGgc.SetLineWidth(0)
} else if i > 0 {
SVGgc.SetLineWidth(gateWidthPx + 1)
}
// valueDist[v] += 1
if vectorize == "png" {
PNGgc.MoveTo(xc+math.Cos(startAngle)*distanceX, yc+math.Sin(startAngle)*distanceY)
} else if vectorize == "svg" {
SVGgc.MoveTo(xc+math.Cos(startAngle)*distanceX, yc+math.Sin(startAngle)*distanceY)
}
// make the gates connect visually by extending arcs so there is no space between adjacent gates.
if i == 0 {
if vectorize == "png" {
PNGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle-.001, endAngle+.001)
} else if vectorize == "svg" {
SVGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle-.001, endAngle+.001)
}
} else if i == numGates-1 {
if vectorize == "png" {
PNGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle, endAngle)
} else if vectorize == "svg" {
SVGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle, endAngle)
}
} else {
if vectorize == "png" {
PNGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle, endAngle+.001)
} else if vectorize == "svg" {
SVGgc.ArcTo(xc, yc, distanceX, distanceY, startAngle, endAngle+.001)
}
}
if vectorize == "png" {
PNGgc.SetStrokeColor(colorSchemes[product][colorScheme](v))
} else if vectorize == "svg" {
SVGgc.SetStrokeColor(colorSchemes[product][colorScheme](v))
}
if vectorize == "png" {
PNGgc.Stroke()
} else if vectorize == "svg" {
SVGgc.Stroke()
}
}
distanceX += gateWidthPx
distanceY += gateWidthPx
azimuth += radial.Header.AzimuthResolutionSpacing()
}
}
// fmt.Println(valueDist)
if renderLabel {
if vectorize == "png" {
addLabel(PNGcanvas, int(width-495.0), int(height-10.0), label)
} else if vectorize == "svg" {
logrus.Warn("Labels cannot be drawn on an SVG image, ignoring -L flag")
}
}
// Save to file
if vectorize == "png" {
draw2dimg.SaveToPngFile(out, PNGcanvas)
fmt.Println("Finished in", time.Since(t))
} else if vectorize == "svg" {
draw2dsvg.SaveToSvgFile(out, SVGcanvas)
fmt.Println("Finished in", time.Since(t))
}
}
The full file can be found in my fork of the project here.
The reason I think the SVG is so large is because it is generating the file very inefficiently, possibly by trying to render every pixel instead of just a start and end point. I have tried setting the DPI with SVGgc.setDPI(), but that hasn't worked.
If anyone has any idea about why the file is so large, or any idea of how to fix it, I would greatly appreciate your input. Hopefully you won't have to go through the entire go-nexrad project to understand this, I have included the code block that I am almost certain is causing the issue, and is the part that uses the library.

Draftail blockquote with it's own css class added, is this possible?

I managed to add a blockquote with a css class button to the draftail (code below) and it works ok. The only issue so far is if I try and a link to a word using the standard link button in the editor within that blockquote text, I get a JS error (also below)
I've tried to adapt the stock example from the docs, but I'm guessing I've messed up something.
The code in wagtail_hooks.py
def poquote_entity_decorator(props):
"""
Draft.js ContentState to database HTML.
Converts the poquote entities into a blockquote with class tag.
"""
return DOM.create_element('blockquote', {
'class': 'pullout',
}, props['children'])
class PoQuoteEntityElementHandler(InlineEntityElementHandler):
"""
Database HTML to Draft.js ContentState.
Converts the blockquote tag into a PoQuote entity, with the right
data.
"""
mutability = 'IMMUTABLE'
def get_attribute_data(self, attrs):
return {
'poquote': attrs['class'],
}
#hooks.register('insert_editor_js')
def draftail_editor_js():
js_files = [
'wagtailadmin/js/draftail.js',
'js/draftail.js',
]
js_includes = format_html_join('\n', '<script src="{0}{1}">
</script>',
((settings.STATIC_URL, filename) for filename in js_files)
)
return js_includes
#hooks.register('register_rich_text_features')
def register_poquote_feature(features):
features.default_features.append('poquote')
"""
Registering the `poquote` feature, which uses the `POQUOTE`
Draft.js entity type,
and is stored as HTML with a `<blockquote class='pullout'>` tag.
"""
feature_name = 'poquote'
type_ = 'POQUOTE'
control = {
'type': type_,
'icon': 'icon icon-form',
'description': 'Pull Out Quote',
}
features.register_editor_plugin(
'draftail', feature_name,
draftail_features.EntityFeature(control)
)
features.register_converter_rule('contentstate', feature_name, {
# Note here that the conversion is more complicated than for
blocks and inline styles.
'from_database_format': {'blockquote[class]':
PoQuoteEntityElementHandler(type_)},
'to_database_format': {'entity_decorators': {type_:
poquote_entity_decorator}},
})
and the JS
const React = window.React;
const Modifier = window.DraftJS.Modifier;
const EditorState = window.DraftJS.EditorState;
// Not a real React component – just creates the entities as soon as
it is rendered.
class PoqSource extends React.Component {
componentDidMount() {
const { editorState, entityType, onComplete } = this.props;
const content = editorState.getCurrentContent();
const selection = editorState.getSelection();
const anchorKey = selection.getAnchorKey();
const currentBlock = content.getBlockForKey(anchorKey);
const start = selection.getStartOffset();
const end = selection.getEndOffset();
const selectedText = currentBlock.getText().slice(start,
end);
// Uses the Draft.js API to create a new entity with the right
data.
const contentWithEntity =
content.createEntity(entityType.type, 'IMMUTABLE', {
poq: selectedText,
});
const entityKey = contentWithEntity.getLastCreatedEntityKey();
// We also add some text for the entity to be activated on.
const text = `${selectedText}`;
const newContent = Modifier.replaceText(content, selection,
text, null, entityKey);
const nextState = EditorState.push(editorState, newContent,
'insert-characters');
onComplete(nextState);
}
render() {
return null;
}
}
const Poq = (props) => {
const { entityKey, contentState } = props;
const data = contentState.getEntity(entityKey).getData();
return React.createElement('blockquote', {className: 'pullout'},
props.children);
};
window.draftail.registerPlugin({
type: 'POQUOTE',
source: PoqSource,
decorator: Poq,
});
The error :
vendor.js:1 TypeError: Cannot read property 'startsWith' of undefined
at h (VM7359 draftail.js:1)
at n.value (VM7359 draftail.js:1)
at commitLifeCycles (vendor.js:1)
at e (vendor.js:1)
at x (vendor.js:1)
at w (vendor.js:1)
at batchedUpdates (vendor.js:1)
at Z (vendor.js:1)
at It (vendor.js:1)
l # vendor.js:1
vendor.js:1 Uncaught TypeError: Cannot read property 'startsWith' of
undefined
at h (VM7359 draftail.js:1)
at n.value (VM7359 draftail.js:1)
at commitLifeCycles (vendor.js:1)
at e (vendor.js:1)
at x (vendor.js:1)
at w (vendor.js:1)
at batchedUpdates (vendor.js:1)
at Z (vendor.js:1)
at It (vendor.js:1)
vendor.js:1 TypeError: Cannot read property 'startsWith' of undefined
at h (VM7359 draftail.js:1)
at n.value (VM7359 draftail.js:1)
at commitLifeCycles (vendor.js:1)
at e (vendor.js:1)
at x (vendor.js:1)
at w (vendor.js:1)
at batchedUpdates (vendor.js:1)
at Z (vendor.js:1)
at It (vendor.js:1)
l # vendor.js:1
vendor.js:1 Uncaught TypeError: Cannot read property 'startsWith' of
undefined
at h (VM7359 draftail.js:1)
at n.value (VM7359 draftail.js:1)
at commitLifeCycles (vendor.js:1)
at e (vendor.js:1)
at x (vendor.js:1)
at w (vendor.js:1)
at batchedUpdates (vendor.js:1)
at Z (vendor.js:1)
at It (vendor.js:1)
If all you want is a block as <blockquote class='pullout'>my text</blockquote>, there is a simpler way to do it without writing JavaScript code.
First, start from the example in the official documentation about blocks, using blockquote:
from wagtail.admin.rich_text.converters.html_to_contentstate import BlockElementHandler
#hooks.register('register_rich_text_features')
def register_blockquote_feature(features):
"""
Registering the `blockquote` feature, which uses the `blockquote` Draft.js block type,
and is stored as HTML with a `<blockquote>` tag.
"""
feature_name = 'blockquote'
type_ = 'blockquote'
tag = 'blockquote'
control = {
'type': type_,
'label': '❝',
'description': 'Blockquote',
# Optionally, we can tell Draftail what element to use when displaying those blocks in the editor.
'element': 'blockquote',
}
features.register_editor_plugin(
'draftail', feature_name, draftail_features.BlockFeature(control)
)
features.register_converter_rule('contentstate', feature_name, {
'from_database_format': {tag: BlockElementHandler(type_)},
'to_database_format': {'block_map': {type_: tag}},
})
You can write styles to display those blocks in the editor with the Draftail-block--blockquote class.
Then, you need to adapt the converter rules so this is stored as <blockquote class='pullout'>my text</blockquote> with the pullout class:
features.register_converter_rule('contentstate', feature_name, {
'from_database_format': {'blockquote[class]': BlockElementHandler(type_)},
'to_database_format': {
'block_map': {
type_: {
'element': tag,
'props': {
'class': 'pullout',
},
},
},
},
})
Of course you can use the poquote type and-or feature name if you want to, no need to use blockquote.

The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)

I am trying to follow the example in a pluralsight videos
https://app.pluralsight.com/player?course=aspdotnet-5-ef7-bootstrap-angular-web-app&author=shawn-wildermuth&name=aspdotnet-5-ef7-bootstrap-angular-web-app-m7&clip=8&mode=live&start=2
When I am trying to complete the Api to add the coordinates I am having the error:
The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
This is happening on the following class:
using Microsoft.Extensions.Logging;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.Http;
namespace Moran.Services
{
public class CoordService
{
private ILogger<CoordService> _logger;
public CoordService(ILogger<CoordService> logger)
{
_logger = logger;
}
public async Task<CoordServiceResult> Lookup(string location)
{
var result = new CoordServiceResult()
{
Success = false,
Message = "Undetermined failures while looking up coordinates"
};
//Lookup Coordinates
var bingKey = Startup.Configuration["AppSettings:BingKey"];
var encodedName = WebUtility.UrlEncode(location);
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={bingKey}";
var client = new HttpClient();
var json = await client.GetStringAsync(url);
// Read out the results
// Fragile, might need to change if the Bing API changes
var results = JObject.Parse(json);
var resources = results["resourceSets"][0]["resources"];
if (!resources.HasValues)
{
result.Message = $"Could not find '{location}' as a location";
}
else
{
var confidence = (string)resources[0]["confidence"];
if (confidence != "High")
{
result.Message = $"Could not find a confident match for '{location}' as a location";
}
else
{
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Latitude = (double)coords[0];
result.Longitude = (double)coords[1];
result.Success = true;
result.Message = "Success";
}
}
return result;
}
}
}
This is happening when I try to add
var client = new HttpClient();
Any Idea why this is happening?
I cannot find any reason why it doesn't compile....
HttpClient class resides in System.Net.Http namespace, which is in System.Net.Http.dll. To use this class in your ASP.NET 5 project,You need to add System.Net.Http to the "dependencies" section of the json data inside your project.json file
"dependencies": {
"Microsoft.AspNet.Diagnostics": "1.0.0-beta5",
"Microsoft.AspNet.Mvc": "6.0.0-beta5",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta5",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta5",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta5",
"Microsoft.Framework.Logging": "1.0.0-beta5",
"Microsoft.Framework.Logging.Console": "1.0.0-beta5",
"System.Net.Http": "4.0.1-beta-23409"
},
4.0.1-beta-23409 is the latest version as of this writing. Visual studio intellisense will give you multiple available versions and you can pick the latest/stable.
After making this change, when you save the file, It will do a dnu restore (which will usually download the necessary packages as needed) and add a reference to the System.Net.Http assembly. You can add a using statement in your class and start using HttpClient class.
using System;
using System.Net.Http;
public class SomeClass
{
public void SomeMethod()
{
var client = new HttpClient();
}
}

Windows 8.0 not discovering CBPeripheral

I have a sample iPhone application taken from https://github.com/KhaosT/CBPeripheralManager-Demo/tree/master/PeripheralModeTest. I am advertising my peripheral service as follows.
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
NSLog(#"didAddService start");
NSLog(#"Added");
NSDictionary *advertisingData = #{CBAdvertisementDataLocalNameKey : #"BTService", CBAdvertisementDataServiceUUIDsKey : #[[CBUUID UUIDWithString:#"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FC"]]};
[peripheral startAdvertising:advertisingData];
NSLog(#"didAddService end");
}
I have taken windows app code sample from https://code.msdn.microsoft.com/windowsapps/Bluetooth-Generic-5a99ef95. I replaced the Heart rate UUID with the service UUID. But on running it, it is unable to find the service mentioned.
void Scenario1_DeviceEvents::RunButton_Click(Object ^ /* sender */, RoutedEventArgs ^ /* e */)
{
RunButton->IsEnabled = false;
Vector<String^>^ additionalProperties = ref new Vector<String^>;
additionalProperties->Append("System.Devices.ContainerId");
Platform::Guid lol = Platform::Guid::Guid(0xEBA38950, 0x0D9B, 0x4DBA, 0xB0, 0xDF, 0xBC, 0x71, 0x96, 0xDD, 0x44, 0xFC);
create_task(DeviceInformation::FindAllAsync(
GattDeviceService::GetDeviceSelectorFromUuid(lol), additionalProperties))
.then([this](Windows::Devices::Enumeration::DeviceInformationCollection^ devices)
{
this->devices = devices;
if (devices->Size > 0)
{
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, devices]()
{
DevicesListBox->Items->Clear();
auto serviceNames = ref new Vector<String^>();
for_each(begin(devices), end(devices), [=](DeviceInformation^ device)
{
serviceNames->Append(device->Name);
});
cvs->Source = serviceNames;
DevicesListBox->Visibility = Windows::UI::Xaml::Visibility::Visible;
}));
}
else
{
MainPage::Current->NotifyUser(L"Could not find any Heart Rate devices. Please make sure your " +
"device is paired and powered on!",
NotifyType::StatusMessage);
}
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
{
RunButton->IsEnabled = true;
}));
}).then([](task<void> finalTask)
{
try
{
// Capture any errors and exceptions that occured during device discovery
finalTask.get();
}
catch (COMException^ e)
{
MainPage::Current->NotifyUser("Error: " + e->Message, NotifyType::ErrorMessage);
}
});
}
I tried pairing the device with windows. But still no luck. It has been so frustating, no proper support for discovering devices.

Free VRam on OS X

does anyone know how to get the free(!) vram on os x?
I know that you can query for a registry entry:
typeCode = IORegistryEntrySearchCFProperty(dspPort,kIOServicePlane,CFSTR(kIOFBMemorySizeKey),
kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents);
but this will return ALL vram, not the free vram. Under windows you can query for free VRAM using directshow
mDDrawResult = DirectDrawCreate(NULL, &mDDraw, NULL);
mDDrawResult = mDDraw->QueryInterface(IID_IDirectDraw2, (LPVOID *)&mDDraw2);
DDSCAPS ddscaps;
DWORD totalmem, freemem;
ddscaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_VIDEOMEMORY;
mDDrawResult = mDDraw2->GetAvailableVidMem(&ddscaps, &totalmem, &freemem);
Ugly, but it works. Anyone knows the osx way?
Best
Wendy
answering myself so others may use this:
#include <IOKit/graphics/IOGraphicsLib.h>
size_t currentFreeVRAM()
{
kern_return_t krc;
mach_port_t masterPort;
krc = IOMasterPort(bootstrap_port, &masterPort);
if (krc == KERN_SUCCESS)
{
CFMutableDictionaryRef pattern = IOServiceMatching(kIOAcceleratorClassName);
//CFShow(pattern);
io_iterator_t deviceIterator;
krc = IOServiceGetMatchingServices(masterPort, pattern, &deviceIterator);
if (krc == KERN_SUCCESS)
{
io_object_t object;
while ((object = IOIteratorNext(deviceIterator)))
{
CFMutableDictionaryRef properties = NULL;
krc = IORegistryEntryCreateCFProperties(object, &properties, kCFAllocatorDefault, (IOOptionBits)0);
if (krc == KERN_SUCCESS)
{
CFMutableDictionaryRef perf_properties = (CFMutableDictionaryRef) CFDictionaryGetValue( properties, CFSTR("PerformanceStatistics") );
//CFShow(perf_properties);
// look for a number of keys (this is mostly reverse engineering and best-guess effort)
const void* free_vram_number = CFDictionaryGetValue(perf_properties, CFSTR("vramFreeBytes"));
if (free_vram_number)
{
ssize_t vramFreeBytes;
CFNumberGetValue( (CFNumberRef) free_vram_number, kCFNumberSInt64Type, &vramFreeBytes);
return vramFreeBytes;
}
}
if (properties) CFRelease(properties);
IOObjectRelease(object);
}
IOObjectRelease(deviceIterator);
}
}
return 0; // when we come here, this is a fail
}
i am somewhat surprised that this query takes almost 3 msec ..
be aware that there may be more than one accelerator on your system ( eg. macbook )
so be sure you select the proper one for the query

Resources