id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23538700
|
Here are the instructions:
Officer: 3357927
CaseNum: 701-1-60140847-3357927
Case 701 - Credible cat thief - stage 2
Kid they need you down at the precinct again.
This time it's a sneaky cat thief who has been absconding with the neighbourhoods felines for some time.
Luckily old Mrs Olivetti caught a glimpse of them as they disappeared over her back fence.
We’ve a bunch of likely characters lined-up but we need your brains to solve the mystery.
Please create a function that takes a suspect object as parameter from the data structure below.
Your function should return a boolean value indicating whether or not they match the witness statement.
You should use conditional statements to compare the suspect's properties to the statement.
It should only return "true" if the suspect matches the description in full.
The function is already being called in draw() but it is your job to implement it.
There are many possible ways of carrying out your duties,
but you should complete this task using ONLY the following
commands:
- function testProperties(suspectObj){}
- if()
Witness statement:
It all started when I was exiting the store. That's when I noticed them. I'm pretty sure they were above the age of 48. They had thin blond hair. Their expression seemed menacing. It's so hard to remember right now. The person I saw was male. They wore red glasses. They were quite big, they probably weigh more than 52 Kg. I'm not quite sure. That's all I can remember about them.
Here is the code:
var suspectList = [
{
"name": "JENIFFER GOODBURY",
"gender": "female",
"expression": "blank",
"hair": "thick black",
"weight": 64,
"age": 62
},
{
"name": "JAUNITA MYRLE",
"gender": "male",
"expression": "menacing",
"hair": "thin blond",
"weight": 62,
"age": 58
},
{
"name": "TAMICA DURANTS",
"gender": "female",
"expression": "sad",
"hair": "no",
"weight": 100,
"age": 43
},
{
"name": "LESLEY PORTOS",
"gender": "female",
"expression": "angry",
"hair": "long white",
"weight": 92,
"age": 47
},
{
"name": "JACQUELINE SILVEIRA",
"gender": "male",
"expression": "empty",
"hair": "shaved",
"weight": 70,
"age": 21
}
];
var myFont;
var backgroundImg;
function preload() {
myFont = loadFont('SpecialElite.ttf');
backgroundImg = loadImage("Background.png");
}
function setup()
{
createCanvas(640,480);
textFont(myFont);
}
// Declare your function here
function testProperties(suspectObj)
{
if(suspectList.age > 48 && suspectList.hair == "thin blond" && suspectList.expression == "menacing" && suspectList.gender == "male" && suspectList.weight > 52 )
{
return true;
}
return false;
}
function draw()
{
//You don't need to alter this code
image(backgroundImg, 0, 0);
for(let i = 0 ; i < suspectList.length; i++){
if(testProperties(suspectList[i]) == true){
fill(255,0,0);
text(suspectList[i].name + " is guilty!", 60, 60 + i * 20);
}else{
fill(0,155,0);
text(suspectList[i].name + " is not guilty", 60, 60 + i * 20 );
}
}
}
A: So close! I think you have typo. You probably meant suspectObj instead of suspectList in testProperties:
function testProperties(suspectObj)
{
if(suspectObj.age > 48 && suspectObj.hair == "thin blond" && suspectObj.expression == "menacing" && suspectObj.gender == "male" && suspectObj.weight > 52 )
{
return true;
}
return false;
}
var suspectList = [
{
"name": "JENIFFER GOODBURY",
"gender": "female",
"expression": "blank",
"hair": "thick black",
"weight": 64,
"age": 62
},
{
"name": "JAUNITA MYRLE",
"gender": "male",
"expression": "menacing",
"hair": "thin blond",
"weight": 62,
"age": 58
},
{
"name": "TAMICA DURANTS",
"gender": "female",
"expression": "sad",
"hair": "no",
"weight": 100,
"age": 43
},
{
"name": "LESLEY PORTOS",
"gender": "female",
"expression": "angry",
"hair": "long white",
"weight": 92,
"age": 47
},
{
"name": "JACQUELINE SILVEIRA",
"gender": "male",
"expression": "empty",
"hair": "shaved",
"weight": 70,
"age": 21
}
];
function testProperties(suspectObj)
{
if(suspectObj.age > 48 && suspectObj.hair == "thin blond" && suspectObj.expression == "menacing" && suspectObj.gender == "male" && suspectObj.weight > 52 )
{
return true;
}
return false;
}
console.log(suspectList.map( s => { return {name: s.name, test: testProperties(s)} }));
You might want to slow down and double check both the code and the data (e.g. is it "Jaunita" or "Juanita", is Jacqueline a male, etc.)
| |
doc_23538701
|
After the pre-processing for text is done we must create a classification in order to get the positive and negative, so my question is it better to have example:
first way:
*
*100 records of text to train that includes 2 fields text &
status filed that indicate if its positive 1 or negative 0.
second way:
100 records of text to train and make a vocabulary for bag of word in order to train and compare the tested records based on this bag of word.
if i am mistaking in my question please tel me and correct my question.
A: I think you might miss something here, so to train a sentiment analysis model, you will have a train data which every row has label (positive or negative) and a raw text. In order to make computer can understand or "see" the text is by representing the text as number (since computer cannot understand text), so one of the way to represent text as number is by using bag of words (there are other methods to represent text like TF/IDF, WORD2VEC, etc.). So when you train the model using data train, the program should preprocess the raw text, then it should make (in this case) a bag of words map where every element position represent one vocabulary, and it will become 1 or more if the word exist in the text and 0 if it doesn't exist.
Now suppose the training has finished, then the program produce a model, this model is what you save, so whenever you want to test a data, you don't need to re-train the program again. Now when you want to test, yes, you will use the bag of words mapping of the train data, suppose there is a word in the test dataset that never occurred in train dataset, then just map it as 0.
in short:
when you want to test, you have to use the bag of words mapping from the data train
| |
doc_23538702
|
places, it stays in null, I have tried to return it with the function but it tells me that it is not compatible Future to list.
class AppState extends ChangeNotifier {
AppState({
places,
this.selectedCategory = PlaceCategory.wantToGo,
this.viewType = PlaceTrackerViewType.map,
}){
getPois();
}
List<Place> places = [];
PlaceCategory selectedCategory = PlaceCategory.wantToGo;
PlaceTrackerViewType viewType;
void getPois() async {
final poi = await fetchPois();
final resType = await fetchPoisTypes();
poi.pois.forEach((element) {
places.add(Place(
id: element.poi.id!,
latLng: LatLng(double.parse(element.poi.longitud!),double.parse(element.poi.latitud!)),
name: element.poi.nombreEs!,
description: element.poi.nombreEs! +" "+element.poi.informacionEs!,
starRating: 3,
category: PlaceCategory.wantToGo,
));
//print(LatLng(double.parse(element.poi.latitud), double.parse(element.poi.longitud)));
});
resType.forEach((element) {
places.add(Place(
id: element.poiType.id!,
latLng: LatLng(1.1, 1.1),
name: element.poiType.tipoEs!,
description: element.poiType.explicacionEs,
starRating: 0,
category: PlaceCategory.wantToGo,
));
});
notifyListeners();
}
A: Your mistake is a misunderstanding of the async statement of the getPois method.
async will allow Dart to delay the execution of the method. It acts somehow like a corouting, which is a non-parallel multitasking. In Flutter, it is used for example to avoid blocking operations (the Flutter/Dart engine can delay async method calls to prioritize screen drawing.
You could check for the existence of your List after calling await getPois();.
This explains that you can't return the list. Since your method is marked async, it has to return a future. So you could make it return a Future<List<Place>>.
A: Try to wrap it like this:
class AppState extends ChangeNotifier {
AppState({
this.selectedCategory = PlaceCategory.wantToGo,
this.viewType = PlaceTrackerViewType.map,
}){
_initialize();
}
final List<Place> _places = <Place>[];
final PlaceCategory selectedCategory;
final PlaceTrackerViewType viewType;
void getPois() async {
final poi = await fetchPois();
final resType = await fetchPoisTypes();
poi.pois.forEach((element) {
_places.add(Place(
id: element.poi.id!,
latLng: LatLng(double.parse(element.poi.longitud!),double.parse(element.poi.latitud!)),
name: element.poi.nombreEs!,
description: element.poi.nombreEs! +" "+element.poi.informacionEs!,
starRating: 3,
category: PlaceCategory.wantToGo,
));
//print(LatLng(double.parse(element.poi.latitud), double.parse(element.poi.longitud)));
});
resType.forEach((element) {
_places.add(Place(
id: element.poiType.id!,
latLng: LatLng(1.1, 1.1),
name: element.poiType.tipoEs!,
description: element.poiType.explicacionEs,
starRating: 0,
category: PlaceCategory.wantToGo,
));
});
notifyListeners();
}
Future<void> _initialize() async{
await getPois();
}
}
| |
doc_23538703
|
template< class RandomIt, class URNG >
void shuffle( RandomIt first, RandomIt last, URNG&& g );
compared to:
template< class RandomIt >
void random_shuffle( RandomIt first, RandomIt last );
I mean, it seems that whatever URNG is (a uniform distribution), the result will be the same (from a statistical point of view). The only point I see, is that std::shuffle is thead-safe, whereas this overload ofstd::random_shuffle is not. Could you confirm that ?
EDIT: I thought that URNG should be a uniform distribution but that does not seem to compile. So can someone provide a little example of use of std::shuffle?
A: As mentioned in the comments, std::shuffle takes a random number generator (or engine in standard speak), not a random number distribution. Different random number generators have different characteristics even if they have a theoretically uniform distribution.
*
*Random or pseudo-random - True random number generators use some sort of an external entropy source. Pseudo-random generators (PRNGs) are strictly deterministic.
*Performance - some generators are faster than others.
*Memory usage - some PRNGs need more memory to store their state than others.
*Period length - all PRNGs have a finite period after which they start repeating the same sequence from the beginning. Some have much longer periods than others.
*Randomness quality - there are numerous tests for measuring whether there are subtle (or not-so-subtle!) patterns in a pseurorandom stream. See, for example, the Diehard tests.
*Whether the stream is cryptographically secure or not. AFAIK, none of the standard PRNGs are.
For an overview of the different generators offered by the standard, please refer to http://en.cppreference.com/w/cpp/numeric/random.
| |
doc_23538704
|
Thanks!
A: Python is well documented.
| |
doc_23538705
|
My code is as follows:
var params = {
TableName: 'Department',
KeyConditionExpression: '#company = :companyId'
, ExpressionAttributeNames: {
'#company': 'CompanyID',
'#dType': 'DepartmentType',
'#cTime': 'CreatedTime'
}
, ExpressionAttributeValues: {
':companyId': 'Test',
':deptType': dType,
':daysPrior': 1250456879634
},FilterExpression: '#dType = :deptType AND #ts > :daysPrior'
};
A: There is typo error in the format in your query(after CreatedTime)
To keep it clean, use either double quotes or single quotes but not both.
I have used double quotes, just the way aws sample codes are there.
var params = {
TableName: "Department",
KeyConditionExpression: "#company = :companyId",
ExpressionAttributeNames: {
"#company": "CompanyID",
"#dType": "DepartmentType",
"#cTime": "CreatedTime" //here
},
ExpressionAttributeValues: {
":companyId": "Test",
":deptType": dType,
":daysPrior": 1250456879634
},
FilterExpression: "#dType = :deptType AND #cTime > :daysPrior"
};
A: In case you need a bit more complex filter expressions to scan or query your DynamoDB table, you could use brackets, for example:
var params = {
TableName: "Department",
...
FilterExpression: "(not (#type <> :type and #company = :company)) or (#timestamp > :timestamp)",
...
};
Note: this example filter expression does not have a particular meaning.
| |
doc_23538706
|
<?php
class DB
{
private $mysqlilink;
private $errors;
function __construct($errors = array())
{
$this -> errors = $errors;
$this -> connect();
}
function connect()
{
$server = "127.0.0.1";
$user_name = "un";
$password = "pw";
$database = "db";
if ($this -> mysqlilink == null)
{
$this -> mysqlilink = new mysqli($server, $user_name, $password, $database);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
return $this -> mysqlilink;
}
function __destruct()
{
$stmt -> close();
}
}
?>
I have plans to use at least one class (in its own script file) with dedicated PHP functions that access the database for various parts of the website. After importing this script above, how do I link to it and make a call to the database through the object's connection? I am using the following code:
<?php
include_once("connect.php");
class PageFunctions
{
function printText()
{
if ($stmt = $this -> mysqlilink -> prepare("SELECT Text, MoreText FROM mytext WHERE id = 1"))
{
$stmt -> execute(); $stmt -> store_result();
$rows = $stmt -> num_rows;
if ($rows == 0) { return 'Database Not Found'; }
else
{
$stmt -> bind_result($returnedText, $moreReturnedText); // Output variable(s)
while ($stmt -> fetch()) // Return results
{
return 'First text: ' . $returnedText . ' Second text: ' . $moreReturnedText;
}
}
$stmt -> free_result();
return;
}
else { printf("Prepared Statement Error: %s\n", $this -> mysqlilink -> error); }
}
}
?>
To reiterate, I need to use the first code sample as a class that forms an object in multiple other classes/code files like the second code sample. Since I am new to PHP object orientation I was unable to successfully accomplish this, so I thought I'd ask for some expert advice before I come up with a bad solution.
A: It sounds like you're looking for Dependency Injection. There are other ways, but this is the best practice.
//create an object of the DB class
$DB = new DB();
//create a PageFunctions object and pass the DB object into it as a dependency
$PF = new PageFunctions($DB);
//call your function from PageFunctions
$PF->myFunction();
//follow these concepts and do whatever you want!
You can make this work by setting a constructor for PageFunctions:
class PageFunctions() {
//we don't want to accidentally change DB, so lets make it private;
private $DB;
//this is the class constructor
//the constructor is called when instantiating the class - new PageFunctions()
public function __construct(DB $DB) {
//now the DB object is available anywhere in this class!
$this->DB = $DB;
}
//sample function
public function myFunction() {
$this->DB->connect();
}
}
So, anytime you need to use a class within another class, make an instance (object) of it (or use an existing one) and pass it into the new class that needs it when creating an instance of it.
You might see this behavior accomplished using a Dependency Injection container, but it is still the same concept, system, and result. It's just a bit more abstracted. As you might have noticed from my explanation there, if you have a lot of classes that depend on other classes, that depend on other classes, etc, it can get quite overwhelming manually creating the instances and passing them in. A dependency injection container is nice because it lets you tell it how to make each class, and then it will take care of putting them altogether.
| |
doc_23538707
|
My .htaccess looked like this:
RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
AddType audio/aac .aac
AddType audio/mp4 .mp4 .m4a
AddType audio/mpeg .mp1 .mp2 .mp3 .mpg .mpeg
AddType audio/ogg .oga .ogg
AddType audio/wav .wav
AddType audio/webm .webm
AddType video/mp4 .mp4 .m4v
AddType video/ogg .ogv
AddType video/webm .webm
Following this answer I added two lines so that the whole file now looks like this:
RewriteEngine On
# This will enable the Rewrite capabilities
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
###### I ADDED THESE TWO LINESBELOW ######
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
AddType audio/aac .aac
AddType audio/mp4 .mp4 .m4a
AddType audio/mpeg .mp1 .mp2 .mp3 .mpg .mpeg
AddType audio/ogg .oga .ogg
AddType audio/wav .wav
AddType audio/webm .webm
AddType video/mp4 .mp4 .m4v
AddType video/ogg .ogv
AddType video/webm .webm
But it still doesn't redirect medify.eu/nl/ to medify.eu/nl. Any ideas what I'm doing wrong?
A: To remove a trailing slash using .htaccess you can use:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
Make sure you clear your cache before testing this. After testing with your website, the output result:
| |
doc_23538708
|
I am sharing my code from template :
<div class="form-group" v-for="(input,k) in data.invoice_product" :key="k">
<div class="row mb-2">
<div class="col-md-3">
<select class="form-control" v-model="data.invoice_product.product_id"
@change="getProductCost">
<option v-for="(product, i) in products" :key="i" :value="product.id">{{
product.product_name }}</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" placeholder="Quantity" v-
model="data.invoice_product.quantity" @keyup="getProductCost">
</div>
<div class="col-md-3">
<input type="text" class="form-control" placeholder="Total" v-
model="data.invoice_product.total">
</div>
<div class="col-md-3">
<span>
<i class="fa fa-minus-circle" @click="removeElement(k)" v-show="k || ( !k
&& data.invoice_product.length > 1)">Remove</i>
<i class="fa fa-plus-circle" @click="addElement(k)" v-show="k ==
data.invoice_product.length-1">Add fields</i>
</span>
</div>
</div>
</div>
from my script (I am excluding irrelevant code segments) :
export default {
data() {
return {
data : {
customer_id : '',
vat : ''
},
inputs: [{
product_id : '',
quantity : '',
total : ''
}],
input: {
product_id : '',
quantity : '',
total : ''
},
products : []
}
},
methods : {
getProductCost() {
axios.get('/api/product-cost?
product_id='+this.item.product_id+'&&quantity='+this.item.quantity,
this.data).then(response => {
this.input.total = response.data
})
},
addElement() {
this.data.invoice_product.push({
product_id : '',
quantity : '',
total : ''
})
},
removeElement (index) {
this.data.invoice_product.splice(index, 1)
},
}
Input returns null if I use "input" instead :
A: The problem is not providing correct data to v-model.
Here, you make an iteration, where you get "input" as an element.
<div class="form-group" v-for="(input,k) in data.invoice_product" :key="k">
But here, you are providing "data.invoice_product" instead of "input".
<select class="form-control" v-model="data.invoice_product.product_id"
@change="getProductCost">
Just change "data.invoice_product.product_id" to "input.product_id", and also do it for other inputs.
A: You are already looping through data.invoice_product with this
<div class="form-group" v-for="(input,k) in data.invoice_product"> .... </div>
so the v-model on your select tag should be
<select v-model="input.product_id"> .... </select>
instead of
<select v-model="data.invoice_product.product_id"> .... </select>
Similar case for your input tags for Quantity and Total.
So, the code in your template should be something like this:
<div class="form-group" v-for="(input,k) in data.invoice_product" :key="k">
<div class="row mb-2">
<div class="col-md-3">
<select class="form-control" v-model="input.product_id"
@change="getProductCost">
<option v-for="(product, i) in products" :key="i" :value="product.id">{{
product.product_name }}</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" placeholder="Quantity" v-
model="input.quantity" @keyup="getProductCost">
</div>
<div class="col-md-3">
<input type="text" class="form-control" placeholder="Total" v-
model="input.total">
</div>
<div class="col-md-3">
<span>
<i class="fa fa-minus-circle" @click="removeElement(k)" v-show="k || ( !k
&& data.invoice_product.length > 1)">Remove</i>
<i class="fa fa-plus-circle" @click="addElement(k)" v-show="k ==
data.invoice_product.length-1">Add fields</i>
</span>
</div>
</div>
</div>
[Updated]
Your scripts should be left as it was before:
export default {
data() {
return {
data : {
customer_id : '',
vat : '',
invoice_product: [{
product_id : '',
quantity : '',
total : ''
}],
},
input: {
product_id : '',
quantity : '',
total : ''
},
products : []
}
},
methods : {
addElement() {
this.data.invoice_product.push(this.input)
},
removeElement (index) {
this.data.invoice_product.splice(index, 1)
},
}
| |
doc_23538709
|
I'm having problems understanding how to get the value of key date from this JSON.
So far, I thought maybe a double nested for loop to push an array with the values of concerts, and they iterate using map. But still, the content of concerts is an Objects (why is so hard in React this? btw)
Can anyone give me a hand here?
I really want to learn how to get pair key value from objects inside an array.
thanks in advance!
Here's my JSON.
[
{
"id": "1",
"name": "Blooming Fluorescence",
"year": "2022",
"concerts": [
{
"1": {
"date": "15/11/2022",
"place": "sssss)",
"ensemble": {
"name": "rtyuaize",
"Players": [
"Flute: OIUYT",
"Oboe: OIUY",
"C.B.Clarinet: 456789",
"Accordion: KJHGF",
"Violoncello: FGHJK"
]
},
"program": "",
"FacebookEvent": "sssss",
"poster": ""
}
},
{
"2": {
"date": "27/01/2023",
"place": "Rübühne, Esse (DE)",
"ensemble": {
"name": "xxxxx",
"Players": [
"Flute: xxxxxx",
"Oboe: xxxxxx",
"C.B.Clarinet: xxxxxx",
"Accordion: xxxxxx",
"Violoncello: xxxxxx"
]
}
}
}
],
"instruments": "B.Fl, Ob, C.B.Cl, Acc, Vc",
"electronics": true,
"score": {
"fullScore": "",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": true,
"category": "chamber music",
"video_by": "xxxxxx",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
},
{
"id": "2",
"name": "Paradise (lush sensitivity digitally designed)",
"year": "2022",
"categeory": "solo",
"concerts": [
{
"1": {
"date": "28/03/2022",
"place": "Centre Culturel Italien, Paris (FR)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
},
"program": "",
"FacebookEvent": "",
"poster": ""
}
},
{
"2": {
"date": "24/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
},
{
"3": {
"date": "25/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
}
],
"instruments": "Sheng (37 reed)",
"electronics": true,
"score": {
"fullScore": "xxxxxx",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": false,
"video_by": "",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
}
]
A: A few flatMaps and Object.values will do it
const dates = data.flatMap(obj => obj.concerts.flatMap(concert => Object.values(concert).map(obj => obj.date)))
const data = [
{
"id": "1",
"name": "Blooming Fluorescence",
"year": "2022",
"concerts": [
{
"1": {
"date": "15/11/2022",
"place": "sssss)",
"ensemble": {
"name": "rtyuaize",
"Players": [
"Flute: OIUYT",
"Oboe: OIUY",
"C.B.Clarinet: 456789",
"Accordion: KJHGF",
"Violoncello: FGHJK"
]
},
"program": "",
"FacebookEvent": "sssss",
"poster": ""
}
},
{
"2": {
"date": "27/01/2023",
"place": "Rübühne, Esse (DE)",
"ensemble": {
"name": "xxxxx",
"Players": [
"Flute: xxxxxx",
"Oboe: xxxxxx",
"C.B.Clarinet: xxxxxx",
"Accordion: xxxxxx",
"Violoncello: xxxxxx"
]
}
}
}
],
"instruments": "B.Fl, Ob, C.B.Cl, Acc, Vc",
"electronics": true,
"score": {
"fullScore": "",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": true,
"category": "chamber music",
"video_by": "xxxxxx",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
},
{
"id": "2",
"name": "Paradise (lush sensitivity digitally designed)",
"year": "2022",
"categeory": "solo",
"concerts": [
{
"1": {
"date": "28/03/2022",
"place": "Centre Culturel Italien, Paris (FR)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
},
"program": "",
"FacebookEvent": "",
"poster": ""
}
},
{
"2": {
"date": "24/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
},
{
"3": {
"date": "25/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
}
],
"instruments": "Sheng (37 reed)",
"electronics": true,
"score": {
"fullScore": "xxxxxx",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": false,
"video_by": "",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
}
]
const dates = data.flatMap(obj => obj.concerts.flatMap(concert => Object.values(concert).map(obj => obj.date)))
console.log(dates)
But I have to say that this structure is a nonsense
You have an array which has objects with one property (1, 2, etc.) this is not ok
Removing the unnecessary nesting will makes things easier:
[
{
"id": "1",
"name": "Blooming Fluorescence",
"year": "2022",
"concerts": [
{
"date": "15/11/2022",
"place": "sssss)",
"ensemble": {
"name": "rtyuaize",
"Players": [
"Flute: OIUYT",
"Oboe: OIUY",
"C.B.Clarinet: 456789",
"Accordion: KJHGF",
"Violoncello: FGHJK"
]
},
"program": "",
"FacebookEvent": "sssss",
"poster": ""
},
{
"date": "27/01/2023",
"place": "Rübühne, Esse (DE)",
"ensemble": {
"name": "xxxxx",
"Players": [
"Flute: xxxxxx",
"Oboe: xxxxxx",
"C.B.Clarinet: xxxxxx",
"Accordion: xxxxxx",
"Violoncello: xxxxxx"
]
}
}
],
"instruments": "B.Fl, Ob, C.B.Cl, Acc, Vc",
"electronics": true,
"score": {
"fullScore": "",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": true,
"category": "chamber music",
"video_by": "xxxxxx",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
},
{
"id": "2",
"name": "Paradise (lush sensitivity digitally designed)",
"year": "2022",
"categeory": "solo",
"concerts": [
{
"date": "28/03/2022",
"place": "Centre Culturel Italien, Paris (FR)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
},
"program": "",
"FacebookEvent": "",
"poster": ""
},
{
"date": "24/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
},
{
"date": "25/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
],
"instruments": "Sheng (37 reed)",
"electronics": true,
"score": {
"fullScore": "xxxxxx",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": false,
"video_by": "",
"prizes": [],
"press": [
{
"blog": {
"language": "",
"link": ""
}
}
]
}
]
const data = [{
"id": "1",
"name": "Blooming Fluorescence",
"year": "2022",
"concerts": [{
"date": "15/11/2022",
"place": "sssss)",
"ensemble": {
"name": "rtyuaize",
"Players": [
"Flute: OIUYT",
"Oboe: OIUY",
"C.B.Clarinet: 456789",
"Accordion: KJHGF",
"Violoncello: FGHJK"
]
},
"program": "",
"FacebookEvent": "sssss",
"poster": ""
},
{
"date": "27/01/2023",
"place": "Rübühne, Esse (DE)",
"ensemble": {
"name": "xxxxx",
"Players": [
"Flute: xxxxxx",
"Oboe: xxxxxx",
"C.B.Clarinet: xxxxxx",
"Accordion: xxxxxx",
"Violoncello: xxxxxx"
]
}
}
],
"instruments": "B.Fl, Ob, C.B.Cl, Acc, Vc",
"electronics": true,
"score": {
"fullScore": "",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": true,
"category": "chamber music",
"video_by": "xxxxxx",
"prizes": [],
"press": [{
"blog": {
"language": "",
"link": ""
}
}]
},
{
"id": "2",
"name": "Paradise (lush sensitivity digitally designed)",
"year": "2022",
"categeory": "solo",
"concerts": [{
"date": "28/03/2022",
"place": "Centre Culturel Italien, Paris (FR)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
},
"program": "",
"FacebookEvent": "",
"poster": ""
},
{
"date": "24/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
},
{
"date": "25/12/2022",
"place": "C-Lab (TW)",
"ensemble": {
"name": "xxxxxx",
"Players": [
"Sheng: xxxxxx",
"Electronics: xxxxxx"
]
}
}
],
"instruments": "Sheng (37 reed)",
"electronics": true,
"score": {
"fullScore": "xxxxxx",
"Parts": ""
},
"lnks": {
"youtube": [],
"soundcloud": [],
"spotify": []
},
"commission": "",
"video": false,
"video_by": "",
"prizes": [],
"press": [{
"blog": {
"language": "",
"link": ""
}
}]
}
]
const dates = data.flatMap(obj => obj.concerts.flatMap(concert => concert.date))
console.log(dates)
| |
doc_23538710
|
This number should not contain all repeating digits.
i.e, I have to validate if the user enters a number like (999) 999-9999. But should allow any other format.
How to write a regular expression for this.
Please help.
Thanks,
Siri
A: To validate a North American style phone number you could use:
\(?\d{3}\)?[- ]?\d{3}-?\d{4}
This allows the repeating digits. To filter those out, you could run a second regex that uses backreferences to validate all the following digits match the first digit match. Here is a regex with phone formatting optional:
\(?(\d)\1\1\)?[- ]?\1{3}-?\1{4}
A: Try this one:
(\(\d{3}\) \d{3}-\d{4})
Prove here: Regex101
Note that there has to be \ between every bracket (). Otherwise they are interpreted as a capturing group.
| |
doc_23538711
|
C:\dev\OpenCMS\Website\Frontend\Scripts\libs\sinnovations>tsc
sinnovations.listv iewbase.ts --module amd
C:/dev/OpenCMS/Website/Frontend/Scripts/libs/sinnovations/sinnovations.listviewb
ase.ts(11,5): error TS2025: Public property 'columns' of exported
class has or i s using private type 'KnockoutObservableArray'.
/// <reference path="../../typings/knockout/knockout.d.ts" />
import ko = require('knockout');
interface Column {
label: string;
}
var _templateBase = '/Frontend/Templates/ListView/';
class ListViewBase<T> {
columns: KnockoutObservableArray<Column> = ko.observableArray([]);
rows: KnockoutObservableArray<T> = ko.observableArray([]);
constructor(public templateHeaderRow = _templateBase+'DefaultTableHeaderTemplate', public templateBodyRow = _templateBase + 'DefaultTableRowTemplate') {
}
addColumn(column: Column) {
this.columns.push(column);
}
addRow(row: T) {
this.rows.push(row);
}
static configure(templateBase) {
_templateBase = templateBase;
}
}
export = ListViewBase;
I understand the error, but dont know how else to get the effect of above. Anyone have a solution to export some interfaces along a class that is exported as export = class?
A: I am afraid you need to define the interface in another file. e.g.
a.ts:
interface Column {
label: string;
}
and your code :
/// <reference path="../../typings/knockout/knockout.d.ts" />
/// <reference path="./a.ts" />
import ko = require('knockout');
var _templateBase = '/Frontend/Templates/ListView/';
class ListViewBase<T> {
columns: KnockoutObservableArray<Column> = ko.observableArray([]);
rows: KnockoutObservableArray<T> = ko.observableArray([]);
constructor(public templateHeaderRow = _templateBase+'DefaultTableHeaderTemplate', public templateBodyRow = _templateBase + 'DefaultTableRowTemplate') {
}
addColumn(column: Column) {
this.columns.push(column);
}
addRow(row: T) {
this.rows.push(row);
}
static configure(templateBase) {
_templateBase = templateBase;
}
}
export = ListViewBase;
| |
doc_23538712
|
max4ReceiveSize = 9216;
max6ReceiveSize = 9216;
Is there another setting?
Edit:
I discovered that the GCDAsyncUdpSocket class did provide a method to set this value called setMaxReceiveIPv4BufferSize. Tried that but it still only received at around 9216 bytes.
A: It would help to know exactly which operating system you are on, as the settings vary. On OS X 10.6, look at:
# sysctl net.inet.udp.maxdgram
net.inet.udp.maxdgram: 9216
However, you must keep in mind that the maximum transmit unit (MTU) of any data path will be determined by the smallest value supported by any device in the path. In other words, if just one device or software rule refuses to handle datagrams larger than a particular size, then that will be the limit for that path. Thus there could be many settings on many devices which affect this. Also note that the MTU rules for IPv4 and IPv6 are radically different, and some routers have different rules for multicast versus unicast.
In general, it is not safe to assume that any IP datagram larger than a total of 576 bytes (including all protocol headers) will be allowed through, as 576 the maximum IP packet size which IPv4 guarantees will be supported. For IPv6, the guaranteed size is 1280. Most devices will support larger packets, but they are not required to.
| |
doc_23538713
|
<html>
<head>
<script type="text/javascript">
function age(){
let x = document.getElementById('txtYear').value;
if(x.length == 0) {
alert("Numbers should be between 1970 and 2018");
return;
}
if(isNaN(x)){
alert("Value entered is not numeric");
return;
}
var age = 2018-parseInt(x);
document.getElementById('age').innerText="Your age in 2018 is "+age;
}
</script>
</head>
Enter Year of Birth: <input type="text" id="txtYear" />
<button onClick="age(txtYear.value)">Calculate Age</button>
<br><br>
<div id="age">
</div>
</body>
</html>
A: Find the code below, I just parsed the entered input to an integer and added a check that value should be between 1970 & 2018 inclusive. I also added the string as you asked.
function age(){
let x = document.getElementById('txtYear').value;
if(isNaN(x)){
alert("Value entered is not numeric");
return;
}
let num = parseInt(x)
if(x.length == 0 || num < 1970 || num > 2018) {
alert("Numbers should be between 1970 and 2018");
return;
}
var age = 2018-parseInt(x);
document.getElementById('age').innerText="Your age in 2018 is "+age+" years old";
}
<html>
<head>
</head>
Enter Year of Birth: <input type="text" id="txtYear" />
<button onClick="age(txtYear.value)">Calculate Age</button>
<br><br>
<div id="age">
</div>
</body>
</html>
A: you can use >/< to detect the number user inputed; and you can use + to concat strings continuously
and actually the year user inputed can not be greater than current year, so you can use (new Date()).getFullYear()
function age(){
let x = document.getElementById('txtYear').value;
if(x < 1970 || x > (new Date()).getFullYear()) {
alert("Numbers should be between 1970 and " + (new Date()).getFullYear());
return;
}
if(isNaN(x)){
alert("Value entered is not numeric");
return;
}
var age = 2018-parseInt(x);
document.getElementById('age').innerText="Your age in 2018 is "+age + " years old";
}
Enter Year of Birth: <input type="text" id="txtYear" />
<button onClick="age(txtYear.value)">Calculate Age</button>
<br><br>
<div id="age">
</div>
A: You could change the type of the input tag to "number" and set the min and/or max properties on it.
Instead of:
<input type="text" id="txtYear" />
Use:
<input type="number" min="1970" max="2017" id="txtYear" />
A: Best way is to use moment js. you can either use cdn from here https://cdnjs.com/libraries/moment.js/ or just download it
Here is a "dirty" simple snippet so you can understand it better:
var todayYear = moment(); // getting todays date as moment object
var input = "1980" //your sanitized string input from page
var inputYear = moment(input); // converterting string to moment object
var yearDifference = moment.duration(todayYear.diff(inputYear)); // moment does the math for you
var result = Math.floor(yearDifference.asYears()); // flooring moment object
alert(result);
A:
var calculateAge = function(birthday) {
var now = new Date();
var past = new Date(birthday);
if(past.getFullYear() < 1970 || past.getFullYear() > 2018) {
alert("Numbers should be between 1970 and 2018");
return;
}else{
var nowYear = now.getFullYear() -1;
var pastYear = past.getFullYear();
var age = nowYear - pastYear;
return age;
}
};
$('#age').submit(function(e) {
e.preventDefault();
var $birthday = $('#birthday').val();
alert('you are ' + calculateAge($birthday) + ' years old');
});
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form action="#" method="post" id="age">
<label for="birthday">Birthday (yyyy-mm-dd)
<input type="text" name="birthday" id="birthday" />
</label>
<input type="submit" name="submit" value="Calculate your age"/>
</form>
| |
doc_23538714
|
it's just running for one time only.
I want know is it possible if I have some exception in my delegate can it cause timer to misbehave?
How can I solve this problem?
This Timer runs throughout the lifecyle of application and stop only when application is stoped.
tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromMilliseconds(500);
tmr.Tick += delegate
{
FaceRecognizer_Advanced.GetInstance.GetFacesFromImage();
};
tmr.Start();
I expect this timer should get hit the way it suppose to be.
| |
doc_23538715
|
http://amdc.in2p3.fr/nubase/nubase2016.txt
I've cleaned it up the best I can but to cut a long story short I would like to space delimit most of each line and then fixed delimit the last column. i.e. ignore the spaces in the last section.
Cleaned Data Text File
Can anyone point me in the right direction of a resource which can do this? Not sure if Pandas copes with this?
Kenny
P.S. I have found some great resources to clean up the multiple whitespaces and replace the line breaks. Sorry can't find the original reference, so see attached.
fin = open("Input.txt", "rt")
fout = open("Ouput.txt", "wt")
for line in fin:
fout.write(re.sub(' +', ' ', line).strip() + "\n")
fin.close()
fout.close()
A: So what i would do is very simple, i would clean up the data as much as possible and then convert it to a csv file, because they are easy to use. An then i would step by step load it into a pandas dataframe and change if it needed.
with open("NudatClean.txt") as f:
text=f.readlines()
import csv
with open('dat.csv', 'w', newline='') as file:
writer = csv.writer(file)
for i in text:
l=i.split(' ')
row=[]
for a in l:
if a!='':
row.append(a)
print(row)
writer.writerow(row)
That should to the job for the beginning. But I don't know what you want remove exactly so I think the rest should be pretty clear.
A: The way I managed to do this was split the csv into two parts then recombine. Not particularly elegant but did the job I needed.
Split by Column
| |
doc_23538716
|
Please help in this regard. Below is my code
class UnionFind:
def __init__(self,v):
self.parent = [-1 for i in range(v)]
self.lis=[]
def addEdge(self,i,j):
self.lis.append([i,j])
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
self.findParent(self.parent[i])
def union(self,i,j):
self.parent[i]=j
def printResult(self):
print self.lis
def isBool(self):
for lisIter in self.lis:
x=self.findParent(lisIter[0])
y=self.findParent(lisIter[1])
if(x==y):
return True
self.union(x,y)
return False
uf = UnionFind(3)
uf.addEdge(0,1)
uf.addEdge(1,2)
uf.addEdge(2,0)
if uf.isBool():
print "The graph is cyclic"
else:
print "The graph is not cyclic"
A: Finally I got that little logic which I missed in the my code. I need to add the return statement in the else block of findParent method or else the returned value will be discarded and a none value will get returned. Uff!
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
return self.findParent(self.parent[i])
| |
doc_23538717
|
import Foundation
import SwiftUI
import WatchKit
final class ExtensionDelegate: NSObject, ObservableObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
NSLog("App launched")
}
func applicationWillTerminate() {
NSLog("App will terminate")
// trying to call this function but is not declared WKExtensionDelegate
}
func applicationDidEnterBackground() {
NSLog("App deactivated")
NotificationCenter.default.post(name: .appDeactivated, object: nil)
}
}
| |
doc_23538718
|
The goal I want to achieve is to
*
*read a CSV file (OK)
*encode it to Dataset<Person>, where Person
object has a nested object Address[]. (Throws an exception)
The Person CSV file
In a file called person.csv, there is the following data describing some persons:
name,age,address
"name1",10,"streetA~cityA||streetB~cityB"
"name2",20,"streetA~cityA||streetB~cityB"
The first line is the schema and address is a nested structure.
Data classes
The data classes are:
@Data
public class Address implements Serializable {
public String street;
public String city;
}
and
@Data
public class Person implements Serializable {
public String name;
public Integer age;
public Address[] address;
}
Reading untyped Data
I have tried first to read the data from the CSV in a Dataset<Row>, which works as expected:
Dataset<Row> ds = spark.read() //
.format("csv") //
.option("header", "true") // first line has headers
.load("src/test/resources/outer/person.csv");
LOG.info("=============== Print schema =============");
ds.printSchema();
root
|-- name: string (nullable = true)
|-- age: string (nullable = true)
|-- address: string (nullable = true)
LOG.info("================ Print data ==============");
ds.show();
+-----+---+--------------------+
| name|age| address|
+-----+---+--------------------+
|name1| 10|streetA~cityA||st...|
|name2| 20|streetA~cityA||st...|
+-----+---+--------------------+
LOG.info("================ Print name ==============");
ds.select("name").show();
+-----+
| name|
+-----+
|name1|
|name2|
+-----+
assertThat(ds.isEmpty(), is(false)); //OK
assertThat(ds.count(), is(2L)); //OK
final List<String> names = ds.select("name").as(Encoders.STRING()).collectAsList();
assertThat(names, hasItems("name1", "name2")); //OK
Encoding through a UserDefinedFunction
My udf that take a Stringand return an Address[]:
private static void registerAsAddress(SparkSession spark) {
spark.udf().register("asAddress", new UDF1<String, Address[]>() {
@Override
public Address[] call(String rowValue) {
return Arrays.stream(rowValue.split(Pattern.quote("||"), -1)) //
.map(object -> object.split("~")) //
.map(Address::fromArgs) //
.map(a -> a.orElse(null)) //
.toArray(Address[]::new);
}
}, //
DataTypes.createArrayType(DataTypes.createStructType(
new StructField[]{new StructField("street", DataTypes.StringType, true, Metadata.empty()), //
new StructField("city", DataTypes.StringType, true, Metadata.empty()) //
})));
}
The caller:
@Test
void asAddressTest() throws URISyntaxException {
registerAsAddress(spark);
// given, when
Dataset<Row> ds = spark.read() //
.format("csv") //
.option("header", "true") // first line has headers
.load("src/test/resources/outer/person.csv");
ds.show();
// create a typed dataset
Encoder<Person> personEncoder = Encoders.bean(Person.class);
Dataset<Person> typed = ds.withColumn("address2", //
callUDF("asAddress", ds.col("address")))
.drop("address").withColumnRenamed("address2", "address")
.as(personEncoder);
LOG.info("Typed Address");
typed.show();
typed.printSchema();
}
Which leads to this execption:
Caused by: java.lang.IllegalArgumentException: The value
(Address(street=streetA, city=cityA)) of the type
(ch.project.data.Address) cannot be
converted to struct
Why it cannot convert from Address to Struct?
A: After trying a lot of different ways and spending some hours researching over the Internet, I have the following conclusions:
UserDefinedFunction is good but are from the old world, it can be replaced by a simple map() function where we need to transform object from one type to another.
The simplest way is the following
SparkSession spark = SparkSession.builder().appName("CSV to Dataset").master("local").getOrCreate();
Encoder<FileFormat> fileFormatEncoder = Encoders.bean(FileFormat.class);
Dataset<FileFormat> rawFile = spark.read() //
.format("csv") //
.option("inferSchema", "true") //
.option("header", "true") // first line has headers
.load("src/test/resources/encoding-tests/persons.csv") //
.as(fileFormatEncoder);
LOG.info("=============== Print schema =============");
rawFile.printSchema();
LOG.info("================ Print data ==============");
rawFile.show();
LOG.info("================ Print name ==============");
rawFile.select("name").show();
// when
final SerializableFunction<String, List<Address>> asAddress = (String text) -> Arrays
.stream(text.split(Pattern.quote("||"), -1)) //
.map(object -> object.split("~")) //
.map(Address::fromArgs) //
.map(a -> a.orElse(null)).collect(Collectors.toList());
final MapFunction<FileFormat, Person> personMapper = (MapFunction<FileFormat, Person>) row -> new Person(row.name,
row.age,
asAddress
.apply(row.address));
final Encoder<Person> personEncoder = Encoders.bean(Person.class);
Dataset<Person> persons = rawFile.map(personMapper, personEncoder);
persons.show();
// then
assertThat(persons.isEmpty(), is(false));
assertThat(persons.count(), is(2L));
final List<String> names = persons.select("name").as(Encoders.STRING()).collectAsList();
assertThat(names, hasItems("name1", "name2"));
final List<Integer> ages = persons.select("age").as(Encoders.INT()).collectAsList();
assertThat(ages, hasItems(10, 20));
final Encoder<Address> addressEncoder = Encoders.bean(Address.class);
final MapFunction<Person, Address> firstAddressMapper = (MapFunction<Person, Address>) person -> person.addresses.get(0);
final List<Address> addresses = persons.map(firstAddressMapper, addressEncoder).collectAsList();
assertThat(addresses, hasItems(new Address("streetA", "cityA"), new Address("streetC", "cityC")));
A: use Row instead of java class in your udf
public static UDF1<String, Row> personParseUdf = new UDF1<String, Row>() {
@Override
public Row call(String s) throws Exception {
PersonEntity personEntity = PersonEntity.parse(s);
List<Row> rowList = new ArrayList<>();
for (AddressEntity addressEntity : personEntity.getAddress()) {
// use row instead of java class
rowList.add(RowFactory.create(addressEntity.getStreet(), addressEntity.getCity()));
}
return RowFactory.create(personEntity.getName(), personEntity.getAge(), rowList);
}
};
to see detail: https://cloud.tencent.com/developer/article/1674399
| |
doc_23538719
|
I herd and read that, SMTP protocol is used for e-mails. If I am correct, when exactly are these email systems use the SMTP protocol?.
Why can't I see the SMTP/S port on wireshark dump of my webmail?
Can the terms WWW and Internet be used interchangeably?
A: Because Gmail uses web interface. And there is no other alternative or option than http/s to interact with the mail servers. Also web interface does not fetch mails directly from the mail server. Rather it uses API provided by another server than mail to read or send e-mails.
If you use another mail client than Google’s web interface (Gmail) for e-mail, like Thunderbird, Outlook etc., then it requires SMTP/POP or IMAP protocol interface to get/ send emails.
HTTPS is a secured interface over HTTP to encrypt packets so there is nothing to do with e-mails I think its the primary reason why google uses HTTPS.
A: What you use in your browser is a web application. A front-end (a client) for the mail service.
SMTP is a protocol for sending mails. For retrieving there are other protocols like POP3 or IMAP.
So when you open the service like Gmail basically you connect to a server hosting a front-end part. It in turn calls to underlying mail services like IMAP to show you your emails.
When you send the mail it calls underlying SMTP service.
If you need to configure your clients to connect directly to SMTP/IMAP infrastructure of Gmail you can use this instruction.
| |
doc_23538720
|
In other words: when a key is defined already, the original value should be kept and not replaced.
My use case is to load libs in a monorepo with their own translation-files. The lib translations should be defaults, but the translations defined in the app (and loaded originally), should have a higher priority and override those in the libs.
when calling setTranslation with shouldMerge = true, the new translation always replaces the old one.
| |
doc_23538721
|
So, what I need:
I have HTML structure for parsing like that:
<div class="foo">
<div class='bar' dir='ltr'>
<div id='p1' class='par'>
<p class='sb'>
<span id='dc_1_1' class='dx'>
<a href='/bar32560'>1</a>
</span>
Neque porro
<a href='/xyz' class='mr'>+</a>
quisquam est
<a href='/xyz' class='mr'>+</a>
qui.
</p>
</div>
<div id='p2' class='par'>
<p class='sb'>
<span id='dc_1_2' class='dx'>
<a href='/foo12356'>2</a>
</span>
dolorem ipsum
<a href='/xyz' class='mr'>+</a>
quia dolor sit amet,
<a href='/xyz' class='mr'>+</a>
consectetur, adipisci velit.
</p>
</div>
<div id='p3' class='par'>
<p class='sb'>
<span id='dc_1_3' class='dx'>
<a href='/foobar4586'>3</a>
</span>
Neque porro quisquam
<a href='/xyz' class='mr'>+</a>
est qui dolorem ipsum quia dolor sit
<a href='/xyz' class='mr'>+</a>
amet, t.
<a href='/xyz' class='mr'>+</a>
<span id='dc_1_4' class='dx'>
<a href='/barefoot4135'>4</a>
</span>
consectetur,
<a href='/xyz' class='mr'>+</a>
adipisci veli.
<span id='dc_1_5' class='dx'>
<a href='/barfoo05123'>5</a>
</span>
Neque porro
<a href='/xyz' class='mr'>+</a>
quisquam est
<a href='/xyz' class='mr'>+</a>
qui.
</p>
</div>
</div>
</div>
What I need (IN ENGLISH): scrape each paragraph BUT I need final scraped text object content in form:
scraped_body 1 => 1 Neque porro quisquam est qui.
scraped_body 2 => 2 dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
scraped_body 3 => 3 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t.
scraped_body 4 => 4 consectetur, adipisci veli.
scraped_body 5 => 5 Neque porro quisquam est qui.
Code what i use for now:
page = Nokogiri::HTML(open(url))
x = page.css('.mr').remove
x.xpath("//div[contains(@class, 'par')]").map do |node|
body = node.text
end
My result is like:
scraped_body 1 => 1 Neque porro quisquam est qui.
scraped_body 2 => 2 dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
scraped_body 3 => 3 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t. 4 consectetur, adipisci veli. 5 Neque porro quisquam est qui.
So this scrape whole text from div paragraph class 'par'. I need to scrape whole text after each span with his content - numbers. Or cut those div's before each span.
I need something like:
SPAN.text + P.text - a.mr
I dunno… how to do this
Please help me with this parsing. I need scrape after/before each span - I guess.
Please help, I've tried everything what i found.
EDIT DUCK @Duck1337:
I use followed code:
def verses
page = Nokogiri::HTML(open(url))
i=0
x = page.css("p").text.gsub("+", " ").split.join(" ").gsub(". ", ". HAM").split(" HAM").map do |node|
i+=1
body = node
VerseSource.new(body, book_num, number, i)
end
end
I need this because I parse a big website with text. There is few more methods. So my final output looks like:
Saved record with: book: 1, chapter: 1, verse: 1, body: 1 Neque porro quisquam est qui.
But if I have single werse with multiple sentences then your code split it by every sentence. So this is to much split.
For example:
<div id='p1' class='par'>
<p class='sb'>
<span id='dc_1_3' class='dx'>
<a href='/foobar4586'>1</a>
</span>
Neque porro quisquam. Est qui dolorem
<a href='/xyz' class='mr'>+</a>
<span id='dc_1_3' class='dx'>
<a href='/foobar4586'>2</a>
</span>
est qui dolorem ipsum quia dolor sit.
<a href='/xyz' class='mr'>+</a>
amet, t.
Your code split like that:
Saved record with: book: 1, chapter: 1, verse: 1, body: 1 Neque porro quisquam.
Saved record with: book: 1, chapter: 1, verse: 2, body: Est qui dolorem
Saved record with: book: 1, chapter: 1, verse: 3, body: 2 est qui dolorem ipsum quia dolor sit.
Hope you what I mean. Really BIG Thanks to you for that. If you can modify this it will be great!
EDIT: @KARDEIZ
Thanks for answer! When I use your code inside of my method: It parsed really radom stuff.
def verses
page = Nokogiri::HTML(open(url))
i=0
#page.css(".mr").remove
page.xpath("//div[contains(@class, 'par')]//span").map do |node|
node.content.strip.tap do |out|
while nn = node.next
break if nn.name == 'span'
out << ' ' << nn.content.strip if nn.text? && !nn.content.strip.empty?
node = nn
end
end
i+=1
body = node
VerseSource.new(body, book_num, number, i)
end
end
The output is like:
Saved record with: book: 1, chapter: 1, verse: 1, body: <here is last part of last sentence in first paragraph after "+" sign(href) and before last "+"(href)>
Saved record with: book: 1, chapter: 1, verse: 2, body: <here is last part of last sentence in second paragraph after "+" sign(href) and before last "+"(href)>
Saved record with: book: 1, chapter: 1, verse: 3, body:
Saved record with: book: 1, chapter: 1, verse: 4, body:
Saved record with: book: 1, chapter: 1, verse: 5, body: <here is last sentence in third paragraph. It is after last "+" in this paragraph and have no more "+" signs(href)
As you can see, I dunno how it make such a mess ;] Can you do something more with that? Thanks a lot!
Regards!
A: I saved your input as "temp.html" on my desktop.
require 'open-uri'
require 'nokogiri'
$page_html = Nokogiri::HTML.parse(open("/home/user/Desktop/temp.html"))
output = $page_html.css("p").text.gsub("+", " ").split.join(" ").gsub(". ", ". HAM").split(" HAM")
# I found the pattern ". " in every line, so i replaced ". " with (". HAM")
# I did that by using gsub(". ", ". HAM") this means replace ". " with ". HAM"
# then i split up the string with " HAM" so it preserved the "." in each item in the array
output = ["1 Neque porro quisquam est qui.", "2 dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.", "3 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t.", "4 consectetur, adipisci veli.", "5 Neque porro quisquam est qui."]
EDIT:
%w[nokogiri open-uri].each{|gem| require gem}
$url = "/home/user/Desktop/temp.html"
def verses
page = Nokogiri::HTML(open($url))
i=0
x = page.css("p").text.gsub("+", " ").split.join(" ").gsub(". ", ". HAM").split(" HAM") do |node|
i+=1
body = node
VerseSource.new(body, book_num, number, i)
end
end
A: Try something like:
x.xpath("//div[contains(@class, 'par')]//span").map do |node|
out = node.content.strip
if following = node.at_xpath('following-sibling::text()')
out << ' ' << following.content.strip
end
out
end
The following-sibling::text() XPATH will get the first text node after the span.
EDIT
I think this does what you want:
html.xpath("//div[contains(@class, 'par')]//span").map do |node|
node.content.strip.tap do |out|
while nn = node.next
break if nn.name == 'span'
out << ' ' << nn.content.strip if nn.text? && !nn.content.strip.empty?
node = nn
end
end
end
outputs:
[
"1 Neque porro quisquam est qui.",
"2 dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.",
"3 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t.",
"4 consectetur, adipisci veli.",
"5 Neque porro quisquam est qui."
]
It's also possible to do this with pure XPath (see XPath axis, get all following nodes until), but this solution is more simple from a coding perspective.
EDIT 2
Try this:
def verses
page = Nokogiri::HTML(open(url))
i=0
page.xpath("//div[contains(@class, 'par')]//span").map do |node|
body = node.content.strip.tap do |out|
while nn = node.next
break if nn.name == 'span'
out << ' ' << nn.content.strip if nn.text? && !nn.content.strip.empty?
node = nn
end
end
i+=1
VerseSource.new(body, book_num, number, i)
end
end
A: require 'nokogiri'
your_html =<<END_OF_HTML
<your html here>
END_OF_HTML
doc = Nokogiri::HTML(your_html)
text_nodes = doc.xpath("//div[contains(@class, 'par')]/p/child::text()")
results = text_nodes.reject do |text_node|
text_node.text.match /\A \s+ \z/x #Eliminate whitespace nodes
end
results.each_with_index do |node, i|
puts "scraped_body#{i+1} => #{node.text.strip}"
end
--output:--
scraped_body1 => Neque porro quisquam est qui.
scraped_body2 => dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.
scraped_body3 => Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t.
scraped_body4 => consectetur, adipisci veli.
scraped_body5 => Neque porro quisquam est qui.
Answer for new html:
require 'nokogiri'
html = <<END_OF_HTML
your new html here
END_OF_HTML
html_doc = Nokogiri::HTML(html)
current_group_number = nil
non_ws_text = [] #non_whitespace_text for each group
html_doc.css("div.par > p").each do |p| #p's that are direct children of <div class="par">
p.xpath("./node()").each do |node| #All Text and Element nodes that are direct children of p tag.
case node
when Nokogiri::XML::Element
if node.name == 'span'
node.xpath(".//a").each do |a| #Step through all the <a> tags inside the <span>
md = a.text.match(/\A (\d+) \z/xm) #Check for numbers
if md #Then found a number, so it's the start of the next group
if current_group_number #then print the results for the current group
print "scraped_body #{current_group_number} => "
puts "#{current_group_number} #{non_ws_text.join(' ')}"
non_ws_text = []
end
current_group_number = md[1] #Record the next group number
break #Only look for the first <a> tag containing a number
end
end
end
when Nokogiri::XML::Text
text = node.text
non_ws_text << text.strip if text !~ /\A \s+ \z/xm
end
end
end
#For the last group:
print "scraped_body #{current_group_number} => "
puts "#{current_group_number} #{non_ws_text.join(' ')}"
--output:--
scraped_body 1 => 1 Neque porro quisquam est qui.
scraped_body 2 => 2 dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.
scraped_body 3 => 3 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, t.
scraped_body 4 => 4 consectetur, adipisci veli.
scraped_body 5 => 5 Neque porro quisquam est qui.
| |
doc_23538722
|
How can I fix it?
Here is my code:
import tweepy
import time
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)
users = [1432834552028962816, 1170672149616615424, 1432600808542117889]
for person in users:
user = api.get_user(id=person)
print(user.id)
api.create_friendship(user.id)
I do not get any error, the code finishes succesfully, but when I check, it only followed the last 2 ids and not the first. Why? and how to fix it?
| |
doc_23538723
|
$ apk add pkg
in an alpine linux based container that isn't starting up.
Can anyone tell what is wrong with the following commands.
$ docker run --rm --entrypoint myimage:mytag 'apk add wget curl vim lynx'
docker: invalid reference format.
See 'docker run --help'.
$ docker run --rm myimage:mytag --entrypoint 'apk add wget curl vim lynx'
container_linux.go:262: starting container process caused "exec: \"--entrypoint\": executable file not found in $PATH"
docker: Error response from daemon: oci runtime error: container_linux.go:262: starting container process caused "exec: \"--entrypoint\": executable file not found in $PATH".
$ docker run --rm myimage:mytag --entrypoint '/sbin/apk add wget curl vim lynx'
container_linux.go:262: starting container process caused "exec: \"--entrypoint\": executable file not found in $PATH"
docker: Error response from daemon: oci runtime error: container_linux.go:262: starting container process caused "exec: \"--entrypoint\": executable file not found in $PATH".
$ docker run --rm --entrypoint "apk" myimage:mytag 'add wget curl vim lynx'
apk-tools 2.7.5, compiled for x86_64.
usage: apk COMMAND [-h|--help] [-p|--root DIR]
[-X|--repository REPO] [-q|--quiet]
A: Your last attempt was almost correct syntax. You just need to remove the quotes around the arguments.
docker run --rm --entrypoint apk myimage:mytag add wget curl vim lynx
ash-3.2$ docker run --rm --entrypoint apk alpine add wget curl vim lynx
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/community/x86_64/APKINDEX.tar.gz
(1/12) Installing ca-certificates (20191127-r2)
(2/12) Installing nghttp2-libs (1.40.0-r1)
(3/12) Installing libcurl (7.67.0-r0)
(4/12) Installing curl (7.67.0-r0)
(5/12) Installing gzip (1.10-r0)
(6/12) Installing ncurses-terminfo-base (6.1_p20200118-r4)
(7/12) Installing ncurses-libs (6.1_p2020
| |
doc_23538724
|
that there is an increase in height of navigation bar, and there is a search bar in the middle and a home button to the left and a help button to the right.country and account access on the the top right aside to the help button. I want to make this navigation bar available in all screens in my application.
Please ask me if you need anymore information regarding the question.
A: Try using following steps:
*
*Hide your navigation bar.
*Add UIView with same frame as Navigation bar (0, 0, 320, 64)
*Use UIButton instead of BarButtonItem and UILabel in place of navigation titlebar
*And your customised navigation bar design is ready!!
*Now set actions on Left button to perform pop operation.
Try and let me know, if you can’t do it.
| |
doc_23538725
|
However, unless logged into the game Bin Weevils, the contents of the page will simply be failed=99.
I used the free Chrome extension EditThisCookie to find out which cookie out of the ones that are set when you log into Bin Weevils is required to view the page and discovered that it is the cookie PHPSESSID. I have attempted to set this cookie in the cURL header, but with no avail - failed=99 is still displayed in the output.
This is the cURL code which I am currently using:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'PHPSESSID: removed for privacy'
));
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
If I visit the page when not signed in to Bin Weevils and simply use EditThisCookie to set the cookie PHPSESSID, the page content shows.
A: To achieve these things first you need to authenticate using user name and password via cURL.
Step:1)
First login using cURL and retrieve cookies and store in a text file.
Step:2)
Using that cookie you can scrape that html page.
For detail example please follow these link Scrape Page using CURL after login.
A: Login to website with cURL and get secure page content
//The username of the account.
define('USERNAME', 'jellylion350');
//The password of the account.
define('PASSWORD', '123456');
//Set a user agent. This basically tells the server that we are using Chrome ;)
define('USER_AGENT', 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36');
//Where our cookie information will be stored (needed for authentication).
define('COOKIE_FILE', 'cookie.txt');
//URL of the login form.
define('LOGIN_FORM_URL', 'https://play.binweevils.com/game.php');
//Login action URL. Sometimes, this is the same URL as the login form.
define('LOGIN_ACTION_URL', 'https://www.binweevils.com/membership/payment/login');
//An associative array that represents the required form fields.
//You will need to change the keys / index names to match the name of the form
//fields.
$postValues = array(
'userID' => USERNAME,
'password' => PASSWORD
);
//Initiate cURL.
$curl = curl_init();
//Set the URL that we want to send our POST request to. In this
//case, it's the action URL of the login form.
curl_setopt($curl, CURLOPT_URL, LOGIN_ACTION_URL);
//Tell cURL that we want to carry out a POST request.
curl_setopt($curl, CURLOPT_POST, true);
//Set our post fields / date (from the array above).
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postValues));
//We don't want any HTTPS errors.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//Where our cookie details are saved. This is typically required
//for authentication, as the session ID is usually saved in the cookie file.
curl_setopt($curl, CURLOPT_COOKIEJAR, COOKIE_FILE);
//Sets the user agent. Some websites will attempt to block bot user agents.
//Hence the reason I gave it a Chrome user agent.
curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT);
//Tells cURL to return the output once the request has been executed.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//Allows us to set the referer header. In this particular case, we are
//fooling the server into thinking that we were referred by the login form.
curl_setopt($curl, CURLOPT_REFERER, LOGIN_FORM_URL);
//Do we want to follow any redirects?
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
//Execute the login request.
curl_exec($curl);
//Check for errors!
if(curl_errno($curl)){
throw new Exception(curl_error($curl));
}
//We should be logged in by now. Let's attempt to access a password protected page
curl_setopt($curl, CURLOPT_URL, 'http://example.com');
//Use the same cookie file.
curl_setopt($curl, CURLOPT_COOKIEJAR, COOKIE_FILE);
//Use the same user agent, just in case it is used by the server for session validation.
curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT);
//We don't want any HTTPS / SSL errors.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//Execute the GET request and print out the result.
$result = curl_exec($curl);
$result = urldecode($result); //decode url
// get result as expected
$data = explode('&',$result);
$final_data =array();
foreach($data as $row){
$temp = explode('=',$row);
$final_data[$temp[0]] = $temp[1];
}
echo "<pre>";
print_r($final_data);
Output of page is as follow
[res] => 1
[idx] => ######## //hiden for security purpose
[weevilDef] => ############### //hiden for security purpose
[level] => 70
[tycoon] => 0
[lastLog] => 1970-01-01+00%3A00%3A00
[dateJoined] => 2015-02-09+11%3A07%3A00
[x] => y
`
For detail read this
| |
doc_23538726
|
list_id int user_id int dest_user_id int
1 10 20
2 10 24
3 10 33
4 11 10
TABLE users_avatar
avatar_id int user_id int webavatar_thumbnail
1 10 test.jpg
2 10 test2.jpg
3 20 test2.jpg
4 20 test11.jpg
TABLE users
user_id int nick varchar
10 kaka
20 caca
24 dada
33 roro
I need to query this three tables there is the logic, table users_community_relations wheen i put user_id = 10 for example i get results from same table column dest_user_id 20,24,33 each number represent user_id in next two tables, i would need to get all data from next two tables accordingly to 20,24,33 numbers from dest_user_id column. Sometimes table users_avatar does not hold any avatar for user in that case string from this table could be empty. Sometimes it holds more than two rows, in that case i would need to get only first one but ordered with avatar_id DESC users_avatar table.
A: This should work:
SELECT ucr.*, u.*, ua1.*
FROM users_community_relations ucr
LEFT JOIN users u
ON u.user_id = ucr.user_id
LEFT JOIN users_avatar ua1
ON ua1.user_id = u.user_id
LEFT JOIN users_avatar ua2
ON ua2.user_id = u.user_id AND ua2.avatar_id > ua1.avatar_id
WHERE ua2.avatar_id IS NULL
It uses joins to ensure we only return the user_avatar row with the highest avatar_id or NULL if there is no avatar.
| |
doc_23538727
|
Sometimes this uploads image and sometimes don't. And when it failed to upload image gives a Nil response.and sends some garbage value to server.
Here is my image upload method:
func UPLOD(){
let image = myImageView.image!
let serviceName = "http://192.168.80.21:8800/api/v1/upload/uploadfile"
var parameters = [String: AnyObject]()
parameters["Folder"] = "uploadfile" as AnyObject?
parameters["Filename"] = "demo\(self.currentTimeStamp)" as AnyObject?
parameters["Ext"] = "jpg" as AnyObject?
parameters["FileToUpload"] = image.jpegData(compressionQuality: 0.5) as AnyObject?
guard let token = UserDefaults.standard.string(forKey: "accesstoken") else {
return
}
print("Create button ACCESS KEY::::- \(token)")
let headers: HTTPHeaders = [
"x-access-token": token
]
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters {
if key == "FileToUpload" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "demo\(self.currentTimeStamp)",
mimeType: "image/jpg"
//_img.jpg
)
} else {
//Data other than image
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}}},
to: serviceName, method: .post, headers: headers) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
//print response.result
print(response.result.value as Any)
}
upload.responseJSON { [self] response in
if let Response = response.result.value as? [String : Any],
let myData = Response["data"] as? [String : Any],
let imgPath = myData["ImagePath"] {
imageUrl = imgPath as! String
print(imageUrl)
print("ImagePath --> ", imgPath)
responseURL = imageUrl
let defaults = UserDefaults.standard
defaults.setValue(imageUrl, forKey: "imageURL")
let key = defaults.object(forKey: "imageURL")
print(key as Any)
self.alamofireRequest(requestURL: "http://192.168.80.21:3204/api/product/create")
}
if let data = response.result.value {
let _ = JSON(data)
}
}
break
case .failure(let encodingError):
print(encodingError)
break
}
}
}
A: Swift 5.0
pod 'Alamofire', '~> 5.4'
func postImageData(url:String, param:[String:Any], img:Data) {
print("POST URL : ", url)
let header: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(img, withName: "image", fileName: "image", mimeType: "image/jpeg")
for (key,value) in param {
MultipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}, to: url, method: .post, headers: header).uploadProgress { (progress) in
print(progress.fractionCompleted)
} .responseJSON { response in
switch response.result {
case .success:
if let JSON = response.value as? [String: Any] {
let flag = JSON["flag"] as! Bool
let code = JSON["code"] as! Int
} else {
}
break
case .failure(let error):
if let data = response.data {
print("Response Error Line No. 265:- \(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)")
}
break
}
}
}
| |
doc_23538728
|
public IQueryable<T> Search<T>(Expression<Func<T, bool>> predicate)
where T : EntityObject
{
return _unitOfWork.ObjectSet<T>().AsExpandable().Where(predicate);
}
And another class which uses the IQueryable return value to subset the query in ways that are not possible using the Boolean LinqKit PredicateBuilder expressions:
public IQueryable<T> SubsetByUser<T>(IQueryable<T> set, User user)
where T : EntityObject
{
return set.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
arc => arc.GUID,
meta => meta.ElementGUID,
(arc, meta) => arc);
}
The problem here is that 'T' as EntityObject does not define GUID, so I can't use this. The natural response to this is to actually define the SubsetByUser() method to use a constraint with a GUID property:
public IQueryable<T> SubsetByUser<T>(IQueryable<T> set, User user)
where T : IHaveMetadata
{
return set.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
arc => arc.GUID,
meta => meta.ElementGUID,
(arc, meta) => arc);
}
But this doesn't work. I'm using LinqKit and the Expandable() method results in:
System.NotSupportedException: Unable to cast the type 'Oasis.DataModel.Arc' to
type 'Oasis.DataModel.Interfaces.IHaveMetadata'. LINQ to Entities only supports
casting Entity Data Model primitive types
I need an IQueryable to be returned. I can do a fake like this:
public IQueryable<T> SubsetByUser<T>(IQueryable<T> set, User user)
where T : EntityObject
{
return set.AsEnumerable()
.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
arc => arc.GUID,
meta => meta.ElementGUID,
(arc, meta) => arc)
.AsQueryable();
}
Which, of course, works, but which is also, of course, a bat-shit crazy thing to do. (The whole reason I want IQueryable is to not execute the query until we're final.
I've even tried this:
public IQueryable<T> SubsetByUser<T>(IQueryable<T> set, User user)
where T : EntityObject
{
return set.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
arc => arc.GetType().GetProperty("GUID").GetValue(arc,null),
meta => meta.ElementGUID,
(arc, meta) => arc);
}
Which uses reflection to get the Runs collection– working around the compiler error. I thought that was rather clever, but it results in the LINQ exception:
System.NotSupportedException: LINQ to Entities does not recognize the
method 'System.Object GetValue(System.Object, System.Object[])' method,
and this method cannot be translated into a store expression.
I could also try to change the search method:
public IQueryable<T> Search<T>(Expression<Func<T, bool>> predicate)
where T : IRunElement
{
return _unitOfWork.ObjectSet<T>().AsExpandable().Where(predicate);
}
But this won't compile of course because IRunElement is not an EntityObject, and ObjectSet constrains T as a class.
The final possibility is simply making all the parameters and return values IEnumerable:
public IEnumerable<T> SubsetByUser<T>(IEnumerable<T> set, User user)
where T : EntityObject
{
return set.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
arc => arc.GetType().GetProperty("GUID").GetValue(arc,null),
meta => meta.ElementGUID,
(arc, meta) => arc);
}
Which also works, but which, again, doesn't allow us to delay instantiation until the end.
So, it seems like there's little I can do to make this work without instantiating everything as an IEnumerable and then returning it using AsQueryable(). Is there some way I can put this together that I'm missing?
A: The natural response to this is to actually define the SubsetByUser() method to use a constraint with a GUID property:
...
But this doesn't work. I'm using LinqKit and the Expandable() method results in:
System.NotSupportedException: Unable to cast the type 'Oasis.DataModel.Arc' to
type 'Oasis.DataModel.Interfaces.IHaveMetadata'. LINQ to Entities only supports
casting Entity Data Model primitive types
You're very close with that. You can make this work if you use an ExpressionVisitor that removes all unnecessary casts (casts to a base type or an implemented interface) that are automatically generated.
public IQueryable<T> SubsetByUser<T>(IQueryable<T> set, User user)
where T : IHaveMetadata
{
Expression<Func<T, Guid>> GetGUID = arc => arc.GUID;
GetGUID = (Expression<Func<T, Guid>>)RemoveUnnecessaryConversions.Instance.Visit(GetGUID);
return set.Join(_searcher.Search<Metadatum>((o) => o.UserGUID == user.GUID),
GetGUID,
meta => meta.ElementGUID,
(arc, meta) => arc);
}
public class RemoveUnnecessaryConversions : ExpressionVisitor
{
public static readonly RemoveUnnecessaryConversions Instance = new RemoveUnnecessaryConversions();
protected RemoveUnnecessaryConversions() { }
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert
&& node.Type.IsAssignableFrom(node.Operand.Type))
{
return base.Visit(node.Operand);
}
return base.VisitUnary(node);
}
}
Alternatively, create the expression tree manually using the Expression.* functions, so that you can avoid including the cast in the first place.
| |
doc_23538729
|
[DEBUG] 2015-11-20 13:19:43.9444 Message type: 'MyAssembly.Messages.NewEmailEvent' could not be determined by a 'Type.GetType', scanning known messages for a match
The event definition looks like this.
namespace MyAssembly.Messages
{
public class NewEmailEvent
{
public Guid MessageId { get; set; }
public string Subject { get; set; }
public string Sender { get; set; }
// a few other fields
}
}
I am publishing the event using the following code.
m_Bus.Publish<NewEmailEvent>(msg => {
msg.MessageId = entry.MessageId;
msg.Subject = entry.Email.Subject;
msg.Sender = entry.Email.Sender.Name;
// more property assignments
});
I have the following routing configuration.
<MsmqTransportConfig InputQueue="Nsb_input" ErrorQueue="Nsb_errors" NumberOfWorkerThreads="1" MaxRetries="5" />
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
<UnicastBusConfig>
<MessageEndpointMappings>
<add Assembly="MyAssembly.Messages" Endpoint="NServiceBus.Service" />
</MessageEndpointMappings>
</UnicastBusConfig>
The event naming conventions are defined in code as follows.
busConfiguration.Conventions().DefiningEventsAs(
t => t.Assembly.GetName().Name.EndsWith(".Messages", StringComparison.InvariantCulture)
&& t.Name.EndsWith("Event", StringComparison.InvariantCulture));
The messages are correctly registered at startup.
[DEBUG] 2015-11-20 13:18:35.1345 Message definitions:
MessageType: MyAssembly.Messages.NewEmailEvent, Recoverable: True, TimeToBeReceived: Not set , Parent types: MyAssembly.Messages.NewEmailEvent
MessageType: NServiceBus.Scheduling.Messages.ScheduledTask, Recoverable: True, TimeToBeReceived: Not set , Parent types: NServiceBus.Scheduling.Messages.ScheduledTask
On the receiving end, I am subscribing to the event using the following code.
bus.Subscribe<NewEmailEvent>();
And using the following configuration.
<UnicastBusConfig>
<MessageEndpointMappings>
<add Assembly="MyAssembly.Messages" Endpoint="NServiceBus.Service" />
</MessageEndpointMappings>
</UnicastBusConfig>
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
The event naming conventions are the same as the service.
A: Your MessageEndpointMappings are the same for both publisher and subscriber - don't know if this is correct / makes a difference.
You have not defined any message or command conventions; only events.
busConfiguration.Conventions()
.DefiningMessagesAs(t => t.Namespace != null &&
t.Namespace.StartsWith("MyAssembly.Messages"))
.DefiningCommandsAs(t => t.Namespace != null &&
t.Namespace.StartsWith("MyAssembly.Commands"))
I think you need to do this if you're not using marker interfaces.
I think this is especially important within the subscriber.
You haven't included the code for your subscriber. Does it have a class that implements IHandleMessages<NewEmailEvent>?
Go back and look at the pub/sub example.
Check your config settings again. It doesn't look like you're using external files; the sections are directly in app.config
| |
doc_23538730
| ERROR: type should be string, got "https://jsfiddle.net/069bmfr0/\n<ul class=\"tabs-menu ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all\" role=\"tablist\">\n<li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab1')\">tab1</a></li>\n<li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab2')\">tab2</a></li>< \n<li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab3')\">tab3</a></li>\n<li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab4')\">tab4</a></li> \n</ul>\n\n.tabs-menu{text-align:justify;width:100%;background:grey;}\n.tabs-menu:after{content:'';display:inline-block;width:100%;}\n.tabs-menu li{display:inline-block;padding:10px;border-right:2px solid white;}\n.tabs-menu a{color:white;}\n\nWhere am I going wrong?\n\nA: CSS3 Flexbox will do that using display:flex in ul and flex:1 in li, the magin is in flex:1 which is shorthand for flex-grow /flex-shrink/flex-basis, so longhanded is flex:1 0 auto.\nHaving flex-grow:1 means it will grow evenly to its siblings .\nUPDATE\nAfter Op's comment\n\njsfiddle.net/9hh86/547 could this be done using flexbox instead?\n\nyou can use justify-content:space-between in ul\n\n\nbody {\r\n margin: 0\r\n}\r\n\r\n.tabs-menu {\r\n \r width: 100%;\r\n display: flex;\r\n margin: 0;\r\n padding: 0;\r\n list-style: none;\r\n justify-content:space-between;\r\n background: grey;\r\n text-align: center;\r\n}\r\n\r\n.tabs-menu li {\r\n padding:10px;\r\n border: solid white;\r\n border-width: 0 2px;\r\n}\r\n\r\n.tabs-menu a {\r\n color: white;\r\n}\n<ul class=\"tabs-menu ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all\" role=\"tablist\">\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab1')\">tab1</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab2')\">tab2</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab3')\">tab3</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab4')\">tab4</a></li>\r\n</ul>\n\n\n\nA: I would use flex on the parent, and set the children to flex-grow: 1; flex-basis: 0 so they grow to fill the parent evenly based on the parent's width, and not the content in the li. Also add text-align: center; and remove the padding from the ul\n\n\n.tabs-menu {\r\n text-align: justify;\r\n background: grey;\r\n display: flex;\r\n padding: 0;\r\n}\r\n\r\n.tabs-menu li {\r\n flex: 1 0 0;\r\n padding: 10px;\r\n border-right: 2px solid white;\r\n list-style: none;\r\n text-align: center;\r\n}\r\n\r\n.tabs-menu a {\r\n color: white;\r\n}\n<ul class=\"tabs-menu ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all\" role=\"tablist\">\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab1')\">tab1</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab2')\">tab2</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab3')\">tab3</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab4')\">tab4</a></li>\r\n</ul>\n\n\n\nA: The best way to handle this is with flex:\n.tabs-menu {\n display: flex;\n flex-wrap: wrap;\n padding: 0; // Optional, but probably desired\n}\n\n.tabs-menu li {\n flex: 1;\n}\n\n\n\n.tabs-menu {\r\n text-align: justify;\r\n width: 100%;\r\n background: grey;\r\n display: flex;\r\n flex-wrap: wrap;\r\n padding: 0;\r\n}\r\n\r\n.tabs-menu:after {\r\n content: '';\r\n display: inlinea-block;\r\n width: 100%;\r\n}\r\n\r\n.tabs-menu li {\r\n display: inline-block;\r\n padding: 10px;\r\n border-right: 2px solid white;\r\n flex: 1;\r\n}\r\n\r\n.tabs-menu a {\r\n color: white;\r\n}\n<ul class=\"tabs-menu ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all\" role=\"tablist\">\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab1')\">tab1</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab2')\">tab2</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab3')\">tab3</a></li>\r\n <li><a class=\"w3-bar-item w3-button\" onclick=\"openCity('tab4')\">tab4</a></li>\r\n</ul>\n\n\nI've also created a working fiddle showcasing this here.\nHope this helps! :)\n"
| |
doc_23538731
|
poll.find().sort({'date': -1}).toArray(function(err,docs){
res.render("home",{polls:docs});
});
The variable polls is an array of objects.I am able to access the polls array successfully in the html view but I don't know a way to access it in the client side js file to draw charts using the data inside array.
If I use <input type='hidden value='{{ polls }}'>, it is converted to a string and the array, objects inside it cannot be accessed in client js. What can be done?
A: i dont know what nunjucks does, but express sends all non-scalar data (= objects & arrays) as an JSON-string.
just use something like
var body = JSON.parse(responseText);
on the client to get the original object/array back.
A: To make it accessible correctly you need to output polls via JSON.stringify which will convert your javascript array to the json format: JSON.stringify(polls).
So,
<input type="hidden" value="{{ JSON.stringify(polls) }}" />
Or to access it in javascript:
<script>
var polls = "{{ JSON.stringify(polls) }}";
</script>
Or it will be even better to do this operation on the server side to make it faster (instead of client-side):
res.render("home", {
polls: JSON.stringify(docs)
});
| |
doc_23538732
|
The book has a property which is also a versioned entity Author.
Author author = new Author();
author.setName("foo");
save(author);
Book book = new Book();
book.setAuthor(author);
save(book);
Now if I change the author's name eg
author.setName("bar");
I want "bar" to be seen from the version of Book as of this hour. eg
Book book = getRevForHour(Book.class, LocalDateTime.now());
if (book.getAuthor().getName() == "bar") {
System.out.println("got what I wanted");
} else {
System.out.println("didn't get what I wanted");
}
But right now I'm getting "foo" which is the value the Author had as of the last rev creation for Book.
Is there a way to trigger a cascade of rev creations upwards to all entities? Or is there a better way to get such historic data?
edit:
I ended up adding a column "last_update" to all entities and entirely manually ended up propagating changes upwards whenever an entity was altered. Changing the value in lastUpdate then triggered envers to create a new version.
| |
doc_23538733
|
rvm install 1.7.4
Below is what my output looks like
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.12/x86_64/jruby-1.7.4.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Requirements installation successful.
HEAD is now at 2390d3b024 Bump for 1.7.4
Previous HEAD position was 2390d3b024... Bump for 1.7.4
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
From https://github.com/jruby/jruby
* branch master -> FETCH_HEAD
Already up-to-date.
git checkout 1.7.4
Copying from repo to src path...
jruby-1.7.4 - #ant jar.......
Error running '__rvm_ant jar',
please read /Users/solid/.rvm/log/1506220984_jruby-1.7.4/ant.jar.log
If I try to install any other version of ruby such as 2.4.1 or 2.0.0, it works.
Below are the contents of the ant.jar.log file
[2017-09-24 08:13:04] __rvm_ant
__rvm_ant ()
{
\ant "$@" || return $?
}
current path: /Users/solid/.rvm/src/jruby-1.7.4
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/solid/.rvm/bin
command(2): __rvm_ant jar
++ ant jar
Buildfile: /Users/solid/.rvm/src/jruby-1.7.4/build.xml
init:
prepare-bin-jruby:
jar:
init:
create-dirs:
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build/classes
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build/classes/jruby
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build/classes/test
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build/test-results
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/build/test-results/html
[mkdir] Created dir: /Users/solid/.rvm/src/jruby-1.7.4/docs/api
copy-resources:
[copy] Copying 45 files to /Users/solid/.rvm/src/jruby-1.7.4/build/classes/jruby
copy-bc-resources:
[copy] Copying 2 files to /Users/solid/.rvm/src/jruby-1.7.4/lib/ruby/shared
update-constants:
[echo] Updating Constants.java
[echo] ...using git revision = 2390d3b024, tzdata = 2012j
[copy] Warning: Could not find file /Users/solid/.rvm/src/jruby-1.7.4/build/src_gen/org/jruby/runtime/Constants.java to copy.
[copy] Copying 1 file to /Users/solid/.rvm/src/jruby-1.7.4/build/src_gen/org/jruby/runtime
_uc_internal_:
[copy] Copying 1 file to /Users/solid/.rvm/src/jruby-1.7.4/build/src_gen/org/jruby/runtime
[javac] Compiling 1 source file to /Users/solid/.rvm/src/jruby-1.7.4/build/classes/jruby
[javac] warning: [options] bootstrap class path not set in conjunction with -source 1.6
[javac] warning: [options] source value 1.6 is obsolete and will be removed in a future release
[javac] warning: [options] target value 1.6 is obsolete and will be removed in a future release
[javac] warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
[javac] 4 warnings
prepare:
compile-annotation-binder:
[javac] Compiling 18 source files to /Users/solid/.rvm/src/jruby-1.7.4/build/classes/jruby
[javac] warning: [options] bootstrap class path not set in conjunction with -source 1.6
[javac] warning: [options] source value 1.6 is obsolete and will be removed in a future release
[javac] warning: [options] target value 1.6 is obsolete and will be removed in a future release
[javac] warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
[javac] Note: /Users/solid/.rvm/src/jruby-1.7.4/src/org/jruby/util/CodegenUtils.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 4 warnings
compile-jruby:
[javac] Compiling 1395 source files to /Users/solid/.rvm/src/jruby-1.7.4/build/classes/jruby
[javac] -Xbootclasspath/p is no longer a supported option.
[javac] Error: Could not create the Java Virtual Machine.
[javac] Error: A fatal exception has occurred. Program will exit.
BUILD FAILED
/Users/solid/.rvm/src/jruby-1.7.4/build.xml:636: The following error occurred while executing this line:
/Users/solid/.rvm/src/jruby-1.7.4/build.xml:289: Compile failed; see the compiler error output for details.
Total time: 4 seconds
++ return 1
Please let me know if you need any other info on setup/environment!
Thanks for the help!
| |
doc_23538734
|
I want something like im = models.ImageField(upload_to="images/", blank=True, null=True) but I do not want to upload many images one by one.
How can I do that? There is a simple way to use FileField or ImageField that upload directly the folder instead of a file/image?
A: I've done some digging around and it doesn't seem possible. According to this answer. You can use some JS to select all the files in the directory you want to upload and then create an upload field for each of the files.
| |
doc_23538735
|
I get the EXC_BAD_ACCESS error on the line with strcpy:
char *invalidOption = NULL;
strcpy(invalidOption, argv[2]);
argv[1] is -v (a "valid" option) and argv[2] is -z (an "invalid" option).
I then need to change "invalidOption" for display reasons (printing the "error" message).
Any ideas as to why this is happening?
Please let me know if you need any more details.
A: strcpy doesn't allocate any memory for you. You're trying to copy your string to NULL, which causes undefined behaviour. You need something like:
char invalidOption[10];
strcpy(invalidOption, argv[2]);
Just make sure that invalidOption is big enough to hold the whole string (including null terminator) or you'll end up with the same problem. You can use dynamic allocation if necessary.
| |
doc_23538736
|
<p class ="BasicP"> Datum: <?php echo $Datum;"\r\n"?>
Betreft: <?php echo $Betreft;"<br>"?>
Offertenr: <?php echo $Offertenr;"\n"?>
<p>
And this outputs:
Datum: Betreft: Offertenr:
I would like it to output:
Datum:
Betreft:
Offertenr:
Each of them starting on a new line.
I've tried <br>, PHP_EOL and newline.
If anyone could tell me what exactly is wrong and how to do it, that would be appreciated.
I added what I tried to the code, none of the tree get me a new line for some reason..
A: There are multiple options:
Sepperate paragraphs:
<p class ="BasicP">Datum: <?php echo $Datum;?></p>
<p class ="BasicP">Betreft: <?php echo $Betreft;?></p>
<p class ="BasicP">Offertenr: <?php echo $Offertenr;?></p>
Line break:
<p class ="BasicP">
Datum: <?php echo $Datum;?><br/>
Betreft: <?php echo $Betreft;?><br/>
Offertenr: <?php echo $Offertenr;?>
<p>
Or print it as code:
<pre>
Datum: <?php echo $Datum;?>
Betreft: <?php echo $Betreft;?>
Offertenr: <?php echo $Offertenr;?>
</pre>
This has noting to do with PHP. A simple HTML question.
| |
doc_23538737
|
A: What version of Windows are you running/testing on?
There's a feature of Windows 7 (not sure if it's in Vista as well, or perhaps even XP) where if you specify a web location (be it http or ftp), Windows downloads the file from that location and passes the path of the downloaded file, hence the Temp folder, to the application. As far as I can tell from the OpenFileDialog documentation on msdn there's no way to disable this behaviour.
You'll have to either roll your own implementation, or see if there's a PInvoke method you can use to persuade it not to exhibit this behaviour.
| |
doc_23538738
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>color</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="three.js"></script>
<script src="OrbitControls.js"></script>
<script src="Detector.js"></script>
<script src="stats.min.js"></script>
<script src="loaders/MTLLoader.js"></script>
<script src="loaders/OBJLoader.js"></script>
<script type='text/javascript' src='DAT.GUI.min.js'></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer,effectController;
var raycaster;
var objects = [];
var selectedObject,selectedPos;
var rotation;
var pos,quat;
var INTERSECTED;
var guiColor;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 15;
controls = new THREE.OrbitControls( camera );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x555000 );
scene.add( camera );
// light
var dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 200, 200, 1000 ).normalize();
camera.add( dirLight );
camera.add( dirLight.target );
var mtlLoader = new THREE.MTLLoader(); mtlLoader.setBaseUrl('assets/'); mtlLoader.setPath('assets/'); mtlLoader.load('anno.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('anno.obj', function (object) {
scene.add( object );
objects.push( object );
});
});
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
/* Controls */
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
raycaster = new THREE.Raycaster();
gui = new dat.GUI();
parameters =
{
color: "#ff0000",
};
gui.add( parameters, 'reset' ).name("Reset");
guiColor = gui.addColor( parameters, 'color' ).name('Color');
container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize, false );
renderer.domElement.addEventListener("click", onclick, false);
}
var mouse = new THREE.Vector2();
function onclick(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
INTERSECTED = intersects[0].object;
if ( INTERSECTED && INTERSECTED.material.emissive != null ){
guiColor.onChange(function(){
INTERSECTED.material.emissive.setHex(parameters.color)
});
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
</script>
</body>
</html>
A: I've create a little live demo with your code and a basic working solution. I'd like to highlight three important changes:
*
*You can use the onChange() event handler in order to know when a certain dat.gui property has changed. The demo uses this feature to update the color of a selected object.
*I have refactored your raycasting logic into something more simple. I've seen you've copied some code from the official three.js examples but the new code should be sufficient for your case. Besides, it's also better to update Material.color instead of Material.emissive.
*If you set OrbitControls.enableDamping to true, you have to update the controls in your animation loop.
https://jsfiddle.net/btuzd23o/2/
three.js R103
| |
doc_23538739
|
When I set (in the information window) the default app for this type of file to the oldest Xcode and apply it for all of them it changes back automatically to newest.
How do I effectively change this?
I really need to use the older version for development.
Regards.
A: I'm not sure if this is an "issue" per se as my experience with the betas over the years has always done this. I know this isn't a solid answer as a "solution" but whenever I have a beta XCode installed I always open the current-release XCode first and open up my project files with CMD-O. Second option is what you're alluding to which is right-clicking to open the project file and choosing the appropriate version. The last option you've got is to uninstall/delete the beta XCode.
| |
doc_23538740
|
I'd like to find records where a text field contains text to populate an autocomplete field in a form. The challenge is that I'd like to limit the results to the first 20 records, but give preference to matches that are at the start of the field.
How I do this now is I execute a query for field LIKE "%term" for 10, and then append records where field LIKE "%term%" for 10. It requires two searches.
Is it possible to do this with just one query of the table? Ordering by the position of the match in the field?
A: Yes, it is possible to order by the first occurrence of the search string. (I assume you wanted to write field LIKE "term%".)
SELECT *, LOCATE('term', field) as rev_score FROM table WHERE field LIKE "%term%" ORDER BY rev_score DESC LIMIT 20;
However most likely this query will be much slower than the field "term%" (assuming you have an index on field).
*
*In your case the field LIKE "term%" could be fulfilled by indexes on field resulting in a range query but still fast.
*field LIKE "%term%" LIMIT 10 if you don't use order still can be fast(er). Statistically 2 times faster than the solution I wrote depending on the search term and data distribution. The reason is because MySQL will start to scan through the table searching for "term" (no indexes can be used here). When it found the 10 elements it will stop. This can be in the beginning the table.
*What I wrote will cause MySQL to do a full scan on the whole table and check every row for "term" than to a filesort on the calculated value. Probably the worst thing which can happen on a single table lookup.
I would say try both version and go with the faster one. Or if your dataset is big you can checkout Full Text Search capabilities of MySQL (MYISAM has it and InnoDB supports it too since MySQL 5.6).
A: Smart! I don't know if it's possible, but I know how you can do it a little bit better:
<?php
$q = 'term';
$limit = 20;
$first = mysql_query("SELECT * FROM some_table WHERE name LIKE '%$q' ORDER BY name LIMIT $limit");
$first_len = !$sql?0:mysql_num_rows($first);
$limit -= $first_len;
$second = mysql_query("SELECT * FROM some_table WHERE name LIKE '%$q%' LIMIT $limit");
$second_len = !$sql?0:mysql_num_rows($second);
if (!$first_len && !$second_len) {
exit('No results found.');
}
function handleSearchResultRow($row) {
echo $row['name'].'<br/>';
}
if ($first_len)
while ($row = mysql_fetch_array($first))
handleSearchResultRow($row);
if ($second_len)
while ($row = mysql_fetch_array($second))
handleSearchResultRow($row);
?>
Tada! You'll get the same result, but with slightly more code! This will make sure that there will always be up to 20 results, with the results starting with the term first!
If you really would like "Ordering by the position of the match in the field", then I think you'll have to create an array of all results and sorting it with php strpos(). But SQL is really powerful, and probably has the power to do this too. Please post another answer and tell me if you find out how to do that. :)
A: I would do:
SELECT * FROM table WHERE field LIKE '%term%' order by IF(field REGEXP '^term.*',0,1),field LIMIT 20;
| |
doc_23538741
|
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
</ul>
A: var listItems = $("#myList").children();
var count = listItems.length;
Of course you can condense this with
var count = $("#myList").children().length;
For more help with jQuery, http://docs.jquery.com/Main_Page is a good place to start.
A: I think this should do it:
var ct = $('#mylist').children().size();
A: and of course the following:
var count = $("#myList").children().length;
can be condensed down to: (by removing the 'var' which is not necessary to set a variable)
count = $("#myList").children().length;
however this is cleaner:
count = $("#mylist li").size();
A: try
$("#mylist").children().length
A: Try:
$("#mylist li").length
Just curious: why do you need to know the size? Can't you just use:
$("#mylist").append("<li>New list item</li>");
?
A: You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call.
So the best way:
$("#mylist li").length
A: Count number of list elements
alert($("#mylist > li").length);
A: Another approach to count number of list elements:
var num = $("#mylist").find("li").length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
</ul>
A:
$("button").click(function(){
alert($("li").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Count the number of specific elements</title>
</head>
<body>
<ul>
<li>List - 1</li>
<li>List - 2</li>
<li>List - 3</li>
</ul>
<button>Display the number of li elements</button>
</body>
</html>
| |
doc_23538742
|
But when I do some scrolling, the progress view distorts like this:
It is definitely something to do with reusing cells. I'm familiar with all that and yes the issue occurs exactly when you'd expect it to. Here is my code; there is quite a lot going on here so perhaps some of this is in the wrong place?:
let Cell = tableView.dequeueReusableCell(withIdentifier: "GroupTableViewCell", for: indexPath) as! GroupTableViewCell
let MyGroup = Application.Variables.SELECTED_TAB?.Groups[(indexPath as NSIndexPath).row]
Cell.MainView.layer.cornerRadius = 4
Cell.MainView.clipsToBounds = true
Cell.ProgressView.layer.cornerRadius = 4
Cell.ProgressView.clipsToBounds = true
Cell.DescriptionLabel.text = MyGroup?.Description
Cell.DescriptionLabel.layer.shadowRadius = 4
Cell.DescriptionLabel.layer.shadowColor = UIColor.white.cgColor
Cell.DescriptionLabel.layer.shadowOffset = CGSize(width: 0, height: 0)
Cell.DescriptionLabel.layer.shadowOpacity = 1
Cell.DescriptionLabel.layer.masksToBounds = false
Cell.SubtitleLabel.layer.shadowRadius = 4
Cell.SubtitleLabel.layer.shadowColor = UIColor.white.cgColor
Cell.SubtitleLabel.layer.shadowOffset = CGSize(width: 0, height: 0)
Cell.SubtitleLabel.layer.shadowOpacity = 1
Cell.SubtitleLabel.layer.masksToBounds = false
Cell.ProgressButton.titleLabel?.font = UIFont.fontAwesome(ofSize: 20, style: .regular)
Cell.ProgressButton.tintColor = UIColor.white
Cell.ProgressButton.layer.cornerRadius = 24
Cell.ProgressButton.clipsToBounds = true
Cell.ProgressButton.imageEdgeInsets = UIEdgeInsets.init(top: 12,left: 12,bottom: 12,right: 12)
Cell.ProgressButton.layer.shadowRadius = 2.0
Cell.ProgressButton.layer.shadowColor = UIColor.black.cgColor
Cell.ProgressButton.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
Cell.ProgressButton.layer.shadowOpacity = 0.40
Cell.ProgressButton.layer.masksToBounds = false
if (MyGroup?.PrescriptionStatus == Prescription.PRESCRIPTION_STATUS_WAITING_FOR_COLLECTION) {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .dollyflatbedalt), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_green
Cell.SubtitleLabel.text = "x" + String(MyGroup!.Prescriptions.count) + " Rx waiting for collection"
}
if (MyGroup?.PrescriptionStatus == Prescription.PRESCRIPTION_STATUS_COLLECTED) {
if (MyGroup!.IsReadyForUpload) {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .clouduploadalt), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_blue
} else {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .flagcheckered), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_blue
}
Cell.SubtitleLabel.text = "x" + String(MyGroup!.Prescriptions.count) + " Rx collected!"
}
if (MyGroup?.PrescriptionStatus == Prescription.PRESCRIPTION_STATUS_WAITING_FOR_DELIVERY) {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .boxcheck), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_green
Cell.SubtitleLabel.text = "x" + String(MyGroup!.Prescriptions.count) + " Rx waiting for delivery"
}
if (MyGroup?.PrescriptionStatus == Prescription.PRESCRIPTION_STATUS_DELIVERED) {
if (MyGroup!.IsReadyForUpload) {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .clouduploadalt), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_blue
} else {
Cell.ProgressButton.setTitle(String.fontAwesomeIcon(name: .clouduploadalt), for: .normal)
Cell.ProgressButton.backgroundColor = UIColor.pts_blue
}
Cell.SubtitleLabel.text = "x" + String(MyGroup!.Prescriptions.count) + " Rx delivered!"
}
let Max:Double = MyGroup!.EndTimeSeconds - MyGroup!.StartTimeSeconds
let Progress:Double = Date().timeIntervalSince1970 - MyGroup!.StartTimeSeconds
let ProgressForTextView:Int = Int(MyGroup!.EndTimeSeconds - Date().timeIntervalSince1970)
let hours = (ProgressForTextView % 86400) / 3600
let minutes = (ProgressForTextView % 3600) / 60
if (hours < 0 || minutes < 0) {
Cell.TargetDeliveryTimeLabel.isHidden = true
} else {
var TargetTimeString:String = ""
if (hours <= 0) {
TargetTimeString = ""
}
if (hours == 1) {
TargetTimeString = "one hour, "
}
if (hours >= 2) {
TargetTimeString = String(hours) + " hours, "
}
if (minutes <= 0) {
TargetTimeString = TargetTimeString + "less than one minute"
}
if (minutes == 1) {
TargetTimeString = TargetTimeString + "one minute"
}
if (minutes >= 2) {
TargetTimeString = TargetTimeString + String(minutes) + " minutes"
}
if (TargetTimeString != "") {
TargetTimeString = TargetTimeString + " left"
}
Cell.TargetDeliveryTimeLabel.text = TargetTimeString
Cell.TargetDeliveryTimeLabel.isHidden = false
}
if (Max >= Progress) {
Cell.DescriptionLabel.tintColor = UIColor.black
Cell.SubtitleLabel.tintColor = UIColor.black
Cell.TargetDeliveryTimeLabel.tintColor = UIColor.pts_darkergrey
Cell.ProgressView.progressTintColor = UIColor.pts_pbgreen
Cell.ProgressView.setProgress(Float(Progress / Max), animated: false)
if (Max * 0.75 <= Progress) {
Cell.ProgressView.progressTintColor = UIColor.pts_pbamber
}
} else {
Cell.DescriptionLabel.tintColor = UIColor.white
Cell.SubtitleLabel.tintColor = UIColor.white
Cell.TargetDeliveryTimeLabel.tintColor = UIColor.white
Cell.ProgressView.progressTintColor = UIColor.pts_pbred
Cell.ProgressView.setProgress(1, animated: false)
}
return Cell
Commenting out the code that turns the progress bar red seems to circumvent the issue... but I do need to calculate the colour in code. The constraints for the progress view set the Trailing, Leading, Top and Bottom spaces to the superview (MainView) with a constant of 1 (for a small margin).
Is the progress view inheriting the corner radius of the button somehow?
A: Using .tintColor instead of .progressTintColor sidestepped this issue.
| |
doc_23538743
|
But it turned out to be that the port specified (50051 as the example said) was unavailable. Switching to a different port on both server and client sides solves the problem.
However, this begs a better solution because we can't ask every rpc call to hardcode a port number. What would be the best practice?
I've consulted this question but couldn't get a sure answer for a bulletproof solution.
Thanks in advance!
| |
doc_23538744
|
My Node code is as follows
var http = require('http');
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Error:
F:\nodejs>node ..\NodeLearning\TestServer1\test.js
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Can Any one tell me what has gone wrong here?
A: Can you try one more time by setting a proxy like mentioned below
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new',
proxy:'add your proxy setting'
};
| |
doc_23538745
|
It is working to make a static variable to hold the score and change it in other scripts when the player should be awarded, but it also advised that using static variable in C# script of Unity might not be recommended.
Flowing is what I do to construct the scoring system:
in ScoreManger which was bonded to an UI Text component to show the score:
public class ScoreManager : MonoBehaviour {
public static int score;
Text text;
private void Awake()
{
text = GetComponent<Text>();
}
private void FixedUpdate()
{
text.text = "Score: " + score;
}
}
And the procedure to add the score:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
ScoreManager.score = ScoreManager.score + score;
Destroy(gameObject);
}
}
So what's the best way to do this without a static variable, and if someone could explain why using a static variable is not recommended will be more grateful.
EDIT
Have tried the event handle way as @rogalski demonstrated in the answer, but the IDE shows that there is an error for type conversion on the lambda function of ExecuteEvents.Execute<T>
A: You have to remember that Unity is a component based engine meaning that components have to do some specific work independently. This can be well combined with event driven programming methodology which mean that application ( or each of it's components ) are dependant on some event input.
Unity introduced really well designed Event ( or Messaging ) system which you should use instead of making static fields, classes etc.
To point you out in the right way of implementing this I'll use the most trivial example.
( EDIT -> Added definition for EventData which is required for Unity's messaging system )
First register your event :
public interface ICoinPickedHandler: IEventSystemHandler
{
void OnCoinPickedUp(CoinPickedEventData eventData);
}
Then implement this EventTarget into your script :
public class ScoreManager
: MonoBehaviour, ICoinPickedHandler
{
private int m_Score;
public void OnCoinPickedUp(CoinPickedEventData eventData)
{
this.m_Score += eventData.Score;
eventData.Use();
}
// code to display score or whatever ...
}
Now to use this you have to just fire the event :
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
// assuming your collision.gameObject
// has the ICoinPicker interface implemented
ExecuteEvents.Execute<ICoinPickedHandler>(collision.gameObject, new CoinPickedEventData(score), (a,b)=>a.OnCoinPickedUp(b));
}
}
Now you have to create EventData :
public class CoinPickedEventData
: BaseEventData
{
public readonly int Score;
public CoinPickedEventData(int score)
: base(EventSystem.current)
{
Score = score;
}
}
Of course this example requires from you to know the target to which you want to send that event. But if you do not know the target, you can use approach to ExecuteHierarchy.
More on that topic on docs.unity3d.com.
A: First of all , it would be better to wrap the static variable in a method: addToScore , so in case behavior changes you only have to implement the changes once.
For the static variable: I think it would be better to make the score manager a singleton instance instead of a static variable. Because then if you decide you need more score managers, reset the score manager, save more data in the score manager or whatever it will be a lot easier.
| |
doc_23538746
|
Hello I am trying to build a shiny app for species sampling. For each species that is selected I need to select in which kind of sampling, and if it is selected in a pin-point sampling it needs to be counted, here is a working example:
library(shiny)
library(shinyMobile)
ui = f7Page(
title = "Show navbar",
f7SingleLayout(
navbar = f7Navbar("Hide/Show navbar"),
f7Button(inputId = "toggle", "Toggle navbar", color = "red"),
f7Text(inputId = "SpeciesName", label = "SpeciesName"),
shinyMobile::f7Card(
f7Flex(
textOutput("SpeciesAgain"),
uiOutput("Sampling_type_ui"),
uiOutput("SpeciesCount")
)
)
)
)
server = function(input, output, session) {
output$SpeciesAgain <- renderText({input$SpeciesName})
output$Sampling_type_ui <- renderUI({
req(input$SpeciesName)
f7Select(inputId = "Sampling_type",
label = "Sampling type",
choices = c("Pin-point", "5m circle", "15m circle"))
})
output$SpeciesCount <- renderUI({
if (req(input$Sampling_type) == "Pin-point") {
shinyMobile::f7Stepper(inputId = "Species1", label = "Species count", min = 1, max = 1000, step = 1, value = 1)
}
})
observeEvent(input$toggle, {
updateF7Navbar()
})
}
shinyApp(ui, server)
This is working just as I want since, it waits until I write a species name, for the f7select to appear, and if I select Pin-point I can use the counter to get the number of individuals.
This does not work
However I will need to select several species in the real app, which is why I want to turn this into a Shiny Module. This is what I have tried:
library(shiny)
library(shinyMobile)
#Species <- "Nothofagus"
Species_UI <- function(id){
f7Text(inputId = NS(id,"SpeciesName"), label = "SpeciesName")
shinyMobile::f7Card(
f7Flex(
textOutput(NS(id, "SpeciesAgain")),
uiOutput(NS(id, "Sampling_type_ui")),
uiOutput(NS(id,"SpeciesCount"))
)
)
}
Species_Server <- function(id){
moduleServer(id, function(input, output, session) {
output$SpeciesAgain <- renderText({input$SpeciesName})
output$Sampling_type_ui <- renderUI({
req(input$SpeciesName)
f7Select(inputId = "Sampling_type",
label = "Sampling type",
choices = c("Pin-point", "5m circle", "15m circle"))
})
output$SpeciesCount <- renderUI({
if (req(input$Sampling_type) == "Pin-point") {
shinyMobile::f7Stepper(inputId = "Species1", label = "Species count", min = 1, max = 1000, step = 1, value = 1)
}
})
})
}
library(shiny)
library(shinyMobile)
ui = f7Page(
title = "Show navbar",
f7SingleLayout(
navbar = f7Navbar("Hide/Show navbar"),
f7Button(inputId = "toggle", "Toggle navbar", color = "red"),
Species_UI("Species")
)
)
server = function(input, output, session) {
Species_Server("Species")
observeEvent(input$toggle, {
updateF7Navbar()
})
}
shinyApp(ui, server)
Now when I do this, the UI in the modules does not appear in the app, but I can't figure out what is wrong.
Extra question
in a final option of the app I want to replace the f7Text that I use to input the species for a f7SmartSelect, Where the input for species names is as follows:
library(shiny)
library(shinyMobile)
ui = f7Page(
title = "Show navbar",
f7SingleLayout(
navbar = f7Navbar("Hide/Show navbar"),
f7Button(inputId = "toggle", "Toggle navbar", color = "red"),
f7SmartSelect(inputId = "SpeciesName", label = "SpeciesName",
choices = c("Species1", "Species2", "Species3", "Species4", "Species5"),
multiple = T, openIn = "popup"),
shinyMobile::f7Card(
f7Flex(
textOutput("SpeciesAgain"),
uiOutput("Sampling_type_ui"),
uiOutput("SpeciesCount")
)
)
)
)
server = function(input, output, session) {
output$SpeciesAgain <- renderText({input$SpeciesName})
output$Sampling_type_ui <- renderUI({
req(input$SpeciesName)
f7Select(inputId = "Sampling_type",
label = "Sampling type",
choices = c("Pin-point", "5m circle", "15m circle"))
})
output$SpeciesCount <- renderUI({
if (req(input$Sampling_type) == "Pin-point") {
shinyMobile::f7Stepper(inputId = "Species1", label = "Species count", min = 1, max = 1000, step = 1, value = 1)
}
})
observeEvent(input$toggle, {
updateF7Navbar()
})
}
shinyApp(ui, server)
So that the module is repeated for each species
Any help is welcome
A: Two issues in your code:
*
*the UI modules should return a tagList() so you need to use
tagList(
f7Text(inputId = NS(id,"SpeciesName"), label = "SpeciesName"),
shinyMobile::f7Card(
f7Flex(
textOutput(NS(id, "SpeciesAgain")),
uiOutput(NS(id, "Sampling_type_ui")),
uiOutput(NS(id,"SpeciesCount"))
)
)
)
*
*when you create an input in the server (like your f7Select()), you still need to be careful about the namespace. In the server part of a module, you need to use session$ns(id-of-input). This is specified in the section "Using renderUI within modules" of the R Shiny modules article. In your case you should use:
f7Select(inputId = session$ns("Sampling_type"),
label = "Sampling type",
choices = c("Pin-point", "5m circle", "15m circle"))
Small addition: usually, in the UI part of a module, it is better to define ns <- NS(id) and then to use ns(id-of-input). Similarly, in the server part of a module, you can define ns <- session$ns.
| |
doc_23538747
|
Is there an attribute that will avoid this?
A: Per the accepted answer and similar question/answer, in addition to [NotMapped] you can also specify it using the Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TheModelAffected>().Ignore(t => t.TheIgnoredProperty);
base.OnModelCreating(modelBuilder);
}
A: [NotMapped] is the short version if you like conciseness. And of course, you would add:
using System.ComponentModel.DataAnnotations.Schema;
to your class.
A: Add the [System.ComponentModel.DataAnnotations.Schema.NotMapped] attribute to the property.
| |
doc_23538748
|
It is a kind of parental control application.
I just don't know which C# class would be able to do such intercepting and which steps would involve configuring it / making it works.
Any suggestion is appreciated.
A: I think the easiest way to achive that would be creating your own HTTP proxy, for example by taking something like http://www.telerik.com/fiddler/fiddlercore.
In such way all the HTTP/HTTPS traffic would go through your proxy and you would be albe to control what can pass through and what can not, that is how corporations control what their employees can access from company's networks.
| |
doc_23538749
|
Thanks in advance.
| |
doc_23538750
|
async function getAnimalSounds(animals){
var sounds = []
for (const a of animals){
asynchronously_fetch_sound(a).then((result) => {
sounds.push(result)
})
}
return sounds // sounds returns as an empty array
}
Thank you in advance!
A: The problem here is that you are using a plain for loop to traverse the animals array. Loops in NodeJS won't wait for the promise of the current iteration to resolve before moving onto the next, so the loop will finish before you have resolved your promises.
The best thing to do is to construct an array of promises you want to resolve, and then call Promise.all on that array.
async function getAnimalSounds(animals){
const promises = animals.map(a => asynchronously_fetch_sound(a))
const sounds = await Promise.all(promises)
return sounds
}
Or if you're happy to use the Bluebird library (docs here), you can do this:
const Bluebird = require('bluebird') // import Bluebird library
async function getAnimalSounds(animals){
const sounds = await Bluebird.map(animals, (a) => asynchronously_fetch_sound(a))
return sounds
}
Remember that since you have written an async function, you will need to wait for it to resolve before doing anything with its output; either by awaiting it or by calling .then(...).
A: You should add await for the asynchronous method call.
async function getAnimalSounds(animals){
var sounds = []
for (const a of animals){
const result = await asynchronously_fetch_sound(a);
sounds.push(result)
}
return sounds // sounds returns as an empty array
}
However, the best practice is to use Promise.all()
async function getAnimalSounds(animals){
var sounds = []
const promises = []
for (const a of animals){
promises.push(asynchronously_fetch_sound(a));
}
sounds = await Promise.all(promises);
return sounds;
}
A: You can use Promise.all() to achieve that:
function getAnimalSounds(animals){
return Promise.all(animals.map(a => asynchronously_fetch_sound(a)));
}
| |
doc_23538751
|
Resources:
EBApplication:
Type: AWS::ElasticBeanstalk::Application
Properties:
ApplicationName: !Ref ApplicationName
Description: "AWS Elastic Beanstalk Account Balance application"
I want to use this resource in another stack, so Im exporting it at the end of the same yaml file:
Outputs:
EBApplicationName:
Value: !Ref EBApplication
Export:
Name: card-balance-EBApplicationName
Now in my second cloud formation stack, I was to use the elastic beanstalk resource, Im trying:
Resources:
EBApplication:
Type: AWS::ElasticBeanstalk::Application
Properties:
ApplicationName: !ImportValue
'Fn::Sub': 'card-balance-EBApplicationName'
But I get an error saying the application name is already being used, as it's trying to create a new Elastic Beanstalk app (with same same) rather than reusing the first one. What am I doing wrong?
EDIT
This question here has a similar problem. Essentially I want 2 separate stacks - one for each environment - but these are under the same EB application. It seem the person achieved this, see their comment under the answer How to create multiple Elasticbeanstalk environments using a single cloudformation template
A:
What am I doing wrong?
You can't "reusing the first one" the first one. All modifications to the first EB environment must be performed using the first CFN stack.
In the second stack you can only reference EB return values in other resources, once you export these values in the first stack.
A: The EB Application resource must be in one and only stack:
EBApplication:
Type: AWS::ElasticBeanstalk::Application
Properties:
ApplicationName: !Ref EBApplicationName
Description: "Application Description"
In this stack, you can reference the application in an environment:
EBApplicationEnvironment1:
Type: AWS::ElasticBeanstalk::Environment
Properties:
ApplicationName: !Ref EBApplication
EnvironmentName: !Ref EBnvironmentName1
This is because, as per the documentation Ref returns the resource name.
In another stack you can't reference by resource, but you can by name:
EBApplicationEnvironment2:
Type: AWS::ElasticBeanstalk::Environment
Properties:
ApplicationName: !Ref EBApplicationName
EnvironmentName: !Ref EBnvironmentName2
With Ref you can reference both another resource (in the same stack only) and a parameter. So for your case, you could in both stacks pass the same application name as a parameter. You don't necessarily need to output the name. (This isn't always the case with CloudFormation. It works here, because you are allowed to define the name and you can reference the resource in the Environment by name. ARNs or ids are needed in other cases. An output will work there).
Also note that the first stack owns the application and environment 1. You will need to delete (when needed) first the second stack and then the first.
| |
doc_23538752
|
#include <math.h>
#include <stdlib.h>
void run_calc();
void scandata(char *op, double * operand);
void do_next_op(char op, double operand, double *akku);
int main()
{
run_calc();
return 0;
}
void run_calc(){
double akku = 0, operand = 0;
char op, answer;
printf("Press enter to use the calculator");
printf("\n");
scanf("%c", &answer);
while(answer='q'||answer!='Q');
{
if(answer=='q'||answer=='Q')
{
printf("The last result was %1.2f\n", akku);
exit(0);
}
else if (answer=='h'||answer=='H')
{
printf("%s\t%s\n", "+" , "add");
printf("%s\t%s\n", "-" , "subtract");
printf("%s\t%s\n", "*" , "multiply");
printf("%s\t%s\n", "/" , "divide");
printf("%s\t%s\n", "^" , "power");
printf("%s\t%s\n", "q" , "quit");
}
else
{
printf("Enter an operator (+,-,/,#,^,*) and optional operand.Enter 'h' for help. Enter 'q' to exit the program.");
scandata(&op, &operand);
do_next_op(op, operand, &akku);
printf("Result so far is: %1.2lf \n", akku);
printf("\n");
}
}
}
void scandata(char *op, double *operand) {
scanf("%c", op);
scanf ("%lf", operand);
}
void do_next_op(char op, double operand, double *akku)
{
switch(op)
{
case '+': *akku += operand; break;
case '-': *akku -= operand; break;
case '*': *akku *= operand; break;
case '/': *akku /= operand; break;
case '#': *akku = sqrt(*akku); break;
case '^': *akku = pow(*akku,operand); break;
case '%': *akku *= -1; break;
case '!': *akku = 1 / *akku; break;
case '@': *akku = log(*akku); break;
case 'q': printf(" The final value of akku is %1.2lf \n", *akku); exit(0);
}
}
After i run the program and press enter or any letter. it just stucks . can someone help me please? This program is a calculator that i try to do it. This is for my homework which is due to next week.
I am still new this programming. i need help and alot of improvement.
Can someone point it out what i did wrong?
I think there is something wrong in run_Calc but i dont know what is wrong with it
A: while(answer='q'||answer!='Q');
{
This is an infinite loop. For a start, the semi-colon at the end of the first line disassociates the opening brace(a) with the while statement meaning that, if the condition is true, it will simply do nothing, forever.
And the condition is true, since answer='q' will set the answer variable to 'q' and then use that as an expression. Since 'q' is non-zero, it's considered true.
However, even if you correct this by changing the = to a != (assuming you only want to continue until user enters quit), you should use && rather than ||. No character can be both q and Q at the same time so using || would also result in the condition always being true.
I suspect what you should have had would be more along the lines of (comparison rather than assignment, get rid of the semicolon, and fix the conjunctive):
while(answer != 'q' && answer != 'Q')
{
There may well be other issues but that's the one causing your apparent "stuck" behaviour.
(a) A "naked" braced section can be used to create a new, isolated scope, such as:
{
int xyzzy = 42;
// Can use xyzzy here.
}
// But not here.
That's what your semicolon is doing in the code you posted.
| |
doc_23538753
|
lista=[a,b,c,d,e]
How would I ask the user to input a number that prints the letter of the corresponding index in the list?
For example , if the user enter the number 3 , the letter of index 3 in the list ie: 'd' would get printed?
A: Read the index you want and access the list using it.
In Python 3 use input():
index = int(input("Enter your number") # transform to int
print(list[index]) # print item
While in Python 2 use raw_input():
index = int(raw_input("Enter your number") # transform to int
print list[index] # print item
| |
doc_23538754
|
2012-07-09 15:41:16 ZooKeeperSaslClient [INFO] Client will not SASL-authenticate because the default JAAS configuration section 'Client' could not be found. If you are not using SASL, you may ignore this. On the other hand, if you expected SASL to work, please fix your JAAS configuration.
2012-07-09 15:41:16 ClientCnxn [INFO] Socket connection established to Cloudera/192.168.0.102:2181, initiating session
2012-07-09 15:41:16 RecoverableZooKeeper [WARN] Possibly transient ZooKeeper exception: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/master
2012-07-09 15:41:16 RetryCounter [INFO] The 1 times to retry after sleeping 2000 ms
2012-07-09 15:41:16 ClientCnxn [INFO] Session establishment complete on server Cloudera/192.168.0.102:2181, sessionid = 0x1386b0b44da000b, negotiated timeout = 60000
2012-07-09 15:41:18 TableOutputFormat [INFO] Created table instance for exact_custodian
2012-07-09 15:41:18 NativeCodeLoader [WARN] Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2012-07-09 15:41:18 JobSubmitter [WARN] Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.
2012-07-09 15:41:18 JobSubmitter [INFO] Cleaning up the staging area file:/tmp/hadoop-hdfs/mapred/staging/hdfs48876562/.staging/job_local_0001
2012-07-09 15:41:18 UserGroupInformation [ERROR] PriviledgedActionException as:hdfs (auth:SIMPLE) cause:java.io.FileNotFoundException: File does not exist: /home/cloudera/yogesh/lib/hbase.jar
Exception in thread "main" java.io.FileNotFoundException: File does not exist: /home/cloudera/yogesh/lib/hbase.jar
at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:736)
at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:208)
at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:71)
at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:246)
at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:284)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:355)
at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1226)
at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1223)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1232)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:1223)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1244)
at
I am able to run sample programs given in hadoop-mapreduce-examples-2.0.0-cdh4.0.0.jar.
But I am getting this error when my job is submitted successfully to jobtracker . Looks like it is trying to access local file-system again (Although I have set all the required libraries for job execution in distributed cache still its trying to access local dir). Is this issues related to user privileges ?
I)
Cloudera:~ # hadoop fs -ls hdfs://<MyClusterIP>:8020/ shows -
Found 8 items
drwxr-xr-x - hbase hbase 0 2012-07-04 17:58 hdfs://<MyClusterIP>:8020/hbase<br/>
drwxr-xr-x - hdfs supergroup 0 2012-07-05 16:21 hdfs://<MyClusterIP>:8020/input<br/>
drwxr-xr-x - hdfs supergroup 0 2012-07-05 16:21 hdfs://<MyClusterIP>:8020/output<br/>
drwxr-xr-x - hdfs supergroup 0 2012-07-06 16:03 hdfs:/<MyClusterIP>:8020/tools-lib<br/>
drwxr-xr-x - hdfs supergroup 0 2012-06-26 14:02 hdfs://<MyClusterIP>:8020/test<br/>
drwxrwxrwt - hdfs supergroup 0 2012-06-12 16:13 hdfs://<MyClusterIP>:8020/tmp<br/>
drwxr-xr-x - hdfs supergroup 0 2012-07-06 15:58 hdfs://<MyClusterIP>:8020/user<br/>
II)
--- No Result for following ----
hdfs@Cloudera:/etc/hadoop/conf> find . -name '**' | xargs grep "default.name"<br/>
hdfs@Cloudera:/etc/hbase/conf> find . -name '**' | xargs grep "default.name"<br/>
Instead I think with new APIS we are using ->
fs.defaultFS --> hdfs://Cloudera:8020 which i have set properly
Although for "fs.default.name" I got entries for hadoop cluster 0.20.2 (non-cloudera cluster)
cass-hadoop@Pratapgad:~/hadoop/conf> find . -name '**' | xargs grep "default.name"<br/>
./core-default.xml: <name>fs.default.name</name><br/>
./core-site.xml: <name>fs.default.name</name><br/>
I think cdh4 default configuration should add this entry in respective directory. (If its bug).
The command I am using to run my progrmme -
hdfs@Cloudera:/home/cloudera/yogesh/lib> java -classpath hbase-tools.jar:hbase.jar:slf4j-log4j12-1.6.1.jar:slf4j-api-1.6.1.jar:protobuf-java-2.4.0a.jar:hadoop-common-2.0.0-cdh4.0.0.jar:hadoop-hdfs-2.0.0-cdh4.0.0.jar:hadoop-mapreduce-client-common-2.0.0-cdh4.0.0.jar:hadoop-mapreduce-client-core-2.0.0-cdh4.0.0.jar:log4j-1.2.16.jar:commons-logging-1.0.4.jar:commons-lang-2.5.jar:commons-lang3-3.1.jar:commons-cli-1.2.jar:commons-configuration-1.6.jar:guava-11.0.2.jar:google-collect-1.0-rc2.jar:google-collect-1.0-rc1.jar:hadoop-auth-2.0.0-cdh4.0.0.jar:hadoop-auth.jar:jackson.jar:avro-1.5.4.jar:hadoop-yarn-common-2.0.0-cdh4.0.0.jar:hadoop-yarn-api-2.0.0-cdh4.0.0.jar:hadoop-yarn-server-common-2.0.0-cdh4.0.0.jar:commons-httpclient-3.0.1.jar:commons-io-1.4.jar:zookeeper-3.3.2.jar:jdom.jar:joda-time-1.5.2.jar com.hbase.xyz.MyClassName
A:
Even I phased the same problem in 2.0.0-cdh4.1.3 while running MR jobs. After adding the
property in mapred.site.xml
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
For running Hive job
export HIVE_USER=yarn
A: Debug procedure: Try running simple Hadoop shell commands.
hadoop fs -ls /
If this shows the HDFS files then your configuration is correct. If not, then the configuration is missing. When this happens hadoop shell command like -ls will refer to local filesystem and not Hadoop file system.
This happens if Hadoop is started using CMS (Cloudera manager). It does not explicitly stores the configuration in conf directory.
Check if hadoop file system is displayed by following command (change port):
hadoop fs -ls hdfs://host:8020/
If it displays local file system when you submit the path as / then you should set the configuration files hdfs-site.xml and mapred-site.xml in configuration directory. Also hdfs-site.xml should have the entry for fs.default.name pointing to hdfs://host:port/. In my case the directory is /etc/hadoop/conf.
See: http://hadoop.apache.org/common/docs/r0.20.2/core-default.html
See, if this resolves your issue.
| |
doc_23538755
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#open IE
driver = webdriver.Ie()
# Open new tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
# Print handles
print(driver.window_handles)
The answer to the print statement above, is:
['5bd4ca0b-0095-4851-a36d-54f8c602c906']
I would expect to get a list with TWO items, but I only get one.
The code above works if I use the Chrome webdriver. So, is this a bug in the IE webdriver?
A: Officially, you can't. Selenium uses the WebDriver specification to communicate with browsers, but the spec doesn't support tabs—only windows.
As your example shows, you can hack workarounds for specific browsers and operating systems. But what your example doesn't show is why you'd want to. Is there a particular reason why you can't just use a new window?
Opening and using a new window
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
initial_windows = driver.window_handles
wait = WebDriverWait(driver, 10)
opened = EC.new_window_is_opened(initial_windows)
driver.execute_script("window.open();")
wait.until(opened)
initial_window = driver.current_window_handle
new_windows = list(set(driver.window_handles) - set(initial_windows))
new_window = new_windows[0]
driver.switch_to.window(new_window)
try:
# ...
finally:
driver.switch_to.window(initial_window)
Bonus: Simplifying with capybara-py
from capybara.dsl import page
with page.window(page.open_new_window()):
# ...
| |
doc_23538756
|
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
and compiled like this on ubuntu (pretty new version):
go build -v -a -tags netgo -ldflags '-w -extldflags "-static"' hw.go
Then I moved the binary to an older linux also 64 bit and while executing got this error:
what am I doing wrong ?
futexwakeup addr=0x558708 returned -38
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x1006 pc=0x425e5b]
runtime stack:
runtime.throw(0x4becb7, 0x2a)
/usr/local/go/src/runtime/panic.go:617 +0x72
runtime.sigpanic()
/usr/local/go/src/runtime/signal_unix.go:374 +0x4a9
runtime.futexwakeup(0x558708, 0x2b1000000001)
/usr/local/go/src/runtime/os_linux.go:81 +0x8b
runtime.notewakeup(0x558708)
/usr/local/go/src/runtime/lock_futex.go:136 +0x44
runtime.startlockedm(0xc000000180)
/usr/local/go/src/runtime/proc.go:2105 +0x7e
runtime.schedule()
/usr/local/go/src/runtime/proc.go:2555 +0x69
runtime.park_m(0xc000000a80)
/usr/local/go/src/runtime/proc.go:2605 +0xa1
runtime.mcall(0x0)
/usr/local/go/src/runtime/asm_amd64.s:299 +0x5b
goroutine 1 [runnable, locked to thread]:
internal/poll.init()
<autogenerated>:1 +0x73
os.init()
<autogenerated>:1 +0x54
fmt.init()
<autogenerated>:1 +0x54
main.init()
<autogenerated>:1 +0x45
runtime.main()
/usr/local/go/src/runtime/proc.go:188 +0x1c8
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:1337 +0x1
A: Just tried an old compiler and it worked.
1.10.8 is the latest version it works, 1.11.8 doesn't work.
*I didn't check minor versions
| |
doc_23538757
|
interface IComponent {
type: string;
text: string;
}
interface IComponents {
cc: IComponent;
lajota: IComponent;
}
interface IMain {
components: IComponents
}
And it is working fine! But now I need to add a new component called "caneta".
SO I'll access this with .components.caneta. But this new component will have a single attribute:
interface IComponentCaneta {
property: string;
}
// Add the new component to be used on IMain
interface IComponents {
cc?: IComponent;
lajota?: IComponent;
caneta?: IComponentCaneta;
}
The problem is I have a method that do some work depending on the attribute type like:
//for each component I have in components objects
function myFunc(component: IComponent) {
_.each(components (val, key) => {
if (key === 'cc') {...}
else if (value?.type === 'xxx') { <---- HERE flags error
components[key].type = 'xxxx'
}
})
}
When I add the new component caneta, Typescript complains saying:
Property 'type' does not exist on type 'IComponentCaneta'.
Tried to make type optional, but didn't work.
What would be the right thing to do in this situation?
Is there a way to explicitly say that "The attribute of type IComponent will be 'X' 'Y' or 'Z'. Something like
function myFunc(component: IComponent ['cc' or 'lajota'])
Things I tried and failed:
// make type optional
interface IComponent {
type?: string;
text: string;
}
// try to infer the object (cc, loja, caneta)
switch (type) {
case 'cc':
// ...
break;
case 'lajota':
// ...
break;
default: //'caneta'
// ...
break;
}
//using IF/ELSE
if (type === 'cc') {.../}
else if(type === 'lajota') {...}
else if(type === 'caneta') {...}
A: I found a solution using Object Entries and forEach.
I don't know if there is a "down side" yet. I just wanted a way to iterate through the components and make typescript happy.
The only solution I could think of was try to infer the object so TS could "see" the right attributes.
function myFunc (components: IComponents) {
Object.entries(components).forEach(([key, value], index) => {
if (key === 'caneta') {
components[key].property = 'Hello World';
} else if(value?.type === 'text') { <--- No longer gives me errors
components[key].type = 'NEW TYPE'
}
});
}
One thing that kind worries me is that when I was trying this code on Typescript Playground it gave me the following error/warning:
Object is possibly 'undefined'.
on the following lines:
components[key].property = 'Hello World';
and
components[key].type = 'NEW TYPE'
No errors on my vscode/lint though
| |
doc_23538758
|
The issue that is that when the anchor is clicked, the user is redirected to the agenda (the desired result), but then the ajax call to the server finishes and the table above expands and pushes the agenda down.
I have tried to wrap the table in a div with a calculated height based on the contents of the table, but the min-height seems to be applied after the fact.
Here is the url for the anchored link: http://www.grastontechnique.com/clinicians/M1_Trainings#m1-training-agenda
I will also include the code snippets pertaining to the table and ajax calls.
Here is the call to the server
$scope.loadData = function () {
$.ajax({
url: '@Url.Action("getTrainings", "Clinicians")',
data: { "trainingType": "M1" },
success: function (data) {
newData = JSON.parse(data)
index = 0;
tableHeight = 77;
trainingsTable = document.getElementById("m1-trainings-table-container");
newData["records"].forEach(function (object) {
if (newData["records"][index]["Early_Bird_Discount_Amount__c"] > 0)
{
tableHeight += 141;
}
else
{
tableHeight += 125;
}
newData["records"][index].firstDayStartTime = BuildTimeString(new Date((newData["records"][index]["First_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')));
newData["records"][index].firstDayEndTime = BuildTimeString(new Date((newData["records"][index]["First_Day_End__c"].slice(0, -9) + "Z").replace('+', '.')));
newData["records"][index].lastDayStartTime = BuildTimeString(new Date((newData["records"][index]["Final_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')));
newData["records"][index].lastDayEndTime = BuildTimeString(new Date((newData["records"][index]["Final_Day_End__c"].slice(0, -9) + "Z").replace('+', '.')));
newData["records"][index]["First_Day_Start__c"] = new Date((newData["records"][index]["First_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')).toDateString();
newData["records"][index]["Final_Day_Start__c"] = new Date((newData["records"][index]["Final_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')).toDateString();
index += 1;
});
trainingsTable.style.minHeight = tableHeight + "px";
$scope.trainingsList = newData['records'];
$scope.$apply();
}
});
};
And here is the table container
<div class="container spaced-container" ng-app="trainingsApp">
<div class="row" ng-controller="trainingsController">
<div class="col-md-8 col-md-offset-2">
<h3 class="training-section-header text-center">M1-Basic Training Schedule</h3>
<p class="text-center">To qualify for the Early Bird Special (Save $50) your registration must be paid for anytime 30-days prior to your training date.<br />
<input type="text" id="zip-input" class="locate-a-provider-input" style="margin: 25px auto; padding-left: 5px;" ng-model="searchQuery" placeholder="Search Trainings"></p>
<div id="m1-trainings-table-container">
<table class="table table-responsive calculator">
<thead>
<tr>
<th style="width: 10%" class="vertical-centered-parent"><p>State</p></th>
<th style="width: 35%" class="vertical-centered-parent"><p>Location</p></th>
<th style="width: 35%" class="vertical-centered-parent"><p>Time & Date</p></th>
<th style="width: 20%" class="vertical-centered-parent"><p>Register</p></th>
</tr>
</thead>
<tbody>
<tr class="table-row vertical-centered-parent" ng-repeat="training in trainingsList | filter:searchQuery as results">
<td class="state-td vertical-centered-parent" id="responsive-state-parent">
<span class="responsive-table-spans">State: </span>
<p class="responsive-paragraph">{{training.Venue_State__c}}</p>
</td>
<td class="location-td vertical-centered-parent">
<p class="min-width">
<span class="responsive-table-spans">Venue:<br /></span>
{{training.Venue_Name__c}}<br />
{{training.Venue_Street_Address_1__c}}<br />
{{training.Venue_City__c}}, {{training.Venue_State__c}} {{training.Venue_Postal_Code__c}}
</p>
</td>
<td class="time-date-td vertical-centered-parent">
<p class="min-width">
<span class="responsive-table-spans">Dates:<br /></span>
<span style="color: #F57149" ng-if="training.Capacity_Full__c > 80 && training.Capacity_Full__c < 99.99">Closing Soon<br /></span>
<span style="color: #F57149" ng-if="training.Capacity_Full__c >= 100">Wait List<br /></span>
<span style="color: #F57149" ng-if="training.Early_Bird_Discount_Amount__c > 0 && training.Capacity_Full__c < 100">Early Bird Special: Save ${{training.Early_Bird_Discount_Amount__c}}!<br /></span>
{{training.First_Day_Start__c}}<br />
{{training.firstDayStartTime}} - {{training.firstDayEndTime}}<br />
{{training.Final_Day_Start__c}} <br />
{{training.lastDayStartTime}} - {{training.lastDayEndTime}}<br />
</p>
</td>
<td class="sign-up-td button">
<button class="rounded-button button-sign-up" ng-click="toTraining(training.Id)">Sign Up</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Any help would be greatly appreciated.
Danny D.
| |
doc_23538759
|
create table document (id bigint not null, version int not null,
data varchar(255), primary key(id, version));
There's another table that contains a hierarchy of views. (I'm leaving out foreign keys and other constraints in this example, but they'd apply).
create table view (id bigint primary key, parent_id bigint);
And another table that contains rows that each relate a view to a set of documents. Assume that there's a unique constraint on view_doc.view_id and view_doc.doc_id, so that a given document may not appear more than once in a given view.
create table view_doc (id bigint primary key, view_id bigint not null,
doc_id bigint not null, doc_version int);
Logically, a view contains all of the document/versions it defines. A child view (which has a non-null view.parent_id) contains all the document/versions in its parent, plus any documents in itself. If different versions of a document are defined in a child view and its parent, only the version of that document specified in the child view should be visible. If a document is specified in a child view with a NULL doc_version, the document should be considered as not existing in that child view, even if it exists in its parent.
I'd like to build SQL that given a view.id will give me a list of all the documents and their respective versions in the view, as defined by the rules above (whether it is a child view or not). I know that this could ultimately result in a recursive query, but would be willing to accept a strict two-level hierarchy as well (in other words, a child view's parent_id could always be assumed to be null) if that simplifies things.
I need to represent this in Oracle, DB2, and SQL Server. It needn't be the exact same query in all three databases, though that would certainly be nice.
How would you write this query so that it runs quickly?
A: The way different DBMSs handle recursion is quite different. Here is a working query that is specifically for SQL server and is not necessarily fast. (Note that sql server limits recursion nesting to 100 levels unless you apply a query hint):
--Flatten views
;with thisView as (
select ID, 0 as nestingLevel, parent_ID
from #view
where id = @viewID
union all
select v.ID, tv.nestingLevel + 1 as nestingevel, v.parent_ID
from #view v
inner join thisView tv on v.ID = tv.parent_id
),--Determine documents/versions to present
docSets as (
select doc_ID, doc_version, ROW_NUMBER() over(partition by doc_id order by nestingLevel) as docSequence
from #view_Doc
inner join thisView tv on view_id = tv.ID
)--filter documents
select *
from docSets
where docSequence = 1
and doc_version is not null;
You mention speed at the end of your question, but you don't give any of the details necessary to determine what the best way to achieve speed would be. Using recursion is generally not very efficient in Sql Server. Further, the most efficient approach might be different between DBMS. For Sql Server 2008, look up the HierarchyID data type: http://www.codeproject.com/Articles/37171/HierarchyID-Data-Type-in-SQL-Server-2008
| |
doc_23538760
|
But, as per CocoaLumberjack's current version there is requirement of Xcode 8, they said that for backword compatibility use CocoaLumberjack 2.2.0 version for Xcode 7.2, but I'm not getting how to download CocoaLumberjack 2.2.0 version.
Thanks in advance.
A: Try this: pod 'CocoaLumberjack/Swift', '2.2.0'
if that doesn't work try this : pod 'CocoaLumberjack/Swift', '~> 2.2.0'
Also have a look at this: https://cocoapods.org
| |
doc_23538761
|
DB Initializer
namespace OProj.DataContext
{
public class OProjDbInitializer : System.Data.Entity.CreateDatabaseIfNotExists<OProjDBContext>
{
protected override void Seed(OProjDBContext context)
{
context.FeedEvents.Add(new FeedEventCommand
{
AnimalId = 1,
FeederTypeId = 2,
FeederType = "Weaned Rat"
});
base.Seed(context);
}
}
}
DbContext
using System.Data.Entity;
namespace OProj.DataContext
{
public class OProjDBContext : DbContext
{
public OProjDBContext() : base("name=OProjDB")
{
}
public DbSet<FeedEventCommand> FeedEvents { get; set; }
}
}
Global.asax.cs
namespace OProj
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer(new OProjDbInitializer());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
FeederEventCommand (using statements omitted)
namespace OProj.DataContext
{
public class FeedEventCommand
{
[Key]
public int Id { get; set; }
public int AnimalId { get; set; }
public int FeederTypeId { get; set; }
public string FeederType { get; set; }
}
}
This same structure of a contact class and DbInitializer class have worked in previous projects but this one has me stumped.
| |
doc_23538762
|
A: After further investigation I believe I can now answer this myself. A decoder only transformer doesn't actually use any memory as there is no encoder-decoder self attention in it like there is in a encoder-decoder transformer. A decoder only transformer looks a lot like an encoder transformer only instead it uses a masked self attention layer over a self attention layer. In order to do this you can pass a square subsequent mask (upper triangle) so that the model cannot look forward to achieve a decoder only model like found in GPT-2/GPT-3.
| |
doc_23538763
|
Element with short title (X)
Element with a very lo...(X)
The title should be ellipsized, but the X must be always visible. In my case, is not possible to use more than one TextView. Do you think there is a simple way of doing this?
Thanks!
A: You can try using something like this:
myTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
It might not give you exactly what you want though, it may do something like this:
Element wi...title (X)
Reference Info
TruncateAt
setEllipsize
A: I really needed a clean solution for a project so after searching around and not finding any solutions I felt I liked, I took some time to write this up.
Here is an implementation of a TextView with enhanced ellipsis control. The way it works is by using Android's Spanned interface. It defines an enum you can use to tag the specific section of text you'd like to be ellipsized if needed.
Limitations:
*
*Does not support ellipsis at MIDDLE. This should be easy to add if it's really needed (I didn't).
*This class will always render the text onto one line, as it only supports a single line of text. Others are welcome to extend it if that's needed (but it's a far harder problem).
Here's a sample of the usage:
FooActivity.java
class FooActivity extends Activity {
/**
* You can do this however you'd like, this example uses this simple
* helper function to create a text span tagged for ellipsizing
*/
CharSequence ellipsizeText(String text) {
SpannableString s = new SpannableString(text);
s.setSpan(TrimmedTextView.EllipsizeRange.ELLIPSIS_AT_END, 0, s.length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
return s;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foo_layout);
TextView textView = (TextView) findViewById(R.id.textView4);
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(ellipsizeText("This is a long string of text which has important information "));
text.append("AT THE END");
textView.setText(text);
}
}
res/layouts/foo_layout.xml
<com.example.text.TrimmedTextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
That's it
Here's an example of the result:
The Implementation
package com.example.text;
import android.content.Context;
import android.text.Editable;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TrimmedTextView extends TextView {
public static enum EllipsizeRange {
ELLIPSIS_AT_START, ELLIPSIS_AT_END;
}
private CharSequence originalText;
private SpannableStringBuilder builder = new SpannableStringBuilder();
/**
* This allows the cached value of the original unmodified text to be
* invalidated whenever set externally.
*/
private final TextWatcher textCacheInvalidator = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
originalText = null;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
public TrimmedTextView(Context context) {
this(context, null, 0);
}
public TrimmedTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TrimmedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
addTextChangedListener(textCacheInvalidator);
Log.v("TEXT", "Set!");
}
/**
* Make sure we return the original unmodified text value if it's been
* custom-ellipsized by us.
*/
public CharSequence getText() {
if (originalText == null) {
return super.getText();
}
return originalText;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Layout layout = getLayout();
CharSequence text = layout.getText();
if (text instanceof Spanned) {
Spanned spanned = (Spanned) text;
int ellipsisStart;
int ellipsisEnd;
TruncateAt where = null;
ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_START);
if (ellipsisStart >= 0) {
where = TruncateAt.START;
ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_START);
} else {
ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_END);
if (ellipsisStart >= 0) {
where = TruncateAt.END;
ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_END);
} else {
// No EllipsisRange spans in this text
return;
}
}
Log.v("TEXT", "ellipsisStart: " + ellipsisStart);
Log.v("TEXT", "ellipsisEnd: " + ellipsisEnd);
Log.v("TEXT", "where: " + where);
builder.clear();
builder.append(text, 0, ellipsisStart).append(text, ellipsisEnd, text.length());
float consumed = Layout.getDesiredWidth(builder, layout.getPaint());
CharSequence ellipsisText = text.subSequence(ellipsisStart, ellipsisEnd);
CharSequence ellipsizedText = TextUtils.ellipsize(ellipsisText, layout.getPaint(),
layout.getWidth() - consumed, where);
if (ellipsizedText.length() < ellipsisText.length()) {
builder.clear();
builder.append(text, 0, ellipsisStart).append(ellipsizedText)
.append(text, ellipsisEnd, text.length());
setText(builder);
originalText = text;
requestLayout();
invalidate();
}
}
}
}
| |
doc_23538764
|
My question is: what is the best practice for building out new instances? should it be includes in the scripts that setup the environment or separated? I'm a bit confused how the script could create instances (say EC2 instances) and accept inventory files.
A: May be that example playbook will help you, it will create the instance(s) for you and then run the tasks/roles on these created instances all in one, it will also add the ip of the newly created instances into the host file(suppose it's in the same directory,from where you are running this playbook):
---
- name: Provision an EC2 Instance
hosts: local
connection: local
gather_facts: False
tags: provisioning
# Necessary Variables for creating/provisioning the EC2 Instance
vars:
instance_type: t1.micro
security_group: test-sg
image: ami-98aa1cf0
region: us-east-1
keypair: ansible
count: 1
# Task that will be used to Launch/Create an EC2 Instance
tasks:
- name: Create a security group
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for Servers
region: "{{ region }}"
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 6800
to_port: 6800
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0
- name: Launch the new EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2
- name: Add the newly created EC2 instance(s) to the local host group
local_action: lineinfile
dest="./hosts"
regexp={{ item.public_ip }}
insertafter="[ec2server]" line={{ item.public_ip }}
with_items: ec2.instances
- name: Wait for SSH to come up
local_action: wait_for
host={{ item.public_ip }}
port=22
state=started
with_items: ec2.instances
- name: Add tag to Instance(s)
local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
with_items: ec2.instances
args:
tags:
Name: test
- name: SSH to the EC2 Instance(s)
add_host: hostname={{ item.public_ip }} groupname=ec2server
with_items: ec2.instances
- name: Install these things on Newly created EC2 Instance(s)
hosts: ec2server
sudo: True
remote_user: ubuntu
gather_facts: True
# Run these tasks
tasks:
- include: tasks/upgrade.yml
And your hosts file will be look like this:
[local]
localhost
[ec2server]
Hope, this will help you. Thanks
| |
doc_23538765
|
my error is as below.enter image description here
System.Management.Automation.CommandNotFoundException: 'The term 'Add'
is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.'
my codes are below, where could i be doing wrong? I'm waiting for your help please. I've been struggling for 3 days, I looked at all the resources but I couldn't find a solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace son1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ekle_Click(object sender, EventArgs e)
{
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
powershell.AddCommand("Add");
powershell.AddArgument("-");
powershell.AddArgument("PrinterPort");
powershell.AddArgument("-");
powershell.AddArgument("name");
powershell.AddArgument(printer_ip);
powershell.AddArgument("-");
powershell.AddArgument("PrinterHostAddress");
powershell.AddArgument(printer_ip);
powershell.Invoke();
}
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
powershell.AddCommand("Add");
powershell.AddArgument("-");
powershell.AddArgument("Printer");
powershell.AddArgument("-");
powershell.AddArgument("Name");
powershell.AddArgument(printer_name);
powershell.AddArgument("-");
powershell.AddArgument("PortName");
powershell.AddArgument(printer_ip);
powershell.AddArgument("-");
powershell.AddArgument("DriverName");
powershell.AddArgument("Canon Generic Plus PCL6");
powershell.Invoke();
}
System.Windows.MessageBox.Show("Success!");
}
}
}
A: The API is a little more sophisticated than requiring you to input every single string token manually.
AddCommand() takes the whole command name at once:
powershell.AddCommand('Add-Printer');
For named parameter arguments, use AddParameter() instead of AddArgument():
powershell.AddParameter("Name", ad);
powershell.AddParameter("PortName", ip)
// etc...
Note that the - that we usually use in front of parameter names in PowerShell scripts is not actually part of the name itself, so don't include that.
If you want to execute multiple pipelines as separate statements, call AddStatement() in between the call to AddCommand() for the first command in the next pipeline:
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
// call `Add-PrinterPort ...`
powershell.AddCommand("Add-PrinterPort");
powershell.AddParameter("Name", printer_ip);
powershell.AddParameter("PrinterHostAddress", printer_ip);
// terminate previous statement (equivalent to a newline or `;` in powershell)
powershell.AddStatement();
// then call `Add-Printer ...`
powershell.AddCommand("Add-Printer");
powershell.AddParameter("Name", printer_name);
powershell.AddParameter("PortName", printer_ip);
powershell.AddParameter("DriverName", "Canon Generic Plus PCL6");
// Invoke the whole thing at once
powershell.Invoke();
}
| |
doc_23538766
|
A: Quad core means twice as many cores as dual. This means it is able to run more applications at once. The i7 3636QM also has a larger L3 Cache meaning more data can be stored for quick access. Therefore the quad core processor seems to be better for parallel computing; even though it has a lower clock speed.
When you have a single task that needs to be done right away, multiple cores can help you by breaking the task into smaller chunks, working on each chunk in parallel, and thus you'll get your work done quicker. In lower end tasks you would probably see a higher clock speed in a dual core work better; however in more complex tasks a quad core processor with a lower clock speed is still likely to perform better. With scientific and engineering tasks(presuming these are the tasks you are expecting to do) Quad would always triumph.
| |
doc_23538767
|
I guess that this means that the location monitoring should run in background mode, but I am fairly new to android and I don't really understand about background processes or about location monitoring. Can anyone point me to a good tutorial or information?
A: to building this app that will monitor where a user is using GPS and alert him if he is within a certain distance, you will using service in background and using gps to get altitude and longitude and you will using a function to calculate a distance bitween a user location giving by gps and others location in the list and you can also start your Service on Boot Automatically.
good luck.
| |
doc_23538768
|
Apple created the UISplitViewController for this exact scenario... seemingly. I say seemingly because although I see it used in Settings, iPod, iTunes, and so on, none of those applications use UISplitViewController inside a UITabBarController, because it's not only documented as not working, but apps can crash if those two are forced into a shotgun marriage.
Consider a hypothetical iPhone application all about Animals. It has three tabs: "Categories" (where animals are categorized by some simple method -- perhaps we have a two-level hierarchy with categories like "Birds" and "Fish"), "Search" (which uses a standard UITableView and a UISearchDisplayController), and "Stories", which are stories about animals (perhaps there is a story about frogs, and another about computer nerd horses that turned into l33t unicorns).
While "Categories" and "Search" are two tabs that could be merged, it's not clear that you could or should merge the list of animals with the stories about the animals. So while you might like to use a UISplitViewController on the iPad (with the search integrated in the "root", left, side of the split), how do you present the "Stories" view? Do you use a segmented controller? Top or Bottom? "Root" or "Detail" view of the split? Or perhaps you use a "home" screen (like WebMD's iPad app) which shows two buttons ("Categories" and "Stories") and then shows a split view for whichever the user taps? Or a toolbar at the top or bottom?
I tried looking at several other apps, including Settings, Mail, iPod, iTunes, Contacts, Maps and so on, but none of them present two "different" kinds of information in one application.
What's the general approach here? Are there any best practices? Any general patterns that the iPad programming community has adopted?
Or do I wait and cross my fingers that Apple somehow eventually allows UISplitViewController to work without requiring it to be the "root"? (That might never happen!)
A: You could use the UISplitViewController and have a UITabBarController as the master view controller (the left side pane that is usually a list).
That way you could still use the tabs and drill down approaches until you read the detail view for each animal (using your analogy) and then display the detail page in the detail view controller (the right side pane).
This would work and isn't forbidden by Apple or the HIG.
That's my idea anyway :)
| |
doc_23538769
|
To do that I have to read the serial data (in this case using C#) and that works fine. But because my Arduino board needs to know when to write data to the serial I first need to send a command to the Arduino board.
Using Arduino IDE's 'Serial Monitor', I tried sending some data but it doesn't get received by the Arduino. When I place an RFID tag in front of the RFID, the Arduino board does receive data. So it seems to me like the serial port input is somehow reserved by the RFID reader? Is that even possible?
Does someone know an solution for my problem? Note that this is my first Arduino project and C is new to me.
Some info:
*
*Arduino UNO
*RFID Reader: Innovations ID12
*RTC Clock module
*C
*C#
*.NET
The code below is the whole Arduino project.
#include "Wire.h"
#include <EEPROM.h>
#include "EEPROMAnything.h"
#define DS1307_ADDRESS 0x68
byte zero = 0; //workaround for issue #527
int buttonState = 0;
byte value;
int byteaddress = 0;
int bytesize = 0;
int lastTag = 0;
byte incomingByte;
struct config_t
{
int seconds;
int hours;
int minutes;
} timestamp;
int RFIDResetPin = 13;
//Register your RFID tags here
char tag1[13] = "03000DEB55B0";
char tag2[13] = "03000DB88137";
char tag3[13] = "03000DC8E026";
char tag4[13] = "03000623FBDD";
char tag5[13] = "03000DB8B701";
void setup()
{
pinMode(7, INPUT);
Wire.begin();
Serial.begin(9600);
pinMode(RFIDResetPin, OUTPUT);
digitalWrite(RFIDResetPin, HIGH);
EEPROM_readAnything(0, timestamp);
setDateTime(); //MUST CONFIGURE IN FUNCTION
pinMode(11, OUTPUT);
}
void loop()
{
buttonState = digitalRead(7);
char tagString[13];
int index = 0;
boolean reading = false;
if (buttonState == HIGH) {
// turn LED on:
printDate();
delay(200);
}
while(Serial.available()){
buttonState = digitalRead(7);
int readByte = Serial.read(); //read next available byte
if(readByte == 2) reading = true; //begining of tag
if(readByte == 3) reading = false; //end of tag
if(reading && readByte != 2 && readByte != 10 && readByte != 13){
//store the tag
tagString[index] = readByte;
index ++;
}
incomingByte = Serial.read();
Serial.println(incomingByte);
}
checkTag(tagString); //Check if it is a match
clearTag(tagString); //Clear the char of all value
resetReader(); //eset the RFID reader
}
void checkTag(char tag[]){
///////////////////////////////////
//Check the read tag against known tags
///////////////////////////////////
int currentTag = 0;
if(strlen(tag) == 0 || strlen(tag) < 12)
return; //empty, no need to continue
if(compareTag(tag, tag1) && lastTag != 1){ // if matched tag1, do this
Serial.println("Scanned tag 1");
lastTag = 1;
currentTag = 1;
printDate();
bleepSucces(11);
}
else
if(compareTag(tag, tag2) && lastTag != 2){ //if matched tag2, do this
Serial.println("Scanned tag 2");
lastTag = 2;
currentTag = 2;
printDate();
bleepSucces(11);
}
else
if(compareTag(tag, tag3) && lastTag != 3){
Serial.println("Scanned tag 3");
lastTag = 3;
currentTag = 3;
printDate();
bleepSucces(11);
}
else
if(compareTag(tag, tag4) && lastTag != 4){
Serial.println("Scanned tag 4");
lastTag = 4;
currentTag = 4;
printDate();
bleepSucces(11);
}
else
if(compareTag(tag, tag5) && lastTag != 5){
Serial.println("Scanned tag 5");
lastTag = 5;
currentTag = 5;
printDate();
bleepSucces(11);
}
else
{
if(currentTag == 0 && lastTag == 0){
Serial.println("Unknown Tag, see below:");
Serial.println(tag); //read out any unknown tag
//resetReader();
lastTag = 0;
bleepFail(11);
}
return;
}
}
void bleepSucces(int pin)
{
digitalWrite(pin, HIGH);
delay(300);
digitalWrite(pin, LOW);
delay(20);
digitalWrite(pin, HIGH);
delay(150);
digitalWrite(pin, LOW);
}
void bleepFail(int pin)
{
digitalWrite(pin, HIGH);
delay(1200);
digitalWrite(pin, LOW);
}
void resetReader()
{ //Reset the RFID reader to read again.
digitalWrite(RFIDResetPin, LOW);
digitalWrite(RFIDResetPin, HIGH);
delay(150);
}
void clearTag(char one[])
{
//clear the char array by filling with null - ASCII 0
//Will think same tag has been read otherwise
for(int i = 0; i < strlen(one); i++)
one[i] = 0;
}
boolean compareTag(char one[], char two[])
{ //compare two tags to see if same,
//strcmp not working 100% so we do this
if (strlen(one) == 0)
return false; //empty
for(int i = 0; i < 12; i++){
if(one[i] != two[i])
return false;
}
return true; //no mismatches
}
void setDateTime()
{
byte second = 20; //0-59
byte minute = 37; //0-59
byte hour = 20; //0-23
byte weekDay = 2; //1-7
byte monthDay = 3; //1-31
byte month = 4; //1-12
byte year = 12; //0-99
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(zero); //stop Oscillator
Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(weekDay));
Wire.write(decToBcd(monthDay));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.write(zero); //start
Wire.endTransmission();
}
byte decToBcd(byte val)
{ // Convert normal decimal numbers to binary coded decimal
return val / 10 * 16 + val % 10;
}
byte bcdToDec(byte val)
{ // Convert binary coded decimal to normal decimal numbers
return val / 16 * 10 + val % 16;
}
void printDate()
{
// Reset the register pointer
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(zero);
Wire.endTransmission();
Wire.requestFrom(DS1307_ADDRESS, 7);
int second = bcdToDec(Wire.read());
int minute = bcdToDec(Wire.read());
int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
int monthDay = bcdToDec(Wire.read());
int month = bcdToDec(Wire.read());
int year = bcdToDec(Wire.read());
//Set variables in our struct
timestamp.hours = hour;
timestamp.minutes = minute;
timestamp.seconds = second;
//Save the timestamp to EEPROM
bytesize = EEPROM_writeAnything(byteaddress, timestamp);
byteaddress = byteaddress + bytesize;
//if (Serial.available() > 0) {
writeSerial();
//}
}
void writeSerial()
{
Serial.print("{");
// read a byte from the current address of the EEPROM
for (int i=0; i <= byteaddress + 4; i = i + 2){
value = EEPROM.read(i);
Serial.print(value, DEC);
if (i < byteaddress+4)
Serial.print(((i-1)%3 == 0) ? ", " : " ");
}
Serial.println("}");
}
A: The arduino UNO only has 1 serial port, pin 0 and 1 are actualy connected to the usb port.
You will need to use softwareserial to create a serial port in the software to talk to your RFID Reader and connect the RFID reader to other pins then 0 and 1
A: Sibster is correct pin 0 and 1 are used for hardware serial and USB connection to PC. use SPI, I2c or software serial for the RFID (depending on what you've got). Also you'd probably be better off using an SD card.
A: When you read from the arduino ide,
if you enter a '2' that will actually equal 50 as ('0'==48).
Try changing the if statement to readByte != '2'
Unless you are entering some kind of control character actually equal to 2.
| |
doc_23538770
|
I used a built-in WordPress function, sanitize_text_field():
function wpdocs_my_search_form( $form ) {
$search_query = sanitize_text_field( get_search_query() );
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div><label class="screen-reader-text" for="s">' . __( 'Search for:' ) . '</label>
<input type="text" value="' . $search_query . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'wpdocs_my_search_form' );
This however, is still not properly sanitizing input such as <script></script>
I also attempted to add additional code to detect if it has been submitted however, that is also not working. I would appreciate any direction/pointers.
| |
doc_23538771
|
This function gets 2 6x6 matrices and returns a vector magnified by the dimensions specified in np.linspace, i.e. 6x91. I want to store these three arrays in a file (using savetxt) by concatenating them as float numbers. Below there's a sample of the function run separately from the class, which works fine.
The problem comes when I declare the list output before the loop and by updating EulArr via a Tkinter window, append the arrays to the list. I can only save the arrays with %s format, but not anymore by %f. Why?
LegForces(self, Li, ti)
import numpy as np
from math import pi
M=100. #total estimated mass to move (upper platform+upper legs+payload)
g=9.81
nsteps= 91
Li=np.matrix([[-10.64569774, -93.1416122, 116.35191853],\
[-10.68368329, 93.17236065, 116.35542498],\
[85.985087,37.35196994, 116.20350534],[-75.34703551,-55.83790049, 115.44528196],\
[-75.33938926, 55.78964226, 115.44457613],[86.0307188,-37.33446016, 116.19929305]])
ti=np.matrix([[88.15843159,88.04450508,50.10006323, -138.28903445, -138.26610178,50.2369224],\
[-108.75675186, 108.84408749, 130.72504635, 21.82594871, -21.97569549,-130.6774372],\
[ 119.40585161, 119.40170883, 119.23577854, 118.41560138, 118.41643529,119.24075525]])
ti=ti.T #transpose the ti for compatible format
x_cm= 1.
y_cm= -1.
z_cm=87.752
z=np.linspace(0,90,nsteps)
Fx=-M*g*np.cos(pi*z/180)
Fy= M*g*np.sin(pi*z/180)
Fz=50 # including braking forces [N]
#specify here the centre of mass coordinates retrieved from Inventor
Mx=Fz*y_cm-Fy*z_cm
My=-Fz*x_cm+Fx*z_cm
Mz=Fy*x_cm-Fx*y_cm
mc=np.zeros((6,3),'float')
ex_forces=np.array([Fx,Fy,Fz,Mx,My,Mz])
for i in range(6):
mc[i,:]=np.cross(ti[i,:],Li[i,:])
r1=[Li[0,0],Li[1,0],Li[2,0],Li[3,0],Li[4,0],Li[5,0]]
r2=[Li[0,1],Li[1,1],Li[2,1],Li[3,1],Li[4,1],Li[5,1]]
r3=[Li[0,2],Li[1,2],Li[2,2],Li[3,2],Li[4,2],Li[5,2]]
r4=[mc[0,0],mc[1,0],mc[2,0],mc[3,0],mc[4,0],mc[5,0]]
r5=[mc[0,1],mc[1,1],mc[2,1],mc[3,1],mc[4,1],mc[5,1]]
r6=[mc[0,2],mc[1,2],mc[2,2],mc[3,2],mc[4,2],mc[5,2]]
DMatrix=np.vstack([r1,r2,r3,r4,r5,r6])
print 'DMatrix form:\n', DMatrix
invD=np.linalg.inv(DMatrix)
print ' inv(DMatrix) is:\n', invD
legF=np.dot(ex_forces,invD)
#slice it!
legF=legF.tolist()
a,b=np.shape(legF)
print 'check identity matrix:\n', np.dot(invD,DMatrix)
print 'leg forces:\n',legF, type(legF)
newlegF=np.reshape(legF,(1,a*b))
strokeValues= np.array([[-0.3595, .1450483, -0.3131,0.4210,-0.0825,.19124]])
print 'strokeValues shape:\n', np.shape(strokeValues)
print 'leg forces vector shape:', np.shape(newlegF)
EulArr=np.array([[0.12,0.2,0,-3.,-1.,15.]])
output=np.concatenate((strokeValues,EulArr,newlegF),axis=1)
np.savetxt('leg_forces.dat', output,fmt=' %f')
print output ,np.shape(output)
The class will look like this:
class Hexapod(self,....):
output=[]
while 1:
...
LegAxialF=self.LegForces(Li,ti)
#create a list for EUl parameters which can be refreshed
EulArr=np.zeros((6,1),'float')
EulArr[0]=180/pi*self.EulPhi
EulArr[1]=180/pi*self.EulTheta
EulArr[2]=180/pi*self.EulPsi
EulArr[3]=self.EulX
EulArr[4]=self.EulY
EulArr[5]=self.EulZ-self.height
#print meaningful values to the specified file
EulArr=np.reshape(EulArr,(1,6))
EulArrList=EulArr.tolist()
strokes=np.reshape(strokeValues,(1,6))
strokeList=strokes.tolist()
output.append(np.concatenate((strokeList,\
EulArrList,LegFList),axis=1))
np.savetxt('act_lengths.dat', output, fmt='%f')
def LegForces(self, Li, ti):
I get the following error:
np.savetxt('act_lengths.dat', output, fmt='%f')
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 1047, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: float argument required, not numpy.ndarray
A: Output is a list containing ndarrays. I think in your code, the elements of output must be ndarrays of varying size and internally NumPy is failing to convert this into a float array due to the ragged data, instead creating an array of objects*. I can reproduce your error with
>>> output = [np.random.rand(3), np.random.rand(4)]
>>> np.savetxt("test", output, fmt='%f')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/yotam/anaconda/lib/python2.7/site-packages/numpy/lib/npyio.py", line 1083, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: float argument required, not numpy.ndarray
>>>
Whereas if I instead use output = [np.random.rand(3), np.random.rand(3)] it works.
(*) i.e. you are getting
>>> np.asarray(output)
array([array([ 0.87346791, 0.10046296, 0.60304887]),
array([ 0.25116526, 0.29174373, 0.26067348, 0.68317986])], dtype=object)
| |
doc_23538772
|
What I'm trying to do is a Query that outputs price data on different pages, at the moment it works fine - however on each page i use the query I have to change the productpage name in the query. How can I automatically get the filename of the page (excluding .PHP) and insert that name into the query? (I have a corresponding column in the DB with all the different page names)
$query=("SELECT *
FROM database e
JOIN validdate1 r ON e.datevalid1=r.id
JOIN validdate2 d ON e.datevalid2=d.id
WHERE productpage='page01'
ORDER BY price2,
So rather than manually entering page01, i want it to be fetched from the file name (in this case is page01.php).
Thank you in advance!
A: echo __FILE__; outputs the current filename.
echo preg_replace('/\.php$/', '', __FILE__); outputs the current filename without '.php'.
Get the current script file name
A: Use variable interpolation in your query:
$pageName = basename(__FILE__, '.php');
$query=("SELECT * FROM database e JOIN validdate1 r ON e.datevalid1=r.id JOIN validdate2 d ON e.datevalid2=d.id WHERE productpage='$pageName' ORDER BY price2");
...or use a prepared statement and submit the page name as an argument
A: Read the php page name using below code
$page=basename($_SERVER['PHP_SELF']); /* Returns PHP File Name */
$page_name=str_replace(".php","",$page);
$query=("SELECT *
FROM database e
JOIN validdate1 r ON e.datevalid1=r.id
JOIN validdate2 d ON e.datevalid2=d.id
WHERE productpage='$page_name'
ORDER BY price2,
A: If the page link is some thing like this:
http://yourhost/abc/page1
You can get /abc/page1 by using this:
$path = parse_url($url, PHP_URL_PATH)
Depends on the structure of your URL, you can use explode to get page 1
| |
doc_23538773
|
<TabControl>
<TabControl.Style>
<Style TargetType="TabControl">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsRunning, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="SelectedIndex" Value="1" />
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.Style>
<TabItem Header="Foo" />
<TabItem Header="Bar" />
</TabControl>
The TabControl should only switch to the second tab, if the IsRunningproperty changes to True, but the problem now is, that as soon as the IsRunning property changes, the TabControl does not update itself to display the second TabItem.
Is there a way to do this through XAML, or do I have to implement a SelectedIndex property in my viewmodel, that binds directly to the SelectedIndexof the TabControl?
A: This works for me just as expected, if the property changes to true the tab switches. Maybe there's a problem with the binding? (Or did i misuderstand the question?)
A: This is an old thread but who knows someone else may stuble upon this just like me looking for an answer.
Solution: Just add a setter in TabControl style to set SelectedIndex to initial value. e.g. Setter Property="SelectedIndex" Value="0"
<TabControl>
<TabControl.Style>
<Style TargetType="TabControl">
<Setter Property="SelectedIndex" Value="0" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsRunning, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="SelectedIndex" Value="1" />
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.Style>
<TabItem Header="Foo" />
<TabItem Header="Bar" />
</TabControl>
| |
doc_23538774
|
I would like to understand how GAMG prepares the internal structures.
Does it create the internal data structures used in GAMG only once in a single iteration on the basis of the geometry and then the entries in these data structures are only updated?
OR
Does it create the interal data structures multiple times in a single iteration?
I read the documentation here but it does not have the answer.
Thanks for your answer.
| |
doc_23538775
|
How we differentiate Network & Organization
Reference : http://build.fhir.org/ig/HL7/VhDir/StructureDefinition-vhdir-network.html
A: That's a very good question. There doesn't seem to be any element in the resource that clearly distinguishes 'network' organizations from other organizations. It is not safe to use meta.profile to distinguish. Profile declarations can't ever declare semantics not already present in the instance. I.e. if you wiped all profile declarations, it should be possible to determine whether an instance was a network or not irrespective of the profile.
I'd suggest submitting a change request against the implementation guide requiring a pattern be set on Organization.code that clearly distinguishes network organizations from other organizations.
A: You can do a GET [base]/Organization?_profile=http://hl7.org/fhir/uv/vhdir/StructureDefinition/vhdir-network.
This will filter the Organizations on the profile url listed in the Organization.meta.profile field. Any Organization that is a network and conforms to the vhdir-network profile should have that field filled in accordingly.
| |
doc_23538776
|
#include <iostream>
using namespace std;
class A
{
public:
A(){}
void m(std::string* s)
{
cout<<*s;
}
void m(std::string s)
{
cout<<s;
}
};
int main()
{
A a;
string str="hi!\n";
std::thread(&A::m,a,&str);
}
this doesn't compile; it gives:
error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, A&, std::string*)’
if I remove the second member it compiles! why? I can't use overloaded methods in std::thread?
A: You can, but you have to pick the desired overload manually:
std::thread th(static_cast<void (A::*)(std::string*)>(&A::m),a,&str);
Or you could use a lambda:
std::thread th([&] { a.m(&str); });
Addendum: The reason this can't be deduced automatically is, in short, that the compiler looks only skin-deep when searching for the right constructor. Finding (making!) the right constructor from the relevant constructor template of the std::thread class involves template argument deduction, and template argument deduction looks, as a rule, only at the signatures and not the internals of a function template (in this case a constructor template, which is for our purposes the same). The relevant constructor template is
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
...which does not in itself say anything about the interplay of f and args in the depths of the implementation. There is not enough information in it to decide that only one overrload of A::m can work, so the ambiguity cannot be resolved, and you have to do it manually.
Whether it is actually possible and/or practical to make the compiler look deeper to resolve such ambiguities is an interesting question. I imagine it would be quite a challenge. Either way, it has not yet been done.
| |
doc_23538777
|
sumofsides <- function(stopvalue) {
totalsum <- 0
while (totalsum < stopvalue) {
face <- sample(6, 1, replace= TRUE)
totalsum <- totalsum + face
}
return(total value)
}
sumofsides(100)
[1] 103
When I am writing the following code to get the number of rolling till it reaches to the stop value. But it's always giving value of 1 which is wrong.
numofrolls <- function(stopvalue) {
totalsum <- 0
while (totalsum < stopvalue) {
face <- sample(6, 1, replace= TRUE)
totalsum <- totalsum + face
}
return(length(face))
}
numofrolls(100)
[1] 1
Any help is appreciated.
A: In your current loop, you are rewriting totalsum every iteration with a new value, so its length will never go beyond one. One solution would be to use a second variable to count the number of rolls:
rollUntil <- function(n) {
nRolls <- 0
sumRolls <- 0
while (sumRolls <= n) {
sumRolls <- sumRolls + sample.int(6, 1)
nRolls = nRolls + 1
}
return(nRolls)
}
# let's look at the distribution of rolls till 100:
hist(replicate(1000,rollUntil(100)))
| |
doc_23538778
|
However, I am trying to push it to a dictionary so it could be formatted as: {0 : image2, 1:image1, 2:image3}. This would allow me to see what image is at each index, so when the user clicks submit, 3 more images could be loaded in to be ranked.
Can anyone help how to get it to do this? The dictionary will not work, and the positions are currently in an array.
var ranked = {}
window.sessionStorage.setItem("ranked", JSON.stringify(ranked));
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
$(function () {
$("#items").sortable({
start: function (event, ui) {
ui.item.toggleClass("highlight");
},
stop: function (event, ui) {
ui.item.toggleClass("highlight");
var order = $(this).sortable('toArray');
var positions = order.join(';');
var rank = positions;
console.log(rank);
var result = $(this).sortable('toArray', {rank: 'value'});
console.log(result)
}
});
$("#items").disableSelection();
});
<html>
<header>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-sortablejs@latest/jquery-sortable.js"></script>
<script type="text/javascript" src="/Users/rankWebsite/js/main.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/Users/rankWebsite/css/mainstyle.css">
</header>
<body class=body>
<h1> Rank Images</h1>
<hr>
<div class="images">
<div id="items">
<img src="/Users/rankWebsite/images/image_1.jpg" id ="image1" style="width:150px;height:150px" >
<img src="/Users/rankWebsite/images/image_2.jpg" id="image2" style="width:150px;height:150px">
<img src="/Users/rankWebsite/images/image_3.jpg" id="image3" style="width:150px;height:150px">
</div>
</div>
<div class="button">
<button type="submit" onclick="submit()">Submit</button>
</div>
</body>
</html>
A: Just to make sure, ALL you wish to do is have the images sorted in an array basically right?
//i just gave the example of how to store the images as the data you wanted
function getArrayOfPictures(){
var items=$('#items')[0].childNodes //change this to wherever the list of images are stored
return Object.keys(items) //returns an array of each KEY of ITEMS
.filter(a=>items[a].tagName=="IMG") //returns ONLY the image elements
.map(a=>{
var arr=items[a].src.split('/')
return arr[arr.length-1]
}) //formats it to have just the name of the img after the last '/'
//stores data how you would like it(and when the order changes everytime you run this function it would return the ordering of it as well)
}
var itemList=getArrayOfPictures()
console.log(itemList)
var itemPointer=Object.keys(items).filter(a=>items[a].tagName=="IMG") //points to the actual image elements for more advanced things you might want to do
<html>
<header>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
</header>
<body class=body>
<h1> Rank Images</h1>
<hr>
<div class="images">
<div id="items">
<img src="https://cdn.akc.org/content/hero/puppy_pictures_header.jpg" id ="image1" style="width:150px;height:150px" >
<img src="https://www.firstforwomen.com/wp-content/uploads/sites/2/2019/07/puppy-eyes.jpg?w=715" id="image2" style="width:150px;height:150px">
<img src="https://parade.com/wp-content/uploads/2018/03/golden-puppy-life-national-geographic-ftr.jpg" id="image3" style="width:150px;height:150px">
</div>
</div>
<div class="button">
<button type="submit" onclick="submit()">Submit</button>
</div>
</body>
</html>
| |
doc_23538779
|
{"username":"one","timestamp":"2015-10-07T15:04:46Z"}---| same day
{"username":"one","timestamp":"2015-10-07T19:22:00Z"}---^
{"username":"one","timestamp":"2015-10-25T04:22:00Z"}
{"username":"two","timestamp":"2015-10-07T19:22:00Z"}
What I want to know is to count the # of unique users for a given time period. Ex:
2015-10-07 = {"count": 2} two different users accessed on 2015-10-07
2015-10-25 = {"count": 1} one different user accessed on 2015-10-25
2015 = {"count" 2} two different users accessed in 2015
This all just becomes tricky because for example on 2015-10-07, username: one has two records of when they accessed, but it should only return a count of 1 to the total of unique users.
I've tried:
function(doc) {
var time = new Date(Date.parse(doc['timestamp']));
emit([time.getUTCFullYear(),time.getUTCMonth(),time.getUTCDay(),doc.username], 1);
}
This suffers from several issues, which are highlighted by Jesus Alva who commented in the post I linked to above.
Thanks!
A: There's probably a better way of doing this, but off the top of my head ...
You could try emitting an index for each level of granularity:
function(doc) {
var time = new Date(Date.parse(doc['timestamp']));
var year = time.getUTCFullYear();
var month = time.getUTCMonth()+1;
var day = time.getUTCDate();
// day granularity
emit([year,month,day,doc.username], null);
// year granularity
emit([year,doc.username], null);
}
// reduce function - `_count`
Day query (2015-10-07):
inclusive_end=true&
start_key=[2015, 10, 7, "\u0000"]&
end_key=[2015, 10, 7, "\uefff"]&
reduce=true&
group=true
Day query result - your application code would count the number of rows:
{"rows":[
{"key":[2015,10,7,"one"],"value":2},
{"key":[2015,10,7,"two"],"value":1}
]}
Year query:
inclusive_end=true&
start_key=[2015, "\u0000"]&
end_key=[2015, "\uefff"]&
reduce=true&
group=true
Query result - your application code would count the number of rows:
{"rows":[
{"key":[2015,"one"],"value":3},
{"key":[2015,"two"],"value":1}
]}
| |
doc_23538780
|
suma = 0
while( a <= 1000):
if (a%3 == 0 or a%5 == 0):
suma = suma + a
a = a + 1
print("The final answer is: %s " % suma)
Question:
Find the sum of all multiples of 3 or 5 up till 1000.
I do know how to solve this problem by using a for loop, what I want to know is that why, when I run this code, it never shows output like a never-ending code statement. I just want to know how to do this through while loop. Thanks for your feedback :D
A: You should increment the value of a regardless of if it's a multiple of 3 or 5
while( a <= 1000):
if (a%3 == 0 or a%5 == 0):
suma = suma + a
a = a + 1
Currently, it is never getting past a = 1 because 1 is neither a multiple of 3 nor 5 so it never increments
A: Well, it's because your loop does never increment.
A: You need to move the increment line out of the if statement.
A: This is not very Python styled. Try instead:
sum_a = 0
for a in xrange(1001):
if a%3 == 0 or a%5 == 0:
sum_a += a
print("The final answer is: {}".format(str(sum_a)))
xrange(1001) will generate the values at each iteration for a. This is much more efficient and quicker than mutating a every interaction.
This way will tend to be clearer and spare a lot of mistakes.
| |
doc_23538781
|
My question is: What is the best way to store data without using multiple files?
To my mind came CSV, but I am not sure if this is a proper solution...
Thanks for answers!
A: There's always xml. You can even use linq with that: http://msdn.microsoft.com/en-us/library/system.xml.linq%28v=vs.110%29.aspx
A: If you want a real sql database, you can use SQLCe. Its a SQL Database in a file.
More Information
*
*SQL Server Compact connection strings
*Code First with SQL CE
A: I would use a JSON-like file text. Easy to Read, easy to Dump / Save and easy to modify as its supported in all major languages.
Read more here:
*
*http://en.wikipedia.org/wiki/JSON
A: If you are working with C#, you could easily use an excel worksheet. ( but as suggested json,xml, plain text will work too)
A: I would use XML if you need to store just text . It also gives you more structure.
http://forums.devshed.com/xml-programming-19/xml-alternative-databases-34313.html
A: I prefer to suggest to use XML for database.
Why:
*
*Easy to query.
*Easy to save data to.
*Easy to edit.
*Very light weight.
You can use LINQ-to-XML to "save-to and retrieve-from" data.
| |
doc_23538782
|
Is there a parser that can extract me all the functions from assembly and start line and endline of their body?
A: There's no foolproof way, and there might not even be a well-defined correct answer in hand-written asm.
Usually (e.g. in compiler-generated code) you know a function ends when you see the next global symbol, like objdump does to decide when to print a new "banner". But without all function-start symbols being visible, there's no unambigious way. That's why some object file formats have room for size metadata associated with a symbol. Like .size foo, . - foo in GAS syntax.
It's not as easy as looking for a ret; some functions end with a jmp tail-call to another function. And some call a noreturn function like abort or __stack_chk_fail (not tailcall because they want to push a return address for a backtrace.) Or just fall off into whatever's next because that path had undefined behaviour in the source so the compiler assumed it wasn't reachable and stopped generating instructions for it, e.g. a C++ non-void function where execution can/does fall off the end without a return.
In general, assembly can blur the lines of what a function is.
Asm has features you can use to implement the high-level concept of a function, but you're not restricted to that.
e.g. multiple asm functions could all return by jumping to a common block of code that pops some registers before a ret. Is that shared tail a separate function that's called with a tail-called with a special calling convention?
Compilers don't usually do that, but humans could.
As for function entry points, usually some other code somewhere in the program will contain a call to it. But not necessarily; it might only be reachable via a table of function pointers, and you don't know that a block of .rodata holds function pointers until you find some code loading from it and calling or jumping.
But that doesn't work if the lowest-address instruction of the function isn't its entry point. See Does a function with instructions before the entry-point label cause problems for anything (linking)? for an example
Compilers don't generate code like that, but humans can. (It's a handy trick sometimes for https://codegolf.stackexchange.com/ questions.)
Or in the general case, a function might have multiple entry points. Or you could describe that as multiple functions with overlapping implementations. Sometimes it's as simple as one tailcalling another by falling into it without needing a jmp, i.e. it starts a few instructions before another.
A:
I wan't to know when a function body ends in assembly, [...]
There are mainly four ways that the execution of a stream of (userspace) instructions can "end":
*
*An unconditional jump like jmp or a conditional one like Jcc (je,jnz,jg ...)
*A ret instruction (meaning the end of a subroutine) which probably comes closest to the intent of your question (including the ExitProcess "ret" command)
*The call of another "function"
*An exception. Not a C style exception, but rather an exception like "Invalid instruction" or "Division by 0" which terminates the user space program
[...] for example in c you have this brakets {} that tell you when the function body start and when it ends but how do i know this in assembly?
Simple answer: you don't. On the machine level every address can (theoretically) be an entry point to a "function". So there is no unique entry point to a "function" other than defined - and you can define anything.
On a tangent, this relates to self-modifying code and viruses, but it must not. The exit/end is as described in the first part above.
Is there a parser that can extract me all the functions from assembly and
start line and endline of their body?
Disassemblers create some kind of "functions" with entry and exit points. But they are merely assumed. No way to know if that assumption is correct. This may cause problems.
The usual approach is using a disassembler and the work to recombinate the stream of instructions to different "functions" remains to the person that mandated this task (vulgo: you). Some tools exist that claim to simplify this, but I cannot judge their efficacy.
From the perspective of a high level language, there are decompilers that try to reverse the transformation from (for example) C to assembly/machine code that try to automatize that task and will work more or less or in some cases.
| |
doc_23538783
|
What I currently have that works is:
import datetime
cww = datetime.datetime.now().isocalendar()[1]
cy = datetime.datetime.now().isocalendar()[0]
l6ww = [str(cy)[2:]+'WW'+str(w) for w in range(cww-5,cww+1)]
print l6ww
['18WW35', '18WW36', '18WW37', '18WW38', '18WW39', '18WW40']
This will work until the first WW of next year. I can think of several brute force ways of solving this, but wanted something a bit more elegant.
A: You can use datetime.timedelta():
import datetime
now = datetime.datetime.now().isocalendar()
l6ww = [(datetime.datetime.now() - datetime.timedelta(weeks=x)).isocalendar() for x in range(6)]
final = [str(i[0])[2:] + 'WW' + str(i[1]) for i in l6ww][::-1]
Yields:
['18WW35', '18WW36', '18WW37', '18WW38', '18WW39', '18WW40']
This will work even as you pass into a new year, either forward x weeks or in the past x weeks. You can slightly modify this code to progress forward as well:
l6ww = [(datetime.datetime.now() + datetime.timedelta(weeks=x)).isocalendar() for x in range(15)]
final = [str(i[0])[2:] + 'WW' + str(i[1]) for i in l6ww]
Yields:
['18WW40', '18WW41', '18WW42', '18WW43', '18WW44', '18WW45', '18WW46', '18WW47', '18WW48', '18WW49', '18WW50', '18WW51', '18WW52', '19WW1', '19WW2']
| |
doc_23538784
|
The problem is that it only works when I'm on the page with the fields I'm trying to fill in! I've tried everything but I'm at a loss. Can anyone help me out? Here's the code:
javascript: (function() {
title = document.title;
url = document.URL;
text = document.getSelection();
w = window.open('My site');
w.onload = function run() {
w.$('#id_title').val(title);
w.$('#id_url').val(url);
w.$('#id_description').val(text);
}
})();
Any help is greatly appreciated, as I'm a a js novice.
A: I believe you are hitting a X-site scripting security measure. A page from site A can't modify a page from Site B.
And/or you are using jQuery to set values in the popup window... is jQuery loaded in the main source window? or do you load it yourself?
| |
doc_23538785
|
http://myserver/Shared%20Documents/Adds2011.xls
However when passing this to the following web routine I receive an error. Here is the routine:
Private Sub OpenExcel(myurl As String)
Dim xlApp As New exServices.ExcelService
xlApp.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim status(10) As exServices.Status
Dim sessionID As String = ""
Try
sessionID = xlApp.OpenWorkbook(myurl, "en-US", "en-US", status)
Dim sheetInfo() As exServices.SheetInfo = xlApp.GetSheetNames(sessionID, status)
Dim cell As Object = xlApp.GetCell(sessionID, sheetInfo(0).Name, 1, 1, True, status)
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
If sessionID <> "" Then
xlApp.CloseWorkbook(sessionID)
End If
End Sub
I receive the following error:
A first chance exception of type 'System.Web.Services.Protocols.SoapException' occurred in System.Web.Services.dll
System.Web.Services.Protocols.SoapException: The workbook that you selected cannot be opened.
The workbook may be in an unsupported file format, or it may be corrupt.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at SMSMInventory.exServices.ExcelService.OpenWorkbook(String workbookPath, String uiCultureName, String dataCultureName, Status[]& status)
at SMSMInventory.LoadSpreadsheetUserControl.OpenExcel(SPFile mySpFile)
Auto-attach to process '[4292] w3wp.exe' on machine 'FS-CHI-SPDEV' succeeded.
A first chance exception of type 'System.Web.Services.Protocols.SoapException' occurred in System.Web.Services.dll
Can anyone tell me what I'm doing wrong?
A: After contacting Microsoft support, they pointed out my Error:
You cannot open a .xls in the browser (see below URL):
Differences between using a workbook in Excel and Excel Services
http://office.microsoft.com/en-us/excel-help/differences-between-using-a-workbook-in-excel-and-excel-services-HA010021716.aspx
All other Microsoft Office Excel file formats are unsupported, including Office Excel 2007 Macro-Enabled Workbook (.xlsm) and Office Excel 2007 97-2003 Workbook (.xls).
Save as .xlsx and try again.
Using the recommended format solved my problem.
| |
doc_23538786
|
rgx = "(?P<start>INSTALLED_APPS.*?)\)"
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
)
match = re.search(rgx, content, re.DOTALL)
grabs
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
but for some reason when I go to sub it, with a new app, like
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'my-new-app',
text, n = re.subn(rgx, new_string, content, re.DOTALL)
it doesn't sub anything. I ran as subn and proved it wasn't matching. This makes no sense, because I am using the exact same regex that just made a match. How can I get the exact same regex to match and then not match the exact same string?
A: You use re.DOTALL for the count argument. Use it for flags instead:
re.subn(rgx, new_string, content, flags=re.DOTALL)
| |
doc_23538787
|
A: There is a number of "mobile" operating systems and we are not telepathic enough to figure out which one you're talking about in order to provide troubleshooting instructions. I assume you use Android as it is about 75% of market.
*
*Make sure to start JMeter's HTTP(S) Test Script Recorder prior to amending mobile device proxy settings
*Make sure JMeter and mobile device are on the same subnet (connected to the same WiFi network)
*Make sure that port 8888 is open in your operating system firewall
*On certain Android versions you cannot set system proxy for HTTPS traffic, you will need to install a separate application like ProxyDroid for this
*If nothing helps you can always consider an alternative way of recording mobile traffic, in this case you won't have to worry about proxies and certificates and you will get confidence that your device is connected to the Internet. See Testing Mobile sites and Apps article for more details.
A: I am very late here, but still this may help others who are still facing this issue.
In beginning i faced the same issue. Then, I tried by disabling the firewall. It worked fine.
Also disabling firewall may create a way for malicious contents to enter. Try only for trusted sources.
| |
doc_23538788
|
This Camera has available OnNewFrame event, so I'll initialize:
camera.OnNewFrame += frameAcquired;
frameAcquired is also member of Engine class.
private void frameAcquired(object sender, EventArgs e)
{
/* this event should periodically raise after ~17ms,
but sometimes it hangs for a short time
(when I overloads main thread) */
}
The Engine object is a member of MainForm class. Here I am displaying images from camera and doing some other graphics stuff. The problem is that MainForm thread sometimes hangs for a very short time. It's not so critical for displaying, but it is for camera.OnNewFrame event (I'm working with 60 fps), as this is also delayed because of main thread delay.
Is it possible to ensure some way, that Engine object (or Camera object in Engine) will raise event's from it's own thread, not from main thread? Other words, ensure that this event raises in rate which SDK producer has set, not dependent on my main thread.
A: I have ran into a similar problem not too long ago. I have dealt with it in C++/CLI so the same approach should also work in C# too.
I believe you have the Engine class initialized in your MainForm. If you want to raise events from another thread then this object has to be initialized in another thread.
I believe you should try creating a new Thread in your MainForm constructor:
MyForm()
{
//rest of your constructor
cameraThread = new Thread(new ParameterizedThreadStart(CameraRun));
cameraThread.Name = "Camera Thread";
cameraThread.Start(this);
while (!cameraThread.IsAlive)
Thread::Sleep(1);
}
This way you can keep a field for cameraThread in your MyForm class. Still, you need to write a function for the new thread to run. We know it will initialize your Engine class but that is not all. Just to make sure the thread doesn't finish the function you gave it to run, add some check at the bottom of thread function like this:
void CameraRun(Object myForm)
{
//you can use (myForm as MyForm)
//and make calls from here
/*
Engine initialization etc
*/
while((myForm as MyForm).isShown)
Sleep(100);
}
cameraThread should join back to your main code in MainForm destructor.
~MyForm()
{
//rest of your destructor
this.isShown=false;
cameraThread.Join();
}
You can put the line this.isShown=false to your OnFormClosed() event if you wish.
If you have come this far, great. However you are not done yet, unfortunately. As you are now working on multiple threads you have to make sure you access objects in a thread safe manner. Long story short, check this answer.
Edit: some corrections
| |
doc_23538789
|
=COUNTIFS(F:F,J6)
A: You have to use the IF function to check for the result.
=IF(COUNTIFS(F:F,J6)>0,COUNTIFS(F:F,J6),"")
If you have Excel 365 you can use a LET-function to avoid counting twice:
=LET(result,COUNTIFS(F:F,J6),
IF(result>0,result,""))
Or you use a special numberformat (with your original formula):
0;;
which will not show negative numbers and 0
A: Alternatively you can try-
=TEXT(COUNTIFS(F:F,J6),"0;;;")
| |
doc_23538790
|
I could not find a JavaScript runtime. See sstephenson/ExecJS (GitHub) for a list of available runtimes (ExecJS::RuntimeUnavailable).
What do I need to do to get this working?
A: Add following gems in your gem file
gem 'therubyracer'
gem 'execjs'
and run
bundle install
you are done :)
A: In your Gem file, write
gem 'execjs'
gem 'therubyracer'
and then run
bundle install
Everything works fine for me :)
A: For amazon linux(AMI):
sudo yum install nodejs npm --enablerepo=epel
A: I had this same error but only on my staging server not my production environment. nodejs was already installed on both environments.
By typing:
which node
I found out that the node command was located in: /usr/bin/node on production
but: /usr/local/bin/node in staging.
After creating a symlink on staging i.e. :
sudo ln -s /usr/local/bin/node /usr/bin/node
the application then worked in staging.
No muss no fuss.
A: I had a similar problem: my Rails 3.1 app worked fine on Windows but got the same error as the OP when running on Linux. The fix that worked for me on both platforms was to add the following to my Gemfile:
gem 'therubyracer', :platforms => :ruby
The trick is knowing that :platforms => :ruby actually means only use this gem with "C Ruby (MRI) or Rubinius, but NOT Windows."
Other possible values for :platforms are described in the bundler man page.
FYI: Windows has a builtin JavaScript engine which execjs can locate. On Linux there is not a builtin although there are several available that one can install. therubyracer is one of them. Others are listed in the execjs README.md.
A: Ubuntu Users
I'm on Ubuntu 11.04 and had similar issues. Installing Node.js fixed it.
As of Ubuntu 13.04 x64 you only need to run:
sudo apt-get install nodejs
This will solve the problem.
CentOS/RedHat Users
sudo yum install nodejs
A: Just add ExecJS and the Ruby Racer in your gem file and run bundle install after.
gem 'execjs'
gem 'therubyracer'
Everything should be fine after.
A: I used to add the Ruby Racer to the Gem file to fix it. But hey, Node.js works!
A: Adding the following gem to my Gemfile solved the issue:
gem 'therubyracer'
Then bundle your new dependencies:
$ bundle install
A: Don't Use RubyRacer as it is bad on memory. Installing Node.js as suggested by some people here is a better idea.
This list of available runtimes that can be used by ExecJs Library also documents the use of Node.js
https://github.com/sstephenson/execjs
So, Node.js is not an overkill, and much better solution than using the RubyRacer.
A: FYI, this fixed the problem for me... it's a pathing problem:
http://forums.freebsd.org/showthread.php?t=35539
A: I installed node via nvm and encountered this issue when deploying with Capistrano. Capistrano didn't load nvm automatically because it runs non-interactively.
To fix, simply move the lines that nvm adds to your ~/.bashrc up to the top. The file will then look something like this:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
A: An alternative way is to just bundle without the gem group that contains the things you don't have.
So do:
bundle install --without assets
you don't have to modify the Gemfile at all, providing of course you are not doing asset chain stuff - which usually applies in non-development environments. Bundle will remember your '--without' setting in the .bundle/config file.
A: The answer on a Mac in 2022 is simply:
brew install nodejs
Then rerun rails server.
A: I started getting this problem when I started using rbenv with Ruby 1.9.3 where as my system ruby is 1.8.7. The gem is installed in both places but for some reason the rails script didn't pick it up. But adding the "execjs" and "therubyracer" to the Gemfile did the trick.
A: In your gem file
Uncomment this line.
19 # gem 'therubyracer', platforms: :ruby
And run
bundle install
You are ready to work. :)
A: Attempting to debug in RubyMine using Ubuntu 18.04, Ruby 2.6.*, Rails 5, & RubyMine 2019.1.1, I ran into the same issue.
To resolve the issue, I uncommented the mini_racer line from my Gemfile and then ran bundle:
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
Change to:
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'mini_racer', platforms: :ruby
A: I'm using Rails 7 and the bootstrap 5.2.3 Gem. On production it runs in a Docker Container, based on Alpine Linux. For my case it was not enough to install nodejs and npm. I had to install yarn like this:
apk add --no-cache yarn
Only after that, the error message disappeared on production.
| |
doc_23538791
|
But cefsharp is only showing 4 options - back, forward, print, view source. There is no copy shortcut option.
I have not initialized the browser with any settings. Just created a chromiumbrowser item and added it to the controls on the form.
Anyone knows why this is happening? I also tried to add a menu item but can't do that as i keep getting an error - "you must use new keyword". Also there is no copy shortcut method in browser which i can call through code.
Can someone help me and explain how to achieve this? How to add more options to right click and how to right click and copy link address. Or recommend me some other browser component? I have tried awesomium but half of the sites don't load on it.
A: You can create your own context menu by implementing IContextMenuHandler. You didn't specify if you're using the WinForms or WPF version, but there ample examples on GitHub for both.
WinForms
https://github.com/cefsharp/CefSharp/blob/master/CefSharp.WinForms.Example/Handlers/MenuHandler.cs
WPF
https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Wpf.Example/Handlers/MenuHandler.cs
For either flavour, you assign your IContextMenuHandler implementation to the MenuHandler property of ChromiumWebBrowser. In this instance, I'm following the GutHub WinForms example and implemented IContextMenuHandler in a class called MenuHandler. Below is an example for WinForms but it can be easily transposed to WPF.
internal class MenuHandler : IContextMenuHandler
{
private const int Copy = 26503;
void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
{
//Add new custom menu items
model.AddItem((CefMenuCommand)Copy, "Copy Link Address");
}
bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
{
if ((int)commandId == Copy)
{
//using System.Windows.Forms;
Clipboard.SetText(parameters.SourceUrl);
}
return false;
}
void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
{
}
bool IContextMenuHandler.RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
{
return false;
}
}
Then it's just a case of assigning an instance to the MenuHandler property of ChromiumWebBrowser
browser.MenuHandler = new MenuHandler();
| |
doc_23538792
|
i have search on stackoverflow advice me to do network thread in background AsyncTask so before use backgroundtask,
My screen look like this http://imgur.com/PlhS03i show multiple rows in nutrition's and ingredient tags after using backgroundtask my screen look like this http://imgur.com/zUvxNpy show only single row in ingredients and nutrition tags
before background task code is this see below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(cla);
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString(
"description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
After using AsyncTask see this code below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;
int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
table = (TableLayout) findViewById(R.id.table2);
table3 = (LinearLayout) findViewById(R.id.table3);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new getDataTask().execute();
// listview.setAdapter(cla);
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
txt1.setText(name);
txt3.setText(description);
androidAQuery.id(img1).image(url1, false, false);
table.addView(row);
table3.addView(row2);
listview.setAdapter(cla);
}
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
name = school2.getJSONObject(0).getString("name");
description = school2.getJSONObject(0).getString(
"description");
url1 = school2.getJSONObject(0).getString("image");
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
row = createRow(school3.getJSONObject(s));
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row2 = createRow2(school5.getJSONObject(i));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
Please Help
Thanks in Advance...:)
A: Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
private static Handler handler;
handler = new Handler();
handler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
public static Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
A: You can use **runOnUiThread()** like this:
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
A: You need to create AsyncTask class and use it
Read here more: AsyncTask
Example would look like this:
private class UploadTask extends AsyncTask<Void, Void, Void>
{
private String in;
public UploadTask(String input)
{
this.in = input;
}
@Override
protected void onPreExecute()
{
//start showing progress here
}
@Override
protected Void doInBackground(Void... params)
{
//do your work
return null;
}
@Override
protected void onPostExecute(Void result)
{
//stop showing progress here
}
}
And start task like this:
UploadTask ut= new UploadTask(input);
ut.execute();
A: you are handling ui in these methods
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
which are called in background thread
if possible do it in onPostExecute or you can use runOnUiThread and Handler.
| |
doc_23538793
|
function testJQueryClick(){
$('#button2').click(function(){ alert ('Debug'); return false; });
}
When I call the function once (and then click on button 2), I get the expected alert. When I call the same function a second time and then click button 2, I get two alerts, third time I get three, etc. jQuery seems to be appending the .click event each time, rather than replacing it.
I would expect that the .click handler to be replaced each time I call it. I can't find anything in the jQuery documentation that either confirms this as the expected behaviour, or not.
A: You'll want to first call off the get rid of the old event listener:
function testJQueryClick () {
$('#button2').off('click').on('click', function () {
alert ('Debug');
return false;
});
}
See it in the Pen in action.
A: Check out the documentation for the bind() method at http://api.jquery.com/bind/. The event binding method's such as "click()", "focus()", etc... are just shortcuts for bind(eventtype) so reading the bind() docs will give you insight into how all of the event binds work. I think the bit that pertains to your specific issue is:
"When an event reaches an element, all handlers bound to that event type for the element are fired."
Meaning if you bind the handler "function(){ alert ('Debug'); return false; }" to the click event 5 times, all 5 will execute.
As a sidenote, the preferred and more modern way to bind to an onclick handler is to completely bypass the "onclick" attribute of a link and perform all your binds on DOM load using jQuery. Here's an example that uses more modern binds and also utilizes the trigger() method to fire the #button2 click handler when #button1 is clicked (which is what I think you were trying to achieve in your example):
$(document).ready(function() {
$('#button2').click(function(){ alert ('Debug'); return false; }); // Bind alert to #button2 click
$('#button1').click(testJQueryClick); // Bind testJQueryClick() to #button1 click
});
function testJQueryClick(e) {
$('#button2').trigger('click'); // Trigger #button2 click handler
}
A: while binding an event jquery does not consider what events are already bound on the control it just binds one more event..
unbind eg:
$('selector').unbind("eventType");
you could use the unbind API to remove the bound event first or if its the same click event handler but you are calling it multiple times since a new control with the same selector has been inserted to the dom then you should probably look at using the live api..
Hope tihs helps..
A: As previously noted you need to remove old click handlers before you add the new one if you want to replace it.
As of jQuery 1.7 the preferred way is to use off. (unbind is deprecated as of jQuery 3)
For example:
function testJQueryClick(){
$('#button2').off('click').click(function(){alert ('Debug'); return false;});
}
A: It's because every time you are assigning a new click handler. It should just be this:
$('#button2').click(function(){ alert ('Debug'); return false; });
After the document loads of course.
| |
doc_23538794
|
loadLocalSubServices$: Observable<Action> = this.actions$.pipe(
ofType(LocalSubServiceTemplateActions.LocalSubServicesTemplateActionTypes.LoadLocalSubService),
map((action: LocalSubServiceTemplateActions.LoadLocalSubService) => action.payload.globalSubServiceId),
// and below I would like to pass globalSubServiceId
withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))),
map(searchParams => searchParams[1]),
mergeMap((params) =>
this.subServiceService.getLocalSubServices(params).pipe(
map(localSubServices => (new LocalSubServiceTemplateActions.LocalSubServiceLoadSuccess(localSubServices))),
catchError(err => of(new LocalSubServiceTemplateActions.LocalSubServiceLoadFail(err)))
)
)
);
A: You should be able to use an arrow function.
loadLocalSubServices$: Observable<Action> = this.actions$.pipe(
ofType(LocalSubServiceTemplateActions.LocalSubServicesTemplateActionTypes.LoadLocalSubService),
map((action: LocalSubServiceTemplateActions.LoadLocalSubService) => action.payload.globalSubServiceId),
(globalSubServiceId) => {
return withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId))));
},
map(searchParams => searchParams[1]),
mergeMap((params) =>
this.subServiceService.getLocalSubServices(params).pipe(
map(localSubServices => (new LocalSubServiceTemplateActions.LocalSubServiceLoadSuccess(localSubServices))),
catchError(err => of(new LocalSubServiceTemplateActions.LocalSubServiceLoadFail(err)))
)
)
);
A: You can now use the concatLatestFrom to handle this.
Replace:
withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))),
with:
concatLatestFrom(globalSubServiceId =>
this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))
https://v11.ngrx.io/api/effects/concatLatestFrom
A: I think I have the recipe you (or future wanderers) are looking for. You have to map the initial payload (of operator below) to an inner observable so that it can be piped and passed as a param to withLatestFrom. Then mergeMap will flatten it and you can return it to the next operator as one array with the initial payload as the first value.
map(action => action.payload),
mergeMap((id) =>
of(id).pipe(
withLatestFrom(
this.store.pipe(select(state => getEntityById(state, id))),
this.store.pipe(select(state => getWhateverElse(state)))
)
),
(id, latestStoreData) => latestStoreData
),
switchMap(([id, entity, whateverElse]) => callService(entity))
| |
doc_23538795
|
(id, intcol1, intcol2, intcol3, ...)
Sample data:
123, 582585, 25215718, 15519
234, 2583, 2371, 1841948
345, 42389, 234289, 234242
I want to run some aggregate calculations using outside data to group the data by. The data I have is of the form:
(id, groupcol)
Sample data:
123, "January",
234, "February"
345, "January"
In this case, suppose I want the SUM of intcol1 using the provided groupings to match IDs, the result would be:
"January", 624974 # 42389 + 582585
"February", 2583
My question is: How do I get the "group data" into the query? Using a WITH clause and JOINING it against the maintable? Or adding it to a temporary table and using that in a following query?
I can manipulate the data I have and format it however way is easiest from the program running the SQL query.
What is the best / fastest / simplest method?
Edited for clarity
A: That looks like a simple join and group by:
select t2.groupcol,
sum(t1.intcol1)
from maintable t1
join table_2 t2 on t1.id = t2.id
group by t2.groupcol;
If you don't have that "outside" data in a table, you can do something like this:
select t2.groupcol,
sum(t1.intcol1)
from maintable t1
join (
values
(123, 'January'),
(234, 'February'),
(345, 'January')
) as t2 (id, groupcol) on t1.id = t2.id
group by t2.groupcol;
| |
doc_23538796
|
extends('layouts.main')
Now in some pages, I need to send a successful message and in other pages not. I implemented that like this:
return....->with(array(
sucessfulMessage => 'asdf'
));
Please note that I do that just in some pages not in all pages.
Now I want to use that variable in JavaScript. I did this in the layout.main:
<head>
{{ HTML::script('/js/jquery-2.1.1.js')}}
@if(isset($successfulMessage))
<script>
var successfulMessage = "{{$successfulMessage}}";
</script>
@endif
{{ HTML::script('/js/myPopupScript.js')}}
</head>
and then in myPopupScript.js I did this:
$(document).ready(function(){
if(!typeof successfulMessage === 'undefined'){
alert(successfulMessage);
}else{
alert("test");
}
});
My problem
The alert is always test even though when the successfulMessage has been sent.
Important note
When I use F12 in Google Chrome to see the actual HTML, I can see this:
<script>
var successfulMessage = "asdf";
</script>
so the variable is defined.
A: The code that works for me is this:
$(document).ready(function(){
var typeOfSuccessfulMessage = typeof successfulMessage;
if(typeOfSuccessfulMessage == 'string'){
alert(successfulMessage);
}else{
alert("undefined");
}
});
Many thanks for @martinezjc, @lowerends and @Cthulhu
A: Change this piece of code:
Edit:
Try to change the condition in your if/else javascript block
$(document).ready(function() {
@if(isset($successfulMessage))
var successfulMessage = {{$successfulMessage}};
@endif
if( !typeof successfulMessage === 'undefined' ) {
alert("test");
} else {
alert(successfulMessage);
}
});
Hope this works :)
| |
doc_23538797
|
*
*Check if model is new.
*If new, AJAX GET from validate() to see if model exists already (by title).
*If response = duplicate set status invalid, if not proceed with save()
The problem Im having is that Backbone is doing the following.
*
*save()
*validate() : GET returns not duplicate
*validation passed, set()
*validate() : GET returns duplicate
My question is about how to prevent that second validate() from firing on the set because it triggers another GET request and I get an error response even though technically Im "done" saving.
To keep this short here is the validate, and save calls
List = Backbone.Model.extend({
idAttribute: "_id",
urlRoot: '/api/lists',
...
validate: function(attrs) {
// if we are editing don't bother with this (for now)
if (this.isNew()) {
// see if this title already exists
var result = '';
$.ajax({
url: "/api/lists/" + this.generateTitleKey(attrs.title),
type: "GET",
async: false,
success: function(data){
result = data;
}
});
if(result.length > 0) {
return {
field: "title",
errMsg: "You already have this list"
};
}
}
}
});
ListView = Backbone.View.extend({
...
save: function() {
var _self = this;
var fields = {
title: _self.$el.find('input[name="new-list-name"]').val()
}
_self.resetErrors();
_self.model.save(fields, {
wait: true,
silent: true,
success: function(model, res) {
if(res.err) {
// add UI error
} else {
new app.View({ model: _self.model });
_self.close();
}
},
error: function(model, res) {
console.log('inside error');
}
})
}
});
app.post('/api/lists', function(req, res){
var list = new ListModel({
titleKey: generateTitleKey(req.body.title),
title: req.body.title
});
return list.save(function(err){
if(!err) {
return res.send(list);
} else {
return res.status(409).send(JSON.stringify({
err: true,
errSrc: "list",
errType: "insert",
errMsg: "That's already a list!"
}));
}
});
});
silent: true doesnt seem to be working for me, save() and set() both trigger validate().
I know there are a number of approaches to doing error handling for validation but I'm purposely trying to use the native valide method that a backbone Model has, and its been working great UNTIL I try to use it with the ajax call. Im so close here I can taste it.
A: You can tell the model not to validate a set with model.set('something', true, { validate: false });. FYI you can do the same in the .save options hash if you need to.
What are you setting anyway? Normally the server response is the attributes you want to save on the client model so maybe you can return what you need on that and avoid calling set.
A: Dominic Tobias led me to the right answer.
isNew() wont work as a check because on the response from the server, the model is validated BEFORE it's set, so isNew() is still technically true at the time of validation for the post save() set. I changed the check in validate() to if(attrs._id) and everything works.
| |
doc_23538798
|
Possible Duplicate:
jQuery $(this) vs this
This code in this video Tutorial
in a Very useful blog jquery for designers
$('.navigation').each(function () {
var $links = $('a',this);
$links.click(function () {
var $link = $(this),
link = this;
if ($link.is('.selected')) {
return;
}
$links.removeClass('selected');
$link.addClass('selected')
});
});
What is the difference between $(this) and this?
Please explain the simple difference in coding.
A: Within the handler being pased into click, this will refer to the DOM element that the click handler was attached to. Calling $() on it ($(this)) wraps that up in a jQuery instance, making various jQuery functions available to you.
In your quoted code, the link = this line is unnecessary as nothing ever uses link. The $link = $(this) line, though, creates a jQuery wrapper around the link so you can use functions like is and addClass.
Off-topic
*
*You probably want to change if ($link.is('.selected')) to if ($link.hasClass('selected')) so that jQuery doesn't have to parse the CSS selector.
*You have a typo, the "o" in removeClass is missing.
A: this is native JavaScript that references the current object in scope. $(this) is jQuery wrapped (adding additional properties) to that priormentioned object. Examples:
Plain JS
var person = {
SayGoodbye: function(){
this.wave();
this.exit();
},
wave: function(){
//code to wave
},
exit: function(){
//code to exit
}
}
person.SayGoodbye();
Some jQuery
//a submit button
$('#myBtn').click(function(){
$(this).attr('disabled', true);
$(this).text("Submitting...");
});
A: // get everything with the class navigation
$('.navigation').each(function () {
// get all anchor tags in that context
var $links = $('a',this);
// assign a listener for the click event.
$links.click(function () {
// set $link = jQuery wrapper around this
var $link = $(this),
// set link = this;
link = this;
// if the link has the selected class do nothing
if ($link.is('.selected')) {
return;
}
//otherwise remove it and then add it again???
$links.remveClass('selected');
$link.addClass('selected')
}); // exit anchor loop
}); // exit nav. loop
P.S. the link variable is unused above.
A: 'this' is the DOM element as accessible by normal JavaScript, whereas when you turn this into $(this), you are creating a JQuery object with more jQuery added API out of that DOM element.
| |
doc_23538799
|
My reasoning would say yes, because the computing is distributed between machines at different physical locations and a network is required.
But i think most people considers distributed computing as strictly parallel, whereas webapps don't run in parallel ... they run sequentially.
So, could Web Apps be considered as a serial kind of distributed computing, or distributed computing is strictly parallel ?
Thanks in advance.
A: Yes Web Applications are distributed computing.
You have User View, Applicaion Tier and the Database. Also called as 3-tier architecture.
User view is where you have the UI or he frontend. Application tier is where you have your business logic and then you have the database. They can be be on three different systems.
Of course, sometimes, the application and the database are present on the same system, in this case its a 2-tier architecture, but is still distributed.
Three tier architecture
A: You can easily identify a distributed system, because it will randomly crash because a machine you don't even need has given up the ghost.
In the most simple instance of a Web App, you have two "tiers": The application server and the user's browser (or whatever client is used to access the application; one could argue that the client is not part of the system, thus it would not be distributed).
Most web apps at least talk to a database, and unless it's in in-process DB (like H2 or Sqlite), you most certainly have another tier. Now we have the start of a distributed system.
So in short: It depends. Most Web Apps are distributed, but it's not a given.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.