_id stringlengths 2 6 | text stringlengths 4 46k | title stringclasses 1 value |
|---|---|---|
d11101 | As per the documentation:
Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds. | |
d11102 | you can use stop() method:
Stop the currently-running animation on the matched elements.
$("#out").mouseover(function () {
$("#in").stop(true, true).animate({"height":"toggle"},200);
});
A: First of all, you should take the advice given by me and by Raminson. The stop() function will halt all currently running animations on the given element and prevent the behavior you were seeing.
Another 2 things can be said about the code you posted.
*
*You have a trailing comma in the parameters you gave to the .animate() function.
{"height":"toggle",}. Now that might work on Chrome and Firefox, but in IE that will probably not work and more over it probably won't tell you where or why it's not working. You should never have trailing commas in an array or object in JavaScript....
*You wrapped your jQuery call in the document ready handler (as you should) but then you wrapped your code within another ready handler for each element.$("#in").ready()... $("#out").ready(). This is unnecessary. You only need one ready function to make sure the DOM and jQuery are loaded. | |
d11103 | I use a slightly different Content-Type (which shouldn't matter):
[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
And I use a slightly different PHP, too:
<?php
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$json_data = json_decode($http_raw_post_data, true);
echo json_encode($json_data);
?>
If you're getting a blank response, I'd wager you have some PHP error. I'd you check out your server's error log, or temporarily changing the display_errors setting in your php.ini as follows:
display_errors = On | |
d11104 | Try using this
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTimeOffset StartDate { get; set; } | |
d11105 | I think the issue here is that you are not specifying which user you want to impersonate in the domain (and you haven't configured the security settings in your domain to authorize the service account to impersonate users in the domain).
The doubleclick API auth documentation has good examples on how to do this. You can use their sample and replace the scopes and API endpoint:
https://developers.google.com/doubleclick-publishers/docs/service_accounts#benefits | |
d11106 | The top 100 variable should be a list, then append a dictionary
top100 = []
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100.append({'title':title,'price':price})
print( top100)
A: You need to make top100 a list with many nested dictionaries, with the following code:
top100 = []
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100.append({'title':title,'price':price})
A: Here for the another version of result
top100 = {'title':[],'price':[]}
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100['title'].append(title)
top100['price'].append(price)
print( top100)
This should output
{'title':[..., ..., ... ],'price':[..., ..., ...]}
A: thanks for the answer i was able to find my own solution,
top100 = []
for product in product_list:
titles = product.xpath('a[@class="someLink"]/text()')
prices = product.xpath('div[@class="somePrice"]/text()')
for title, price, in zip(titles, prices):
top100.append({'title':title, 'price':price})
output:
top100 = [{'title': 'title1', 'price': '100'},
{'title': 'title2', 'price': '200'}] | |
d11107 | I am not sure but you can get the list of services for sharepoint by constructing a url like below.
http://yoursharepointhostname/_vti_bin/lists.asmx | |
d11108 | if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) { is your problem.
In JavaScript, the sort method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7
Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
function palindrome(str) { return str.split("").reverse().join("") == str;}
A: It is because string subtraction yields NaN, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding, you sort the entire string, then for instance the string abba would be sorted front to back as aabb and back to front as bbaa. (edit: and also what Carl wrote about sort changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse on the array) and compare.
A: You might do as follows;
var isPalindrome = s => { var t = s.toLowerCase()
.replace(/\s+/g,"");
return [].slice.call(t)
.reverse()
.every((b,i) => b === t[i]);
};
console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));
A: function pal()
{
var x=document.getElementById("a").value;
//input String
var y="";
//blank String
for (i=x.length-1;i>=0;i--)
//string run from backward
{
y=y+x[i];
//store string last to first one by one in blank string
}
if(x==y)
//compare blank and original string equal or not
{
console.log("Palindrome");
}
else
{
console.log("Not Palindrome ");
}
} | |
d11109 | It is, but the problem is that protobuf-net assumes (due to the concatenatable nature of the protobuf format) that it should extend (append to) lists/arrays, and your field-initializer is starting it at length 2.
There are at least 3 fixes here:
*
*you can add SkipConstructor=true to the ProtoContract, which will mean it doesn't run the field initializer
*there is a "replace lists" syntax on ProtoMember which tells it to replace rather than append (I can't remember the actual option, but it is there)
*you can add a before-deserialization callback to clear the field between the constructor and the deserialization | |
d11110 | No need for an if statement; just use grep:
echo $line | grep "\b$word\b"
A: You can use if [[ "$line" == *"$word"* ]]
Also you need to use the following to assign variables
line="1234 abc xyz 5678"
word="1234"
Working example -- http://ideone.com/drLidd
A: Watch the white spaces!
When you set a variable to a value, don't put white spaces around the equal sign. Also use quotes when your value has spaced in it:
line="1234 abc xyz 5678" # Must have quotation marks
word=1234 # Quotation marks are optional
When you use comparisons, you must leave white space around the brackets and the comparison sign:
if [[ $line == *$word* ]]; then
echo $line
fi
Note that double square brackets. If you are doing pattern matching, you must use the double square brackets and not the single square brackets. The double square brackets mean you're doing a pattern match operation when you use == or =. If you use single square brackets:
if [ "$line" = *"$word"* ]
You're doing equality. Note that double square brackets don't need quotation marks while single brackets it is required in most situations.
A: echo $line | grep "$word"
would be the typical way to do this in a script, of course it does cost a new process
A: You can use the bash match operator =~:
[[ "$line" =~ "$word" ]] && echo "$line"
Don't forget quotes, as stated in previous answers (especially the one of @Bill).
A: The reason that if [ "$line"==*"$word"* ] does not work as you expect is perhaps a bit obscure. Assuming that no files exist that cause the glob to expand, then you are merely testing that the string 1234 abc xyz 5678==*1234* is non empty. Clearly, that is not an empty string, so the condition is always true. You need to put whitespace around your == operator, but that will not work because you are now testing if the string 1234 abc xyz 5678 is the same as the string to which the glob *1234* expands, so it will be true only if a file named 1234 abc xyz 5678 exists in the current working directory of the process executing the shell script. There are shell extensions that allow this sort of comparison, but grep works well, or you can use a case statement:
case "$line" in
*$word*) echo $line;;
esac
A: An alternative solution would be using loop:
for w in $line
do
if [ "$w" == "$word" ]; then
echo $line
break
fi
done
A: Code Snippet:
$a='text'
$b='text'
if [ $a -eq $b ]
then
msg='equal'
fi | |
d11111 | So you looked at your process/calcs and it seems correct but you look at your result and it's funny. One thing you notice when you print the counts...
print predatorI, preyI
is that there are fractions of predators and prey which, in the real world, doesn't make sense. You are trying to simulate the real world. All your rate parameters are probably based on whole things, not fractional things. So you decide that there can't be any fractional beings in your simulation and you only deal with whole beings (ints) after the population growth calculations ...
Your function returns the count vectors. If you want to move the plotting statements outside of the function you need to assign the function's return value(s) to a name and then use them for plotting.
prey, predator, = simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predator, 'r', prey, 'b')
plt.show()
Here are some things to read from the docs concerning names, scope, namespaces
https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects
https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
You might need to read them periodically as you use the language more.
A: If I initialize your plot data with the starting populations and use int() truncation for the populations, I get the plot you say you're supposed to see:
import matplotlib.pyplot as plt
def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
preyCounts = [initialPrey]
predatorCounts = [initialPred]
predator = initialPred
prey = initialPrey
while predator > 0 and prey > 0:
predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey
preyScaleFactor = 1.0 + preyGrowth - predationRate * predator
predator = int(predator * predatorScaleFactor)
prey = int(prey * preyScaleFactor)
predatorCounts.append(predator)
preyCounts.append(prey)
plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show()
return preyCounts, predatorCounts
simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002) | |
d11112 | The solution depends on where you are acquiring the event parameters from. Are they coming from text that is being clicked, or are they coming from the page path, etc. One possible solution would require that you push your dynamic category, action, label values with your dataLayer push:
dataLayer.push({
'event': 'event_name',
'category': 'your category',
'action': 'your action',
'label': 'your label'
})
In GTM, you would then need to define new dataLayer variables that would correspond to the category, action, and label. In your event tag, you would then just use the new dataLayer variables. | |
d11113 | I found an alternative solution this may not automatically allow drag objects to snap to every snap zone but it does allow you to control it with less code.
I created a function to get the object(code) and the zone(outline):
function snapTo(code, outlineSnap) {
var outline = outlines[outlineSnap + '_black'];
if(isNearOutline(code, outline)) {
code.position({
x : outline.x,
y : outline.y
});
console.log("privKey:"+ privKey);
console.log("Key:"+ key);
console.log(code.id());
codeLayer.draw();
var testKey = privKey+ "_black";
if(code.id() == outlineSnap) {
setTimeout(function() {
code.draggable(false);
}, 50);
}
}
}
This function has to be in created the for(var key in codes) {} and outside the drag events. I then called the function inside the dragend event.
code.on('dragend', function() {
snapTo(code, "pstart");
snapTo(code, "pend");
}
There's a bit of an issue with adding the score, I have found a solution that just yet other than keeping the if statement to change draggable to false for the right object outline combination, as if this it taken out the user could 'farm' the drag feature for points... | |
d11114 | As per my knowledge if your woocommerce by default currency is dollar then currency always comes in same the currency.Can you please share your site Url then I can check what is the problem? | |
d11115 | I think you would be better off using InvokeRepeating(string methodName, float time, float repeatRate). You only need to call it once and it will repeat.
Example:
void Start()
{
InvokeRepeating("myTask", 1.5f, 1.5f);
}
void myTask()
{
// Execute repetitive task.
}
If you want to stop it at any point you simply have to call: CancelInvoke(string methodName);.
Example:
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
CancelInvoke();
}
This would put an end to the repetitive task. | |
d11116 | Declare currentDate as an @property in your class. And try this.
@property(nonatomic, retain) NSDate *currentDate;
Initially set
self.currentDate = [NSDate date];
before calling this method.
- (void)weekCalculation
{
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:self.currentDate];
[comps setWeekday:1]; // 1: Sunday
firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
[comps setWeekday:7]; // 7: Saturday
lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
NSLog(@" first date of week =%@", firstDateOfTheWeek);
NSLog(@" last date of week =%@", lastDateOfTheWeek);
firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek];
lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek];
}
Once the view is loaded self.currentDate value should be updated from showNextDates. Make sure it is not getting reset anywhere else.
- (IBAction)showNextDates:(id)sender
{
int addDaysCount = 7;
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:addDaysCount];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheWeek options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheWeek options:0];
NSLog(@" new dates =%@ %@", newDate1, newDate2);
self.currentDate = newDate1;
}
A: I had needed similar thing in one of my old projects and achieved it via the code below. It sets this weeks date to an NSDate variable and adds/removes 7 days from day component in each button click. Here is the code:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *date = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date ];
//
[components setDay:([components day] - ([components weekday] )+2)];
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];
The code above calculates this week start and sets it to currentDate variable. I Have two UIButtons with UIActions named prevClick and nextClick which calls the method that sets the next or previous weekstart:
- (IBAction)prevClick:(id)sender {
[self addRemoveWeek:NO];
}
-(void)addRemoveWeek:(BOOL)add{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.currentDate ];
components.day = add?components.day+7:components.day-7;
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];
}
- (IBAction)nextClk:(id)sender {
[self addRemoveWeek: YES];
} | |
d11117 | I recently found a nice way of logging the value of an expression:
trait Logging {
protected val loggerName = getClass.getName
protected lazy val logger = LoggerFactory.getLogger(loggerName)
implicit class RichExpressionForLogging[T](expr: T){
def infoE (msg: T ⇒ String):T = {if (logger.isInfoEnabled ) logger.info (msg(expr)); expr}
def traceE(msg: T ⇒ String):T = {if (logger.isTraceEnabled) logger.trace(msg(expr)); expr}
def debugE(msg: T ⇒ String):T = {if (logger.isDebugEnabled) logger.debug(msg(expr)); expr}
def infoL (msg: String):T = {if (logger.isInfoEnabled ) logger.info (msg+expr); expr}
def traceL(msg: String):T = {if (logger.isTraceEnabled) logger.trace(msg+expr); expr}
def debugL(msg: String):T = {if (logger.isDebugEnabled) logger.debug(msg+expr); expr}
}
}
Here how it is used:
Example 1 (rules):
val x = if(condition1(a.debugL("a="),b.debugL("b=")))
Some(production1(a,b).debugL("rule1="))
else if(condition2(c,d))
Some(production2(a,b).debugL("rule2="))
else
None
Example 2:
def f(list:List[Int]) =
list.
map(_*2).
debugE(s"res1="+_).
flatMap(t => (0 until t).
map(_+1).
debugE(s"res2="+_)).
debugE(s"res="+_)
It can also be used everywhere in expressions:
if((a<0).debugE(s"a=$a<0="+_))
for{
a <- f(list).debugE("f(list)="+_)
b <- a.debugL("a=")
} yield b.debugL("b=")
Of course you should mix-in Logging trait to your class.
This kind of instrumentation doesn't hide the logic of the code. | |
d11118 | You can do this by using the GroundOverlay object of Google Maps JavaScript API. But you need to get the current map object used in your google-maps-react code and you will use this to setMap the overlay into this map ref.
See the sample code and code snippet below:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
const mapStyles = {
width: '100%',
height: '100%',
};
const imageBounds = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655,
};
class MapWithOverlay extends Component {
mapRef = (ref) => {
let historicalOverlay = new google.maps.GroundOverlay(
'https://storage.googleapis.com/geo-devrel-public-buckets/newark_nj_1922-661x516.jpeg',
imageBounds
);
historicalOverlay.setMap(ref.map);
};
render() {
return (
<>
<div>
<Map
ref={(ref) => {
this.mapRef(ref);
}}
google={this.props.google}
zoom={12}
style={mapStyles}
initialCenter={{ lat: 40.74, lng: -74.18 }}
>
<Marker position={{ lat: 40.74, lng: -74.18 }} />
</Map>
</div>
</>
);
}
}
export default GoogleApiWrapper({
apiKey: 'YOUR_KEY',
})(MapWithOverlay); | |
d11119 | It might be worth taking a step back and seeing if what you want to achieve is really valid.
Generally, a serializable class is used for data transport between two layers. It is more likely to be a simple class that only holds data.
It seems a little out of place for it to hold the ability to persist to a database. It is not likely that both ends of the pipe actually have access to the database, and it seems very unlikely that they would both have the ability to persist data.
I wonder if it's worth factoring the save out to a repository. So have a repository class that will accept the data transfer object, construct the database object and save it.
This will simplify your code and completely avoid the problem you're having. It will also greatly enhance testability.
A: The problem is that the db field gets serialized, while clearly it doesn't need to be serialized (it's instantiated once the object is created).
Therefore, you should decorate it with the NonSerialized attribute:
[NonSerialized]
ContactDataContext db = new ContactDataContext();
[Update]
To make sure the db field is accesable after object initialization, you should use a lazy loading property and use this property instead of the field:
[NonSerialized]
ContactDataContext db = null;
[NonSerialized]
private ContactDataContext {
get {
if (db == null) {
db = new ContactDataContext();
}
return db;
}
set {
db = value;
}
}
public void Save()
{
Contact contact = new Contact();
contact.FirstName = FirstName;
contact.LastName = LastName;
Db.Contacts.InsertOnSubmit(contact);
Db.SubmitChanges();
}
[Update2]
You can serialize most objects, as long as it has a public parameterless constructor (or no constructor at all) and no properties/fields that cannot be serialized but require serializing. If the class itself is not marked as [Serializable], then you can do this yourself using a partial class. If the class has properties/fields that cannot be serialized, then you might achieve this by inheriting the class and overriding these properties/fields to decorate them as [NonSerialized].
A: You can create a surrogate that knows how to serialize the dodgy classes - see here for an example
A: I think you do need to decorate the base class, however, the DataContext auto generated classes are marked as partial. Have you tried doing something like:
[Serializable]
public partial class ContactDataContext
{
}
Not sure if it would work but its worth a try. | |
d11120 | On http://www.scala-sbt.org/release/docs/Community/Community-Plugins.html is a list of SBT plugins.
A plugin for your purpose can be https://github.com/steppenwells/sbt-sh . | |
d11121 | I assume you have already checked the log4j2 documentation so you know how to create a basic log4j2.xml file.
I also assume you want to keep some logging but only want to switch off some very verbose logging by org.quartz.scheduler.* loggers.
Then, a basic config with quartz loggers switched to ERROR-only could look like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<File name="MyFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%p %d %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Logger name="org.quartz.scheduler" level="ERROR" additivity="false">
<AppenderRef ref="MyFile"/>
</Logger>
<Root level="trace">
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>
A: <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<File name="MyFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%p %d %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Logger name="org.quartz" level="ERROR" additivity="false">
<AppenderRef ref="MyFile"/>
</Logger>
<Root level="trace">
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration> | |
d11122 | You can try to use @Bucket bigint = NULL for @Bucket default value.
because NULL mean unknow
or you can set a value which should not in bucket column be the default value.
declare @Bucket bigint = NULL
select *
from @t
where (@Bucket is Null or bucket = @Bucket)
NOTE
but If @Bucket bigint is bigint it should not be ''
Edit
CREATE TABLE T(
Bucket bigint
);
declare @Bucket bigint = 0
INSERT INTO T VALUES (1);
INSERT INTO T VALUES (2);
INSERT INTO T VALUES (-1);
INSERT INTO T VALUES (5);
INSERT INTO T VALUES (0);
select * from T
where (@Bucket is Null or (@Bucket ='' and @Bucket <> 0) or bucket=@Bucket)
A: FIXED
declare @t table(bucket bigint);
INSERT INTO @t VALUES (1);
INSERT INTO @t VALUES (2);
INSERT INTO @t VALUES (-1);
INSERT INTO @t VALUES (5);
INSERT INTO @t VALUES (0);
declare @Bucket bigint = 0 --filter by 0
select * from @t
where 1=1
AND (@Bucket is Null or cast(@Bucket as nvarchar) = '' or bucket=@Bucket) | |
d11123 | you can
<button mat-button (click)="clickCard('PC_Job005')">..</button>
clickCard(value:any)
{
console.log(value)
}
//or
<button mat-button value="PC_Job005" (click)="clickCard($event)">..</button>
clickCard(event:any)
{
//see that you need use currentTarget
console.log(event.currentTarget.getAttribute('value'))
} | |
d11124 | You need to add the trailing quote like this (if using the @ syntax you must use "" to match a one quote):
str = Regex.Replace(str, @"xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);
Add a space at the beginning if you want <sender> instead of <sender >:
str = Regex.Replace(str, @" xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);
A: Note that to remove XML namespaces, you can use regular C# code described at How to remove all namespaces from XML with C#?, but since you say that does not help, here is a solution for your special case.
In order to remove any slashes you may use a character class [/\\] - just in case you have both \ and /. Note that a literal backslash must be doubled in a verbatim string literal.
The regex will look like
\s*xmlns=[^<]*?\.be[/\\]"
Here is a regex demo
And in C#:
var rx = new Regex(@"\s*xmlns=[^<]*?\.be[/\\]""");
The \s* will "trim" the whitespace in the resulted replacement.
Results after replacing with string.Empty: | |
d11125 | My issue turned out to be that the DB had been created with a firewall rule for 1 IP named Azure. This was somehow set to the IP address the function app was sometimes using. No idea how this got setup.
The DB firewall rules have a switch to allow Azure resources to connect. No need for v-net and premium plans, unless you want it more secure. | |
d11126 | No, you don't need a conversational Action for what you're doing.
Depending on the specifics of how you're providing the content, you may wish to look at either Podcast Actions or News Actions. These methods document what Google is looking for to make structured content available to the Google Assistant. | |
d11127 | Take a look at the SetTimer function, I think it does exactly what you need.
Before event loop you should call this function with desired interval and you have to pass to it a callback function. Alternatively you can use another function CreateTimerQueueTimer
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) {
}
UINT timer = SetTimer(NULL, 0, 500, &TimerProc);
MSG message;
while(GetMessage(&message, NULL, 0, 0))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
KillTimer(NULL, timerId);
A: Make a new thread to sleep x milis and then send in a while(!interrupted) loop.
As you may know, accessing the same data for read and write from 2 separate threads simultaneously will cause an error.
http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.80).aspx
To avoid that you can use critical section
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx
Or just make your thread to sleep and turn a boolean value to true meaning 'yes we waited enough' and your main function always send data when that boolean is true then set it back to false.
edit:
I believe this is the simplier way to archieve this
while(!interrupted) { // Your thread will do this.
sleep(60000);
maysend = true;
}
[...]
if(maysend) { // Your main function will contain this
send();
maysend = false;
} | |
d11128 | No, you can do that. CodedUi tests are executed through command line through MSTest which does not support it. Check here to see the available command-line options of MSTest.
However, you can create another Project (e.g. console application) to achieve that. The second project has a reference to your CodedUI Project. Then pass the parameters through the .exe file of this Project which calls the appropriate CodedUI Test Method. But I think that this will not work like MSTest does (it will not create Test Results). | |
d11129 | Since you are using Material-UI, you can use their autocomplete component with a TextField as input, have a look at the "Combo box" here:
https://material-ui.com/components/autocomplete/#combo-box | |
d11130 | I found the issue. It turns out that I was setting my flags and service improperly.
First, according to this, INTERNET_OPEN_TYPE_DIRECT and INTERNET_OPEN_TYPE_PRECONFIG conflict with each other. So, I removed INTERNET_OPEN_TYPE_DIRECT to tell Windows that I would like to use the network settings stored in the registry.
Next, I looked at the Windows documentation, here, and found out that, although INTERNET_SERVICE_HTTPS is defined, both HTTP and HTTPS requests are defined by the INTERNET_SERVICE_HTTP service flag.
Finally, I was not including the INTERNET_FLAG_SECURE flag in the right place. I discovered, from this question, that this flag needs to be included on the call to HttpOpenRequestW and including it anywhere else would be redundant.
After making all these changes, my code looks like this:
HttpRequester::HttpRequester(const string verb, const string host, const string resource,
const int port, const bool secure, const string referrer = NULL) {
m_ready = false;
ResetLastError();
// First, report to Windows the user agent that we'll request HTTP data with. If this fails
// then return an error
int flags = INTERNET_OPEN_TYPE_PRECONFIG | INTERNET_FLAG_NO_CACHE_WRITE;
m_open_handle = InternetOpenW(GetUserAgentString(), flags, NULL, NULL, 0);
if (m_open_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_FAILED_ERROR);
return;
}
// Next, attempt to create an intenrnet connection to the URL at the desired port;
// if this fails then return an error
m_session_handle = InternetConnectW(m_open_handle, host, port, "", "", INTERNET_SERVICE_HTTP, flags, 0);
if (m_session_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_CONNECT_FAILED_ERROR);
return;
}
// Now, if we want a secure connection then add the secure flag to the connection
if (secure) {
flags |= INTERNET_FLAG_SECURE;
}
// Finally, open the HTTP request with the session variable, verb and URL; if this fails
// then log and return an error
string accepts[];
m_request_handle = HttpOpenRequestW(m_session_handle, verb, resource, NULL, referrer,
accepts, flags, 0);
if (m_request_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_REQUEST_FAILED_ERROR);
return;
}
m_ready = true;
} | |
d11131 | If you want to declare that ONLY these people form the commitee, you should use Collection, not rdf:Bag. The RDF tutorial at w3schools.com gives an example:
https://www.w3.org/TR/rdf-schema/#ch_collectionvocab
In the RDF schema you need to declate a property "hasMember" or "member". Its domain is a commitee, and its range is a member. Then, the RDF file can describe an unlimited number of members for a given commitee. If in the commitee resource you want to specify that these are the ONLY memebrs, you use a collection. If you allow more members, use a rdf:Bag.
Note: This does not mean it's impossible to define a "bag of members" or "collection of members" as the range of a property. You can take a look at existing simple ontologies on the web (there are hundreds of them written in RDFS) and compare how they define a similar concept. | |
d11132 | You can overcome the problem with checking whether there is anything to stash first. You can use one of the ways to check whether an index is dirty that are suggested in Checking for a dirty index or untracked files with Git
For instance this command will not output anything if there are no changes to stash:
git status --porcelain
Using this command, the script may look like this:
is_stashing=$(git status --porcelain)
test -n "$is_stashing" && git stash save -u
git fetch origin
[apply our workflow/update strategy]
test -n "$is_stashing" && git stash pop --index
A: A solution would be to search the git reflog stash using the name of the stash as a regexp and obtaining its name in the stash@{<number>} format.
Then you can create an alias in git for using it as a command.
A quick and dirty solution, that can be greatly improved, is something like:
[alias]
sshow = "!f() { git stash show `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
ssdrop = "!f() { git stash drop `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
By adding this two aliases in your .git/config you can see the files modified in the stash with:
git sshow <regexp matching the name of the stash>
and you can drop the stash with:
git ssdrop <regexp matching the name of the stash>
A: I found a way to drop a stash by name. You can do it like this:
git stash drop stash@{$((git stash list | grep -w NAME_OF_THE_STASH) | cut -d "{" -f2 | cut -d "}" -f1)}
Here is the breakdown of the script:
*
*I am using the standard git stash drop stash@{n} structure
*We need to get the n of the stash with the name you want to delete. So to do that we list the stashes and grep the item with the matching name. To do that I used the script: git stash list | grep -w NAME_OF_THE_STASH
*Out of that item we need to extract the index which is within brackets {}. We can extract that number by adding to the script in item 2 the following: | cut -d "{" -f2 | cut -d "}" -f1
I tested it and it works great for me.
By the way, if you enter a name that does not exist then nothing gets erased.
Also, only the exact name match will be erased. If you don't want an exact match necessarily then remove the -w after grep. | |
d11133 | if you want to pack the bs into the frame data field, you can -
unpack(packing.low, bs, current_frame.data); | |
d11134 | It gets desugared to this:
println("Unisex names: ".+(boys).intersect(girls))
then according to the -Xprint:typer compiler option it gets rewritten like this:
println(augmentString("Unisex names: ".+(boys.toString)).intersect[Any](girls))
where augmentString is an implicit conversion from type String to StringOps, which provides the intersect method. | |
d11135 | not provided by Solr itself.
But nothing prevents you from doing this:
*
*set your DIH sql for the delta like this:
WHERE (last_pk_id > '${dataimporter.request.LAST_PK_ID}')
*when you run some indexing, store, outside Solr, the last_pk_id value you indexed, say 333.
*next time you need to delta index, add to your request
...&clean=false&LAST_PK_ID=333
*store your new LAST_PK_ID (you can query solr for this) | |
d11136 | Short Answer
using System;
using System.Text.RegularExpressions;
Console.WriteLine(Regex.IsMatch("1313123", @"^\d+$")); // true
That assumes we want to validate a simple integer.
Conversation
If we also want to include thousands grouping structures for one or more cultures or other numeric conventions, that will be more complicated. Consider these cases:
*
*10,000
*10 000
*100,00
*100,000
*-10
*+10
For a sense of the challenge, see the NumberFormatInfo properties here.
If we need to handle culture specific numeric conventions, it's probably best to leverage the Int64.TryParse() method instead of using Regex.
Sample Code
It's live here. The complete list of NumberStyles is here. We can add/remove the various NumberStyles until we find the set that we want.
using System;
using System.Text.RegularExpressions;
using System.Globalization;
public class Program
{
public static void Main()
{
Console.WriteLine(IsIntegerRegex("")); // false
Console.WriteLine(IsIntegerRegex("2342342")); // true
Console.WriteLine(IsInteger("1231231.12")); // false
Console.WriteLine(IsInteger("1231231")); // true
Console.WriteLine(IsInteger("1,231,231")); // true
}
private static bool IsIntegerRegex(string value)
{
const string regex = @"^\d+$";
return Regex.IsMatch(value, regex);
}
private static bool IsInteger(string value)
{
var culture = CultureInfo.CurrentCulture;
const NumberStyles style =
// NumberStyles.AllowDecimalPoint |
// NumberStyles.AllowTrailingWhite |
// NumberStyles.AllowLeadingWhite |
// NumberStyles.AllowLeadingSign |
NumberStyles.AllowThousands;
return Int64.TryParse(value, style, culture, out _);
}
} | |
d11137 | The place where I think you've mistaken is where you're writing code for update
The way I do it is
def update(self):
# Update sprite position
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# moving left
if self.movex < 0:
self.frame += 1
if self.frame > 3 * ani:
self.frame = 0
self.image = self.images[self.frame//ani]
# moving right
elif self.movex > 0:
self.frame += 1
if self.frame > 3 * ani:
self.frame = 0
self.image = self.images[(self.frame//ani)+4]
self.rect.topleft = self.rect.x, self.rect.y | |
d11138 | That constructor will be called on the server when you make your request from the client.
Creating a "reference" to a web service (and then using the client classes) is very different to referencing a regular .DLL. All of your service code will run on the server-side, but not until the service is invoked...
A: The only way for the server-side constructor to be called for each request is to set the InstanceContextMode to PerCall (in the ServiceBehavior attribute). | |
d11139 | The immediate problem, causing the fan shape you observe, is caused by startx and starty remaining the same for each object entry in canvas_data.pencil array. This is because, startx and starty are assigned the values held in prevX and prevY, but these were set in the mousedown event listener and are not updated in the mousemove event listener.
This is fixed as follows:
Firstly, although not strictly necessary for funtion, remove the references to prevX and prevY from the mousedown event listener in the pencil function and set ctx.moveTo(curX, curY) - this is a little less confusing because the mousedown is where the draw begins from:
// inside pencil function;
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
ctx.beginPath();
ctx.moveTo(curX, curY); // prev -> cur;
};
Next, in the mousemove listener, add lines to update prevX and prevY:
// inside pencil function;
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
prevX = curX; // new
prevY = curY; // new
}
};
These changes form the correct data object array with each object's startx and starty value now being set to the previous object's endx and endy value, as required.
However, there's another immediate problem: the undo_pixel function only fully executes on the first click to remove the last object of the pencil array (causing the last sliver of line captured by the last mousemove event to disappear as intended), but subsequent clicks (to remove successive parts of the line) are aborted.
I'm assuming the undo_pixel function is intended to remove a sliver for each click rather than the entire pencil line (see later if not).
The reason for the process to be aborted is because of resetting the canvas_data.last_action flag inside undo_pixel:
canvas_data.last_action = -1`
Because there is no case block in the switch statement for -1, nothing happens on subsequent clicks of the undo button;
Instead, the case block for the pencil should be:
case 4:
canvas_data.pencil.pop();
canvas_data.last_action = 4; // not -1;
break;
You have to leave it at 4 until another action is selected to undo or until the whole pencil line is removed and then move to the object drawn immediately before the lencil line (for which you will need to keep track of the order in which items were drawn).
I've made a working snippet with the above suggestions. You'll need to display it full page as the preview window is too small to see the line while you click the undo button. If you draw a short pencil sqiggle and repeatedly press the undo button, you'll see the line being 'undrawn'.
(I had to delete some of your other functions as I exceeded the allowed character limit for an answer)
var canvas = document.getElementById("paint");
var ctx = canvas.getContext("2d");
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var width = canvas.width;
var height = canvas.height;
var curX, curY, prevX, prevY;
var hold = false;
ctx.lineWidth = 2;
var fill_value = true;
var stroke_value = false;
var canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
// //connect to postgres client
// var pg = require('pg');
// var conString = "postgres://postgres:database1@localhost:5432/sketch2photo";
// client = new pg.Client(conString);
function color(color_value) {
ctx.strokeStyle = color_value;
ctx.fillStyle = color_value;
}
function add_pixel() {
ctx.lineWidth += 1;
}
function reduce_pixel() {
if (ctx.lineWidth == 1) {
ctx.lineWidth = 1;
} else {
ctx.lineWidth -= 1;
}
}
function fill() {
fill_value = true;
stroke_value = false;
}
function outline() {
fill_value = false;
stroke_value = true;
}
function reset() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas_data = {
"pencil": [],
"line": [],
"rectangle": [],
"circle": [],
"eraser": [],
"last_action": -1
};
}
// pencil tool
function pencil(data, targetX, targetY, targetWidth, targetHeight) {
//prevX = 0; // new
//prevY = 0; // new
canvas.onmousedown = function(e) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
hold = true;
ctx.beginPath();
ctx.moveTo(curX, curY); // prev -> cur;
};
canvas.onmousemove = function(e) {
if (hold) {
curX = e.clientX - canvas.offsetLeft;
curY = e.clientY - canvas.offsetTop;
draw();
prevX = curX; // new
prevY = curY; // new
}
};
canvas.onmouseup = function(e) {
hold = false;
};
canvas.onmouseout = function(e) {
hold = false;
};
function draw() {
ctx.lineTo(curX, curY);
ctx.stroke();
canvas_data.pencil.push({
"startx": prevX,
"starty": prevY,
"endx": curX,
"endy": curY,
"thick": ctx.lineWidth,
"color": ctx.strokeStyle
});
canvas_data.last_action = 0;
}
}
function undo_pixel() {
switch (canvas_data.last_action) {
case 0:
case 4:
canvas_data.pencil.pop();
canvas_data.last_action = 4; // not -1;
break;
case 1:
//Undo the last line drawn
console.log("Case 1");
canvas_data.line.pop();
canvas_data.last_action = -1;
break;
case 2:
//Undo the last rectangle drawn
console.log("Case 2");
canvas_data.rectangle.pop();
canvas_data.last_action = -1;
break;
case 3:
//Undo the last circle drawn
console.log("Case 3");
canvas_data.circle.pop();
canvas_data.last_action = -1;
break;
default:
break;
}
redraw_canvas();
}
function redraw_canvas() {
// Redraw all the shapes on the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw the pencil data
canvas_data.pencil.forEach(function(p) {
ctx.beginPath();
ctx.moveTo(p.startx, p.starty);
ctx.lineTo(p.endx, p.endy);
ctx.lineWidth = p.thick;
ctx.strokeStyle = p.color;
ctx.stroke();
});
// Redraw the line data
canvas_data.line.forEach(function(l) {
ctx.beginPath();
ctx.moveTo(l.startx, l.starty);
ctx.lineTo(l.endx, l.endy);
ctx.lineWidth = l.thick;
ctx.strokeStyle = l.color;
ctx.stroke();
});
}
<html>
<head>
<title>Paint App</title>
<script src="main.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<body>
<p style="text-align:left; font: bold 35px/35px Georgia, serif;">
PaintApp
</body>
</body>
<div align="right">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<body onload="pencil(`{{ data }}`, `{{ targetx }}`, `{{ targety }}`, `{{ sizex }}`, `{{ sizey }}`)">
<p>
<table>
<tr>
<td>
<fieldset id="toolset" style="margin-top: 3%;">
<br>
<br>
<button id="penciltool" type="button" style="height: 15px; width: 100px;" onclick="pencil()">Pencil</button>
<br>
<br>
<br>
<button id="linetool" type="button" style="height: 15px; width: 100px;" onclick="line()">Line</button>
<br>
<br>
<br>
<button id="rectangletool" type="button" style="height: 15px; width: 100px;" onclick="rectangle()">Rectangle</button>
<br>
<br>
<br>
<button id="circletool" type="button" style="height: 15px; width: 100px;" onclick="circle()">Circle</button>
<br>
<br>
<br>
<button id="erasertool" type="button" style="height: 15px; width: 100px;" onclick="eraser()">Eraser</button>
<br>
<br>
<br>
<button id="resettool" type="button" style="height: 15px; width: 100px;" onclick="reset()">Reset</button>
</fieldset>
</td>
<td>
<canvas id="paint" width="500vw" height="350vw" style="border: 5px solid #000000; margin-top: 3%;"></canvas>
</td>
</tr>
</table>
</p>
<fieldset id="colorset" style="margin-top: 1.8%;">
<table>
<tr>
<td><button style="height: 15px; width: 80px;" onclick="fill()">Fill</button>
<td><button style="background-color: #000000; height: 15px; width: 15px;" onclick="color('#000000')"></button>
<td><button style="background-color: #B0171F; height: 15px; width: 15px;" onclick="color('#B0171F')"></button>
<td><button style="background-color: #DA70D6; height: 15px; width: 15px;" onclick="color('#DA70D6')"></button>
<td><button style="background-color: #8A2BE2; height: 15px; width: 15px;" onclick="color('#8A2BE2')"></button>
<td><button style="background-color: #0000FF; height: 15px; width: 15px;" onclick="color('#0000FF')"></button>
<td><button style="background-color: #4876FF; height: 15px; width: 15px;" onclick="color('#4876FF')"></button>
<td><button style="background-color: #CAE1FF; height: 15px; width: 15px;" onclick="color('#CAE1FF')"></button>
<td><button style="background-color: #6E7B8B; height: 15px; width: 15px;" onclick="color('#6E7B8B')"></button>
<td><button style="background-color: #00C78C; height: 15px; width: 15px;" onclick="color('#00C78C')"></button>
<td><button style="background-color: #00FA9A; height: 15px; width: 15px;" onclick="color('#00FA9A')"></button>
<td><button style="background-color: #00FF7F; height: 15px; width: 15px;" onclick="color('#00FF7F')"></button>
<td><button style="background-color: #00C957; height: 15px; width: 15px;" onclick="color('#00C957')"></button>
<td><button style="background-color: #FFFF00; height: 15px; width: 15px;" onclick="color('#FFFF00')"></button>
<td><button style="background-color: #CDCD00; height: 15px; width: 15px;" onclick="color('#CDCD00')"></button>
<td><button style="background-color: #FFF68F; height: 15px; width: 15px;" onclick="color('#FFF68F')"></button>
<td><button style="background-color: #FFFACD; height: 15px; width: 15px;" onclick="color('#FFFACD')"></button>
<td><button style="background-color: #FFEC8B; height: 15px; width: 15px;" onclick="color('#FFEC8B')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #F5DEB3; height: 15px; width: 15px;" onclick="color('#F5DEB3')"></button>
<td><button style="background-color: #FFE4B5; height: 15px; width: 15px;" onclick="color('#FFE4B5')"></button>
<td><button style="background-color: #EECFA1; height: 15px; width: 15px;" onclick="color('#EECFA1')"></button>
<td><button style="background-color: #FF9912; height: 15px; width: 15px;" onclick="color('#FF9912')"></button>
<td><button style="background-color: #8E388E; height: 15px; width: 15px;" onclick="color('#8E388E')"></button>
<td><button style="background-color: #7171C6; height: 15px; width: 15px;" onclick="color('#7171C6')"></button>
<td><button style="background-color: #7D9EC0; height: 15px; width: 15px;" onclick="color('#7D9EC0')"></button>
<td><button style="background-color: #388E8E; height: 15px; width: 15px;" onclick="color('#388E8E')"></button>
</tr>
<tr>
<td><button style="height: 15px; width: 80px" onclick="outline()">Outline</button>
<td><button style="background-color: #71C671; height: 15px; width: 15px;" onclick="color('#71C671')"></button>
<td><button style="background-color: #8E8E38; height: 15px; width: 15px;" onclick="color('#8E8E38')"></button>
<td><button style="background-color: #C5C1AA; height: 15px; width: 15px;" onclick="color('#C5C1AA')"></button>
<td><button style="background-color: #C67171; height: 15px; width: 15px;" onclick="color('#C67171')"></button>
<td><button style="background-color: #555555; height: 15px; width: 15px;" onclick="color('#555555')"></button>
<td><button style="background-color: #848484; height: 15px; width: 15px;" onclick="color('#848484')"></button>
<td><button style="background-color: #F4F4F4; height: 15px; width: 15px;" onclick="color('#F4F4F4')"></button>
<td><button style="background-color: #EE0000; height: 15px; width: 15px;" onclick="color('#EE0000')"></button>
<td><button style="background-color: #FF4040; height: 15px; width: 15px;" onclick="color('#FF4040')"></button>
<td><button style="background-color: #EE6363; height: 15px; width: 15px;" onclick="color('#EE6363')"></button>
<td><button style="background-color: #FFC1C1; height: 15px; width: 15px;" onclick="color('#FFC1C1')"></button>
<td><button style="background-color: #FF7256; height: 15px; width: 15px;" onclick="color('#FF7256')"></button>
<td><button style="background-color: #FF4500; height: 15px; width: 15px;" onclick="color('#FF4500')"></button>
<td><button style="background-color: #F4A460; height: 15px; width: 15px;" onclick="color('#F4A460')"></button>
<td><button style="background-color: #FF8000; height: 15px; width: 15px;" onclick="color('FF8000')"></button>
<td><button style="background-color: #FFD700; height: 15px; width: 15px;" onclick="color('#FFD700')"></button>
<td><button style="background-color: #8B864E; height: 15px; width: 15px;" onclick="color('#8B864E')"></button>
<td><button style="background-color: #9ACD32; height: 15px; width: 15px;" onclick="color('#9ACD32')"></button>
<td><button style="background-color: #66CD00; height: 15px; width: 15px;" onclick="color('#66CD00')"></button>
<td><button style="background-color: #BDFCC9; height: 15px; width: 15px;" onclick="color('#BDFCC9')"></button>
<td><button style="background-color: #76EEC6; height: 15px; width: 15px;" onclick="color('#76EEC6')"></button>
<td><button style="background-color: #40E0D0; height: 15px; width: 15px;" onclick="color('#40E0D0')"></button>
<td><button style="background-color: #9B30FF; height: 15px; width: 15px;" onclick="color('#9B30FF')"></button>
<td><button style="background-color: #EE82EE; height: 15px; width: 15px;" onclick="color('#EE82EE')"></button>
<td><button style="background-color: #FFC0CB; height: 15px; width: 15px;" onclick="color('#FFC0CB')"></button>
<td><button style="background-color: #7CFC00; height: 15px; width: 15px;" onclick="color('#7CFC00')"></button>
</tr>
<tr>
<td><label>Line Width</label></td>
<td><button id="pixel_plus" type="button" onclick="add_pixel()" style="width: 25px;">+</button></td>
<td><button id="pixel_minus" type="button" onclick="reduce_pixel()" style="width: 25px;">-</button></td>
<td><button id="undo" type="button" onclick="undo_pixel()" style="width: 75px;">Undo</button></td>
</tr>
</table>
<br>
</fieldset>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src=" {{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
Note about intended undo function
If I have misunderstood and the undo action is supposed to remove the entire last pencil shape for a single click, you have to change the way the pencil object array is structured.
At present, the array is structured like this:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
]
this means that removing the last object (which your .pop in case 4 does) removes only the sliver of the pencil line captured during the last mousemove event. This is ok if you want to fine tune a line (I think that's a good feature, and assuemed it you wanted it that way) but causes a problem if more than one separate pencil line is drawn. If there are two pencil lines, they are merged into one inside the pencil data array.
To deal with this you would have to re-structure the pencil array to hold descrete inner arrays for each line like this:
[
// first line array:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
],
// more line arrays;
// last line array:
[
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
},
// more data objects for each mousemove captured;
{
"startx": 148,
"starty": 281,
"endx": 148,
"endy": 280,
"thick": 2,
"color": "#000000"
}
]
] // end of pencil array;
Under this structure, .pop will remove a whole line (which may be what you intended). It will also solve a bug where currently a redraw will join any separate lines into one line. | |
d11140 | The expression x % a is only valid for integral types x and a. Since x is a float type, compilation fails.
If you want the floating point modulus for a float type, then use
std::fmodf
instead. (Note that a will be implicitly converted to a float.)
Reference: https://en.cppreference.com/w/cpp/numeric/math/fmod | |
d11141 | Postgres version does not matter here. The tables are not identical. Most likely in your 9.4.5 table the column id is a primary key, while in 9.4.4 is not. | |
d11142 | The code is valid, assuming that the variable $imgD is defined (var_dump is one way of checking this, but print or echo may also work).
Check to ensure that cookies are enable in your browser.
Also, be sure that session_start() comes near the top of your script, it should be the first thing sent to the client each time.
To test a session, create "index.php" with the following code:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = " . $_SESSION['views'];
?>
Reload the page several times and you should see an incrementing number.
An example of passing session variables between two pages is as follows:
PageOne.php
<?php
session_start();
// makes an array
$colors=array('red', 'yellow', 'blue');
// adds it to our session
$_SESSION['color']=$colors;
$_SESSION['size']='small';
$_SESSION['shape']='round';
print "Done";
?>
PageTwo.php
<?php
session_start();
print_r ($_SESSION);
echo "<p>";
//echo a single entry from the array
echo $_SESSION['color'][2];
?>
For simplicity put PageOne.php and PageTwo.php in the same directory. Call PageOne.php and then PageTwo.php.
Try also tutorials here, here, and here.
A: If you call session_start(), the server gets the session ID from cookies.
Maybe something is wrong with the cookies because the code is valid. | |
d11143 | It's not quite clear where in the app hierarchy that component is so I've attempted a bit of guess work. You're almost there by the looks of things. You just need to iterate over the buttons and create them.
function Button(props) {
const { disabled, text } = props;
return <button disabled={disabled}>{text}</button>;
}
// Buttons creates the buttons in the set
function Buttons() {
const setOne = [2, 6, 8];
const setTwo = [3, 8, 4];
// Remove the duplicates from the combined sets
const combined = [...new Set([...setOne, ...setTwo])];
// Get your duplicate values
const hasDuplicateValues = setOne.filter(item => setTwo.includes(item));
// `map` over the combined buttons
// If `hasDuplicateValues` includes the current button, disable it
return combined.map((n) => (
<Button
text={n}
disabled={hasDuplicateValues.includes(n) && 'disabled'}
/>
));
}
ReactDOM.render(<Buttons />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/> | |
d11144 | you can try this
select distinct on (eccev.extra_data , c.id) eccev.extra_data , c.id, case when ...
but your query seems not optimized as you cross join 6 tables all together ... | |
d11145 | You could have something like:
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {
@RequestMapping(value = "{messageId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Message> getMessage(@PathVariable("messageId") Long messageId) {
...
}
}
@RestController
@RequestMapping("/api/v1/messages/{messageId}/comments")
public class CommentController {
@RequestMapping(value = "{commentId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId,
@PathVariable("commentId") Long commentId) {
...
}
} | |
d11146 | It doesn't work that way because you cannot transmit the file via a URL and Pages cannot access a file that is stored in your app's sandbox.
If you want to give the user the option to open a file in Pages in your UI, UIDocumentInteractionController is the way to do that. It presents a UI where the user can preview the file and select to open it in any application that supports the file type.
AFAIK it is not possible with the SDK to do this completely programmatically, i.e. without user interaction. | |
d11147 | In your imports you are mixing imports between the keras and tf.keras packages, that is actually not supported, you should choose one and make all imports from the selected package. | |
d11148 | Like @daliusd mentioned in his answer, the accepted answer here should be:
npm i @types/multer --save-dev
req.files is now typed and recognized by the Typescript compiler.
A: Probably we can just extend Request
interface MulterRequest extends Request {
file: any;
}
public document = async (req: Request, res: Response): Promise<any> => {
const documentFile = (req as MulterRequest).file;
}
or may be like this code
interface MulterRequest extends Request {
file: any;
}
public document = async (req: MulterRequest , res: Response): Promise<any> => {
const documentFile = req.file;
}
A: Or install @types/multer with
npm i @types/multer --save-dev
and check out this https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18569
A: if using typescript with express-fileupload you can install @types/express-fileupload as dev dependencie and it will be solved | |
d11149 | *
*Click on the link, show "Loading.."
*Load CSS file by ajax, in callback function, create <style> tag, and then insert CSS code to <style> tag, and then start load content by ajax.
*you can optimize the flow by load CSS and content individually, but content only take place in a hidden container, once CSS file finish load, then change hidden container to be shown.
Hope it helps. | |
d11150 | This is how I'd do it in haml:
.col-xs-2
.text-center
= product.input :auth_quantity, type: "number", max: "<%= producto.req_quantity %>" label: false, required: "required"
Where producto.req_quantity is the numerical value of the quantity of a certain product a client requested.
A: So I basically solved it like this. Thanks for the answer, made me think a lot!!
.col-xs-2
.text-center
= producto.input :auth_quantity, input_html: { min: '0', max: product.object.req_quantity, step: 'any' }, label: false, required: "required" | |
d11151 | I would create a class that will hold gather all "store entities" and their sales, i think that using a collection of this class (StoreEntity in my example) it will be much easier to perform a variety of data manipulation (for this task and in future tasks).
here is my suggestion:
public class StoreEntity
{
Person PersonEntity { get; set; }
Customer CustomerEntity { get; set; }
List<Sale> SalesList { get; set; }
public StoreEntity(Person p, Customer c,List<Sale> sales)
{
this.PersonEntity = p;
this.CustomerEntity = c;
this.SalesList = sales;
}
public int SalesCount
{
get
{
if (SalesList == null)
{
return 0;
}
else
{
return SalesList.Count;
}
}
}
}
public List<StoreEntity> Entities { get; set; }
public void MostOrders()
{
List<Person> per = Data.GetAllPersons();
List<Sale> sale = Data.GetAllSales();
List<Customer> cus = Data.GetAllCustomers();
Entities = new List<StoreEntity>();
foreach (Person p in per)
{
var cust = cus.Where(x => x.PersonID == p.PersonID).Select(x => x).SingleOrDefault();
if (cust != null)
{
var sales = sale.Where(x => x.CustomerId == cust.CustomerID).ToList();
StoreEntity entity = new StoreEntity(p, cust, sales);
Entities.Add(entity);
}
}
// now you have list of all entities with their sales
// it will be musch easy to manipulate with linq
// you can do this:
Entities = Entities.OrderBy(x => x.SalesCount).ToList();
// or this...
var bestEntity = Entities.Max(x => x.SalesCount);
} | |
d11152 | The misconception:
To quote the docs:
Widgets should not be confused with the form fields. Form fields deal with the logic of input validation and are used directly in templates. Widgets deal with rendering of HTML form input elements on the web page and extraction of raw submitted data.
Widgets have no influence on validation. You gave your widgets a format argument, but that does not mean the form field validation will use it - it only sets the initial format the widget's content is rendered with:
format: The format in which this field’s initial value will be displayed.
The solutions
Two options:
*
*provide the form field (forms.DateTimeField) with the datetime format you would like to use by passing a input_formats argument
class MyIdealDateForm(forms.ModelForm):
start = forms.DateTimeField(
input_formats = ['%Y-%m-%dT%H:%M'],
widget = forms.DateTimeInput(
attrs={
'type': 'datetime-local',
'class': 'form-control'},
format='%Y-%m-%dT%H:%M')
)
This needs to be done for every form field (and probably by extension even their widgets). What you are doing here is effectively overwriting the settings (see the next point).
*Add your datetime format to the settings as the first item. This will apply globally to all formfields and widgets that use that setting.
A: you just have a typo. Make it 'form' instead of 'fom' in class value.
'calendar': forms.Select(attrs={
'class': 'fom-control chosen-select'
}),
A: Maybe you need to import datetime to ensure it's a valid date/time format for python, here you can see an aproach. | |
d11153 | You can define to_param on your model. It's return value is going to be used in generated URLs as the id.
class Thing
def to_param
name
end
end
The you can adapt your routes to scope your resource like so
scope "/something" do
resources :things
end
Alternatively, you could also use sub-resources is applicable.
Finally you need to adapt your controller as Thing.find(params[:id]) will not work obviously.
class ThingsController < ApplicationController
def show
@thing = Thing.where(:name => params[:id).first
end
end
You probably want to make sure that the name of your Thing is unique as you will observe strange things if it is not.
To save the hassle from implementing all of this yourself, you might also be interested in friendly_id which gives you this and some additional behavior (e.g. for using generated slugs)
A: You need the scope in routes.rb
scope "/something" do
resources :models
end | |
d11154 | I am attempting to use pthreads with Apache FPM.
You can't. Find a way to work without them.
The pthreads extension cannot be used in a web server environment. Threading in PHP is therefore restricted to CLI-based applications only.
-- http://php.net/manual/en/intro.pthreads.php | |
d11155 | It does not work because you have paused the CCDirector. Remove the following line:
[[CCDirector sharedDirector] pause];
Alternatively if you really need that, resume the director before you attempt to replace the scene.
[[CCDirector sharedDirector] resume];
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t]; | |
d11156 | You can generate a ClickOnce certificate with any expiration date (and any Issued To/Issued By values):
makecert -sv ClickOnceTestApp.pvk
-n CN=Sample ClickOnceTestApp.cer
-b 01/01/2012 -e 12/31/2100 -r
It will be a self-signed certificate, same as generated by Visual Studio for click once deployments.
from http://bernhardelbl.wordpress.com/2012/03/20/create-a-non-expiring-test-certificate-pfx-for-clickonce-applications/ | |
d11157 | After
pm <- ggpairs(tips, 1:3, columnLabels = c("Total Bill", "Tip", "Sex"))
do this
levels(pm$data$sex)[levels(pm$data$sex) == "Male"] = "M"
levels(pm$data$sex)[levels(pm$data$sex) == "Female"] = "F"
You'll get this plot:
It won't change anything in tips dataset:
head(tips)
total_bill tip sex smoker day time size
1 16.99 1.01 Female No Sun Dinner 2
2 10.34 1.66 Male No Sun Dinner 3
3 21.01 3.50 Male No Sun Dinner 3
4 23.68 3.31 Male No Sun Dinner 2
5 24.59 3.61 Female No Sun Dinner 4
6 25.29 4.71 Male No Sun Dinner 4 | |
d11158 | The size of the map value &S, a pointer, is the same irrespective of the capacity of slice b.
package main
import (
"fmt"
"unsafe"
)
type S struct {
a uint32
b []uint32
}
func main() {
size := unsafe.Sizeof(&S{})
fmt.Println(size)
size = unsafe.Sizeof(&S{b: make([]uint32, 10)})
fmt.Println(size)
s := make(map[uint32]*S)
for k, v := range s {
delete(s, k)
s[k] = &S{a: v.a}
}
}
Output:
8
8
A slice is represented internally by
type slice struct {
array unsafe.Pointer
len int
cap int
}
When you set &S{a: v.a} you set b to initial values: array to nil and len and cap to zero. The memory formerly occupied by the underlying array is returned to the garbage collector for reuse.
A: The map size is bounded to the maximum size it had at any point. Because you store pointers (map[uint32]*S) and not values the deleted objects will get garbage collected eventually but usually not immediately and that why you don’t see it in top/htop like monitors.
The runtime is clever enough and reserves memory for future use if the system is not under pressure or low on resources.
See https://stackoverflow.com/a/49963553/1199408 to understand more about memory.
In your example you don't need to call delete. You will achieve what you want just by clearing the slice in the struct.
type S struct {
a uint32
b []uint32
}
s := make(map[uint32]*S)
for k, v := range s {
v.b = []uint32{}
} | |
d11159 | The problem is that you created a placeholder in add_final_training_ops that you don't feed. You might think that the placeholder ground_truth_tensor that you create in add_final_training_ops is the same, but it is not, it is a new one, even if it is initialized by the former.
The easiest fix would be perhaps to return the placeholder from add_final_training_ops and use this one instead. | |
d11160 | Maybe you can do this:
public function store(Request $request)
{
//Approved Request
$approvedRequest= DB::table('request')
->where('users_MemId',Auth::user()->MemId)
->where('requestStatus','Approved')
->join('requestdetails','request.requestId','=','requestdetails.request_requestId')
->join('itemattribute','requestdetails.RequestDetailsId','=','itemattribute.RequestDetailsId')
->join('exudeinventory', 'itemattribute.AttrName', '=', 'exudeinventory.ItemName')
->select('itemattribute.AttrName', 'exudeinventory.InventoryId', 'request.requestId')
->get()
->each (function ($request, $key) {
$dis = new Disbursment;
$dis->DisbursmentId = rand(1, 999999);
$dis->ItemImage = 'default.jpg';
$dis->ItemTypeId = $request->AttrName;
$dis->exudeinventory_InventoryId = $request->InventoryId;
$dis->request_requestId = $request->requestId;
$dis->save();
});
} | |
d11161 | I had the same problem until I specified the key and cert in my .bash_profile file:
export EC2_HOME=~/.ec2
export PATH=$PATH:$EC2_HOME/bin
export EC2_PRIVATE_KEY='ls $EC2_HOME/key.pem'
export EC2_CERT='ls $EC2_HOME/cert.pem' | |
d11162 | It's really a shared value, so every time a constructor runs, the value is incremented by 1 regardless of when the variable is accessed thereafter. You could verify this yourself:
private static void showObjectCounter()
{
Counter val1 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val2 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val3 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val4 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
}
You'll see that value changes every time.
A: You might be helped by using some conventional naming and coding style.
*
*Use this for instance variables
*Use C# Property instead of getter/setter method
*Don't use this for static variables
*Slightly more descriptive naming
Sample:
public class Counter
{
public int Count { get; }
private static int instanceCounter = 0;
public static int InstanceCount
{
get
{
return instanceCounter;
}
}
public Counter()
{
this.Count = instanceCounter;
instanceCounter++;
}
}
A: In your example, there is only one physical location in memory that corresponds to the ValueCounter variable.
By contrast, the non-static value field is stored in each instance's object data. | |
d11163 | You can use a delegate:
from PyQt5 import QtCore, QtGui, QtWidgets
class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
option.palette.setBrush(QtGui.QPalette.Button, QtGui.QColor("red"))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.watchListslistWidget = QtWidgets.QListWidget()
self.setCentralWidget(self.watchListslistWidget)
watch_list = ["Protesters", "Local news staff", "Techfluencers"]
for category in watch_list:
checkBox = QtWidgets.QListWidgetItem(category)
checkBox.setFlags(checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
checkBox.setCheckState(QtCore.Qt.Unchecked)
self.watchListslistWidget.addItem(checkBox)
delegate = CheckBoxDelegate(self.watchListslistWidget)
self.watchListslistWidget.setItemDelegate(delegate)
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
A: I got it working by using indicator as follows:
self.watchListslistWidget.setStyleSheet("""
QListWidget::indicator{
border: 1px solid white;
}
""") | |
d11164 | GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented.
I have however used the modules XPATH and DOM with great success.
Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:
*
*dom-parser.js
*dom.js
*sax.js
*xpath.js
To use it in DataPower GWS you first need to get the XML data from INPUT:
// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {
if (readAsBuffersError) {
console.error('Error on readAsBuffers: ' + readAsBuffersError);
session.reject('Error on readAsBuffers: ' + readAsBuffersError);
} else {
if (data.slice(0,5).toString() === '<?xml') {
console.log('It is XML!');
parseXML(data);
}
} //end read as buffers error
}); //end read as buffer function
function parseXML(xml) {
// Load XML Dom and XPath modules
var select = require('local:///xpath.js');
var dom = require('local:///dom-parser.js');
var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
// Get attribute
var nodes = select(doc, "//root/element1/@protocol");
try {
var val = nodes[0].value.toString();
console.log('found xml attribute as ['+val+']');
} catch(e) {
// throw error here
}
// Get an element
nodes = select(doc, "//root/element1/child1");
try {
var val = nodes[0].firstChild.data;
console.log('elemnt found as ['+val+']');
} catch(e) {
//throw error here
}
}
That should be a working sample... You need to change the path for the modules if you move them.
I have a directory in store:/// where I add my GWS modules.
Hope you'll get it to fly!
A: At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:
//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
if (error) {
//error behaviour
} else {
var domTree;
try {
domTree = XML.parse(nodeList);
} catch (error) {
//error behaviour
}
var transform = require('transform'); //native gatewayscript module
transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
if(error){
//error behaviour
}
//some use of result, for example putting it to output
session.output.write(result);
}
});
}); | |
d11165 | The height increases because you set the height in the first run. After that the height remains the "max hight" + 25 and adds additional 25 to it.
To prevent that just reset the height of the element to auto.
function listHeight() {
$("ul.container").each(function () {
var listHeight = 0;
var newHeight = 0;
$("li", this).each(function () {
var el = $(this);
el.css('height', 'auto');
newHeight = el.height();
if (newHeight > listHeight) {
listHeight = newHeight;
}
});
$("li", this).height(listHeight += 25);
});
}
listHeight();
$(window).resize(function () {
listHeight();
});
For better performance I suggest that you debounce/throttle the function call.
A: you need to add
$("li", this).height("auto");
after
var listHeight = 0;
var newHeight = 0;
view Demo
A: I think you need to look at this thread.
jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?
You need to call it at the end of the resize event.
Hope it helps!
A: You need to increment height only if newHeight > listHeight, I think. | |
d11166 | try to add some constraints in the layout of edittext instead defining
style
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:maxHeight="40dp"
android:scrollbars="vertical"
android:scrollbarStyle="outsideOverlay" >
try this it may help u | |
d11167 | Instead of creating a gradient in drawRect:, have you considered using CAGradientLayer as the layer class of your custom view, e.g.:
+ (Class)layerClass
{
return [CAGradientLayer class];
}
Then you can perform any setup of your gradient in your initializer, via self.layer. | |
d11168 | The accepted answer is most likely written towards an older version of the SDK I just couldn't get it to work. This is what works for me as of now.
As an example, the following allow us to access files in Google Drive which is part of googleapis.
Dependencies
pubspec.yaml:
dependencies:
google_sign_in: any
googleapis: any
(I just put any here as a example, but you should specific the version(s) for you actual app.)
How it works
Necessary imports:
import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart' as signIn;
Step 1, sign in the user and ask for access permission (scope) to google drive:
final googleSignIn = signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.DriveScope]);
final sign.GoogleSignInAccount account = await googleSignIn.signIn();
Step 2, build a AuthenticateClient:
class AuthenticateClient extends http.BaseClient {
final Map<String, String> headers;
final http.Client client;
AuthenticateClient(this.headers, this.client);
Future<http.StreamedResponse> send(http.BaseRequest request) {
return client.send(request..headers.addAll(headers));
}
}
As suggested in http, this is using the BaseClient with extra authentication headers (being composable).
Step 3, create a authenticated http client with from step 1 and 2 and access google drive API.
final baseClient = new Client();
final authenticateClient = AuthenticateClient(authHeader, baseClient);
final driveApi = drive.DriveApi(authenticateClient);
Checkout How to Use the Google Drive API With Flutter Apps for details.
A: This worked for me:
Logging in using package google_sign_in and then get auth headers from it:
import 'package:google_sign_in/google_sign_in.dart'
show GoogleSignIn, GoogleSignInAccount;
import 'package:googleapis/people/v1.dart'
show ListConnectionsResponse, PeopleApi;
useGoogleApi() async {
final _googleSignIn = new GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
await _googleSignIn.signIn();
final authHeaders = _googleSignIn.currentUser.authHeaders;
// custom IOClient from below
final httpClient = GoogleHttpClient(authHeaders);
data = await PeopleApi(httpClient).people.connections.list(
'people/me',
personFields: 'names,addresses',
pageToken: nextPageToken,
pageSize: 100,
);
}
This is a custom IOClient implementation that automatically adds the auth headers to each request. The googleapis call support passing a custom HTTP client to be used instead of the default (see above)
import 'package:http/io_client.dart';
import 'package:http/http.dart';
class GoogleHttpClient extends IOClient {
Map<String, String> _headers;
GoogleHttpClient(this._headers) : super();
@override
Future<StreamedResponse> send(BaseRequest request) =>
super.send(request..headers.addAll(_headers));
@override
Future<Response> head(Object url, {Map<String, String> headers}) =>
super.head(url, headers: headers..addAll(_headers));
}
A: Update to the accepted answer
Along with google_sign_in and googleapis packages, now you can use extension_google_sign_in_as_googleapis_auth package (provided by flutter.dev) to get configured http client. So the accepted answer can be simplified to below. No implementation of GoogleHttpClient is necessary.
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/people/v1.dart';
useGoogleApi() async {
final _googleSignIn = new GoogleSignIn(
scopes: [
'email',
PeopleServiceApi.contactsReadonlyScope,
],
);
await _googleSignIn.signIn();
// custom IOClient
final httpClient = await _googleSignIn.authenticatedClient();
data = await PeopleApi(httpClient!).people.connections.list(
'people/me',
personFields: 'names,addresses',
pageToken: nextPageToken,
pageSize: 100,
);
}
A: I can't add comments yet, so I'll just post it as an answer.
I kept trying to make a GoogleHttpClient as per the top answer, but on the import, it says "The library 'package:http/http.dart' doesn't export a member with the shown name 'IOClient'."
I found the answer here https://pub.dartlang.org/packages/http#-changelog-tab-, which says you should import IOClient separately as such: import 'package:http/io_client.dart';
I thought this might help out others who are new to flutter and its implementation of Google APIs. | |
d11169 | Ok it turns out you spelt it getElementByTagName, whereas the method is actually getElementsByTagName. | |
d11170 | As stated here, you can extend the build script as ember-cli.
You can also look at the ember-cli user guide for built in configurations that you can use without making any extension first | |
d11171 | You can also do like we do in hawtio (http://hawt.io/) where we use REST calls to remote manage Camel applications, so we can control routes, see statistic, view routes, and much more. All this is made easier by using an excellent library called jolokia (http://jolokia.org/) that makes JMX exposed as REST services. Each JMX operation/attribute is easily callable as an URI template over REST. And data is in json format.
That what you can build UI consoles that just use REST for communication, and are not tied into the Java or JMX world etc.
Also the Java API on CamelContext allows you to control routes. And there is also the control-bus EIP that has more details: http://camel.apache.org/controlbus | |
d11172 | What you are looking for is often refered to as AC (access control). One of the most popular is an RBAC (role based access control) because it allows you to group your users/accounts into groups and give those groups certain privileges.
Let's go through the design steps of a minimal setup:
Basically what you are saying is, that you have some sort of accounts already for your users (except Guest, because that is a not-logged-in-user)
Now what the roles in RBA are, are basically groups that have or don't have certain privileges.
So that results in the following Relations:
*
*Zero to many Accounts belong to zero to many Roles (->group e.g. "Admin", "Manager", etc.)
*Zero to many Roles have zero to many privileges / rights (e.g. "Access the manager section" or "Update this record")
Now let's move on, what data for what part of that system you need to have in order to implement it
*
*Typically you have an ID on your account table for each account.
*Roles typically have an ID and a name.
*Privileges typically have at least a constant-like identifier (which should be the primary key, so that it's unique --- for example ACCESS_MANAGER - You can see why this is usefull in my code example below. It can be used to lookup ) and a name
That leads to the following tables:
Account(AccountID (PK), ...)
Account_Role(AccountID (PK, FK), RoleID (PK, FK))
Role(RoleID (PK), name)
Role_Privilege(RoleID (PK, FK), PrivilegeID (PK, FK));
Privilege(identify (PK), name)
Now you can manage roles and privileges these roles have.
If you want to check, if the current user has a specific privilege you can ask your DB, for example.
if(
$this
->getCurrentUser() //would return a dummy guest user with no roles assigned if no user is logged in
->hasPrivilege('ACCESS_MANAGER') //joins account via account_role to role to role_privilege and finally to privilege
) { /*display only links a manager would see*/ }
if($this->getCurrentUser()->hasPrivilege('ACCESS_ADMIN')) { /*display only links an admin would see*/ }
PS: The wiki articles provided are very theoretical. You might want to just google for queries like "php access control system" or similar to get you started with solutions others have come up with.
A: Give each user a number to identify what category they belong to. For example guests would be 1, employees would be 2 and managers would be 3. Then when they log in you store this inside a session.
To display a link for any given category you can do this. Just change the number for each category.
<?php if( $_SESSION[ 'user' ][ 'category' ] == 3 ) : ?>
<a href="www.google.co.uk">Link for a manager</a>
<?php endif; ?>
A: Assuming you have user roles set up already and some sort of class you can easily do this by:
if($users->role($userid) == "some role") //can be int or string which ever way you set it up
{
echo "a href='somelink.php'> Click to access</a>";
} | |
d11173 | If the phone is off and you turn it on you will then get the GCM message, its the same as you would an email that you got if you had your phone off. When it says there is no guarantee you will receive the message that means there is no guarantee the server will send it out. I remember reading there is a time to live on the message but its not one that expires for a while | |
d11174 | I think that the aggregate you have is not correct. A Course entity can exists on its own, it is not a child entity of a Student entity. A course has its own lifecyle: e.g. if a student leaves the school, the course keep on existing. The course id doesn't depend on the student id. The student can hold the course id, but they are different aggregates.
Anyway, to your question of passing just the course id to the "student.subscribeTo" method if they were an aggregate, the answer is no, you cannot pass the id of a child entity to an operation of the aggregate, as the child entities doesn't have a global identity known outside the aggregate. They have local id into the aggregate.
UPDATE:
Since Course and Student are two aggregates, the rule "student's age must be above the minimum age required to enroll the course" isn't an invariant. Why? Because an invariant is a business rule about the state of just an aggregate, that must always be transactionally consistent. An aggregate defines a transactional consistency boundary.
So, the rule is just a validation rule that must be checked when the student subscribes to a course ("student.subscribeTo" method). Since aggregates shouldn't use repositories, you can pass a domain service to the method, and the student aggregate would double-dispatch to the domain service in order to get the course from the course id.
Take a look at the aggregates chapter of the Red Book IDDD by Vaughn Vernon (pages 361-363) or the article by the same author:
http://www.informit.com/articles/article.aspx?p=2020371&seqNum=4
Hope it helps.
A: I'm also learning DDD and few days ago I ask a question to a similar problem you can find here.
What I've learned is that the only real answer is: it depends. There is no right or wrong approaches per se, everything must serve a purpose to the business problem and its solution. Although, there are guidelines and rules of thumb that can be very useful, for instance:
*
*Don't model reality. The domain model is an abstraction designed to solve a particular problem.
*Don't model based on data relationship. Every association must be there to enforce a rule or invariant and not because those objects are related in real life. Start modeling based on behavior.
*Prefer small aggregates.
*Prefer modify a single aggregate at the same time (use case / transaction), and use eventual consistency to update other aggregates.
*Make associations between aggregates by identity only.
I think the problem in your scenario is that there is a lot missing. Who owns that association and why? Is there any other use case that span both, student and course? Why do you put student.SubscribeTo(course) instead of course.enroll(student)? Remember that the goal of DDD is tackle a complex domain logic so it shines when approaching the write side of the model, the reading side can be done in many different ways without put a lot of associations into the model.
For what you've said, just validating the age is probably not and invariant that requires making a large aggregate:
If I change the Course.MinAge in some other places of my code I don't break my business requirements, as I want the age be respected only when subscribing the course and I don't mind if later the Course.MinAge changes.
Then there is no reason to enforce Student and Course to be consistent at all times (in this particular context/scenario), and there is no necessity of make them part of the same aggregate. If the only rule you need to enforce is Student.Age >= Course.MinAge you can stick with a simple:
Student.SubscribeTo(Course course)
where Student and Course are not part of the same aggregate. There is nothing against loading two different aggregates and use them in the same transaction, as long as you modify only one. (Well, there is nothing against modify two aggregates in the same transaction either, is just a rule of thumb, but probably you don't need to break it in this case).
Here Student.SubscribeTo will enforce the rule regarding the age. I have to say, it sounds "weird" to let the Student validate his own age, but maybe it is just right in your model (remember, don't model reality, model solutions). As the result, Student will have a new state holding the identity of the course and Course will remain unchanged.
Different case if business requirements state: when Course.MinAge changes students already enrolled in the course should be removed from the course if Student.Age < Course.MinAge.
Here you have to answer first (with the help of a domain expert) some more questions: Why should they be removed? Should they be removed immediately? What if they are attending the class in that moment? What does it mean for a student to be removed?
Chances are that there is no real need in the domain to remove the students at the same time the MinAge is changed (as when the operation is only considered successful when all happens, and if not, nothing happens). The students might need to enter a new state that can be solved eventually. If this is the case, then you also don't need to make them part of the same aggregate.
Answering the question in the title, unsurprisingly: it depends. The whole reason to have an aggregate is to protect invariants of a somehow related set of entities. An aggregate is not a HAS-A relationship (not necessarily). If you have to protect an invariant that spans several entities, you can make them an aggregate and choose an entity as the aggregate root; that root is the only access point to modify the aggregate, so every invariant is always enforced. Allowing a direct reference to an entity inside the aggregate breaks that protection: now you can modify that entity without the root knowing. As entities inside the aggregate are not accessible from the outside, those entities have only local identity and they have no meaning as standalone objects without a reference to the root. It is possible to ask the root for entities inside the aggregate, though.
You can, sometimes, pass a reference to an inner entity to another aggregate, as long as it's a transient reference and no one modify that reference outside the aggregate root. This, however, muddles the model and the boundaries starts to become blurry. A better approach is passing a copy of that entity, or event better, pass a immutable view of that entity (likely a value object) so there is no way to break invariants. If you think there is no invariant to break by passing a reference to an inner entity, then maybe there is no reason to have an aggregate to begin with. | |
d11175 | Just export the slides to html using the no input option:
jupyter nbconvert YOURNOTEBOOKSNAME.ipynb --to slides --no-input serve
For more check out nbconvert's documention | |
d11176 | The recommended way is to use AsyncTasks for long running tasks. So, not everything needs to be run with AsyncTasks, as you can get a performance hit due to the context switching.
As for how AsyncTasks work, read the documentation.
A: Use an AsyncTask and make sure to implement these as needed. You mention the idea of doing something in the background while a user is doing something so I'm guessing you'll want to alter the UI.
Take a look at these links for an more details from Android. They cover Runnable, AsyncTask and Handler
*
*Overview of them all http://developer.android.com/guide/components/processes-and-threads.html
*AsyncTask example http://developer.android.com/reference/android/os/AsyncTask.html
*Old but relevant, Painless Threading http://android-developers.blogspot.com/2009/05/painless-threading.html
*Another, more complex example http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I don't generally paste full examples in here but I had a lot of trouble finding an example I was happy with for a long time and to help you and others, here is my preferred method. I generally use an AsyncTask with a callback to the Activity that started the task.
In this example, I'm pretending that a user has triggered onClick(...) such as with a button, but could be anything that triggers a call into the Activity.
// Within your Activity, call a custom AsyncTask such as MyTask
public class MyActivity extends Activity implements View.OnClickListener, MyTask.OnTaskComplete {
//...
public void onClick(View v) {
// For example, thet user clicked a button
// get data via your task
// using `this` will tell the MyTask object to use this Activty
// for the listener
MyTask task = new MyTask(this);
task.execute(); // data returned in callback below
}
public void onTaskComplete(MyObject obj) {
// After the AsyncTask completes, it calls this callback.
// use your data here
mTextBox.setText(obj.getName);
}
}
Getting the data out of a task can be done many ways, but I prefer an interface such as OnTaskComplete that is implemented above and triggered below.
The main idea here is that I often want to keep away from inner classes as they become more complex. Mostly a personal preference, but it allows me to separate reusable tasks outside of one class.
public class MyTask extends AsyncTask<Void, Void, MyObject> {
public static interface OnTaskComplete {
public abstract void onTaskComplete(MyObject obj);
}
static final String TAG = "MyTask";
private OnTaskComplete mListener;
public MyTask(OnTaskComplete listener) {
Log.d(TAG, "new MyTask");
if (listener == null)
throw new NullPointerException("Listener may not be null");
this.mListener = listener;
}
@Override
protected MyObject doInBackground(Void... unused) {
Log.d(TAG, "doInBackground");
// do background tasks
MyObbject obj = new MyObject();
// Do long running tasks here to not block the UI
obj.populateData();
return
}
@Override
protected void onPostExecute(MyObject obj) {
Log.d(TAG, "onPostExecute");
this.mListener.onTaskComplete(obj);
}
} | |
d11177 | Assuming you want to store generic Objects you will need to use remove() instead of pop().
Your problem after that is returning True, which is not a valid return type for a view. Flask view raises TypeError: 'bool' object is not callable
from flask import session as sesh
@app.route('/todo/<profile_id>')
def todo(profile_id):
kw = request.args.get('kw', None)
lp = request.args.get('lp', None)
# remove if it exists
try:
print(sesh[lp])
sesh[lp].remove(kw)
sesh.modified = True
print("rem", sesh)
return '{}'.format(sesh[lp])
except Exception as e:
print(e)
# add if it doesn't exist
if kw and lp:
try:
sesh[lp].append(kw)
except:
sesh[lp] = [kw]
print("add",sesh)
sesh.modified = True
return '{}'.format(sesh[lp]) | |
d11178 | As your console tab shows, the problem is with a HTML document or Javascript (jquery), not with the image itself.
Moreover, why isn't your varnishlog showing the second request? What server is returning the "304 Not Modified"? There's something in between Chrome and Varnish. A Chrome plugin? | |
d11179 | The topic you're interested in is called "url rewriting". You will also see similar looking url's on sites using MVC as well.
It has very little to do with preventing security exploits.
I think you are referring to sql injection when you say most websites are attacked from their URL. This is possible when using GET variables (the one's passed by url) in unsanitized sql statements. The same techniques are easily used against sites that use POST variables, it's just requires a little more effort to populate the values.
I suggest you focus your research on "SQL Injection" instead. | |
d11180 | This answers nothing, just report that I cannot repeat it, the code is compiled with
gcc x.c -W -Wall -fopenmp -ggdb
and gdb session as the following, everything seems fine, I guess it may be related with compile flag, try add -O0 in addition to -g or -ggdb
Reading symbols from ./a.out...done.
(gdb) break 9
Breakpoint 1 at 0x40064d: file x.c, line 9.
(gdb) run
Starting program: /some/path/to/a.out
[Thread debugging using libthread_db enabled]
Thread 3 "a.out" hit Breakpoint 1, main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 2
a = 0
(gdb) info threads
Id Target Id Frame
1 Thread 0x2aaaaaaebb40 (LWP 31287) "a.out" main._omp_fn.0 () at x.c:9
2 Thread 0x2aaaabab0700 (LWP 31516) "a.out" main._omp_fn.0 () at x.c:9
* 3 Thread 0x2aaaabcb1700 (LWP 31517) "a.out" main._omp_fn.0 () at x.c:9
4 Thread 0x2aaaabeb2700 (LWP 31518) "a.out" main._omp_fn.0 () at x.c:9
(gdb) thread 1
[Switching to thread 1 (Thread 0x2aaaaaaebb40 (LWP 31287))]
#0 main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 0
a = 0
(gdb) thread 2
[Switching to thread 2 (Thread 0x2aaaabab0700 (LWP 31516))]
#0 main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 1
a = 0
(gdb) | |
d11181 | I solved an issue with this same message caused by a proxy-blocker of the client. I had to set --proxy-server flag in my customLauncher in karma.conf.js, so the karma server could get the ChromeHeadless and execute the tests perfectly.
karma.conf.js
browsers: ['MyChromeHeadless'],
customLaunchers: {
MyChromeHeadless: {
base: 'ChromeHeadless',
flags: [
'--no-sandbox',
'--proxy-bypass-list=*',
'--proxy-server=http://proxy.your.company'
]
}
} | |
d11182 | You can use the ARN in the --function-name parameter when executing AWS CLI calls for the AWS lambda API.
Here's an example for the get-function api:
--function-name (string)
The name of the Lambda function, version, or alias.
Name formats
Function name - my-function (name-only), my-function:v1 (with alias).
Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function .
Partial ARN - 123456789012:function:my-function | |
d11183 | Node.js processes the request one after the other. There is only one thread.
However, if you for example query the database for some information and pass a callback, while the query is executed, node.js can process new requests. Once the database query is completed, node.js calls the callback and finishes processing the first request.
EDIT:
Simple server example:
var http = require('http');
var numresponses = 0;
http.createServer(function (request, response) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is response #' + (++numresponses));
}).listen(80);
this server will always print out the number of the request even if two requests happen simultaneously, node will choose one that gets processed first, and both will have different numbers. | |
d11184 | What version of Transcrypt are you using? Wasn't able to replicate the error using Python 3.9.0 and Transcrypt 3.9.0. You can check like this (Win):
> transcrypt -h | find "Version"
# and may as well double check that the right version of python was used:
> python --version
The Python and Transcrypt versions should match, as Transcrypt uses Python's AST that may change between versions.
Another aspect is that I first installed Transcrypt into a virtual env as follows (Win):
> py -3.9 -m venv wenv
> wenv\Source\activate.bat
> pip install transcrypt
> python -m transcrypt -b -m -n test.py
It sometimes happens that one inadvertently uses the wrong version of Python. 'py' is the Python launcher on Windows and useful to launch the right version if you have multiple versions installed. On Linux there are typically binaries in /usr/bin such as 'python3.9' or a symlink such as 'python3' that links to the most recent 3 version. Installing into a virtual env as demonstrated is also helpful, as various problems can come about otherwise.
The above compiled test.py without error (Win 10 cmd.exe). Fwiw, the file was saved as utf-8 and compile worked with and without a BOM. | |
d11185 | The why behind your pattern escapes me but one solution could be to define a null collection, (docs) copy the records you need to that, do your work, and then copy back the results into the original collection for automatic sync back to the server.
myLocalCollection = new Mongo.Collection(null); | |
d11186 | Why don't you use something like this to generate your $dados object?
There is no need to build your data as a html ajax GET Parameter string.
var $dados = {};
$("#form").find('textarea').each(function(){
$dados[$(this).attr('name')] = tinyMCE.get($(this).attr('id')).getContent();
}); | |
d11187 | The most likely thing here is that you don't actually have a signed -0.0, but your formatting is presenting it to you that way.
You'll get a signed negative zero in floating point if one of your calculations yields a negative subnormal number that's rounded to zero.
If you do indeed have a pure signed zero, then one workaround is to clobber it with a the ternary conditional operator as printf does reserve the right to propagate the signed zero into the output: f == 0.0 ? 0.0 : f is one such scheme or even with the flashier but obfuscated f ? f : 0.0. The C standard defines -0.0 to be equal to 0.0. Another way (acknowledge @EricPostpischil) is to add 0.0 to the value.
A: For floating point values there are two zeroes 0.0 and -0.0. They compare as equal (e.g. -0.0 == 0.0 returns 1) but they are two distinct values. They are there for symmetry, because for any small value other than 0, the sign does make a mathematical difference. For some edge cases they make a difference. For example 1.0/0.0 == INFINITY and 1.0/-0.0 == -INFINITY. (INFINITY, -INFINITY and NAN) are also values that the floating point variables can take.
To make printf not print -0 for -0.0 and any small that would be truncated to 0 or -0, one way is to artificially put very small values to 0.0, for example:
if(abs(x) < 1e-5) x = 0.0; | |
d11188 | It can happen for a number of reasons, see here more details.
You should try firs @bayanAbuawad suggestion that works most of the times:
*
*Add the platforms with cordova platform add ios android
*Remove them with cordova platform remove ios android
*Add them again.
It is super weird, but it’s related to a faulty android.json and ios.json inside the platforms folder. | |
d11189 | Assigning structs does a member-wise assignment, and for arrays this means assigning each item. (And this is done recursively for "multiple dimension" arrays, which are really just arrays of arrays.)
You are correct that it does a shallow copy, even on arrays. (I'm assuming that you have not overloaded op= with respect to C++; if you overload it you can do anything you want.)
Remember that a shallow copy means copying the value of something, while a deep copy means copying the value to which something points or refers. The value of an array is each item in it.
The difference between shallow and deep is most meaningful when you have a type that does indirection, such as a pointer. I find my answer the most helpful way to look at this issue, but you could also say "shallow" vs "deep" doesn't even apply to other types, and they are just "copied".
struct S {
int n;
int* p;
int a[2];
int* ap[2];
int xy[2][2];
};
void f() {
S c, d;
c = d;
// equivalent to:
c.n = d.n;
c.p = d.p;
c.a[0] = d.a[0]; // S::a is similar to your situation, only using
c.a[1] = d.a[1]; // int instead of char.
c.ap[0] = d.ap[0];
c.ap[1] = d.ap[1];
c.xy[0][0] = d.xy[0][0];
c.xy[0][1] = d.xy[0][1];
c.xy[1][0] = d.xy[1][0];
c.xy[1][1] = d.xy[1][1];
}
That I used int above doesn't change anything of the semantics, it works identically for char arrays, copying each char. This is the S::a situation in my code.
Note that p and ap are copied shallowly (as is every other member). If those pointers "own" the memory to which they point, then it might not be safe. ("Safe" in your question is vague, and really depends on what you expect and how you handle things.)
For an interesting twist, consider boost::shared_ptr and other smart pointers in C++. They can be copied shallowly, even though a deep copy is possible, and this can still be safe.
A: If by "shallow copy", you mean that after assignment of a struct containing an array, the array would point to the original struct's data, then: it can't. Each element of the array has to be copied over to the new struct. "Shallow copy" comes into the picture if your struct has pointers. If it doesn't, you can't do a shallow copy.
When you assign a struct containing an array to some value, it cannot do a shallow copy, since that would mean assigning to an array, which is illegal. So the only copy you get is a deep copy.
Consider:
#include <stdio.h>
struct data {
char message[6];
};
int main(void)
{
struct data d1 = { "Hello" };
struct data d2 = d1; /* struct assignment, (almost) equivalent to
memcpy(&d2, &d1, sizeof d2) */
/* Note that it's illegal to say d2.message = d1.message */
d2.message[0] = 'h';
printf("%s\n", d1.message);
printf("%s\n", d2.message);
return 0;
}
The above will print:
Hello
hello
If, on the other hand, your struct had a pointer, struct assignment will only copy pointers, which is "shallow copy":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data {
char *message;
};
int main(void)
{
struct data d1, d2;
char *str = malloc(6);
if (str == NULL) {
return 1;
}
strcpy(str, "Hello");
d1.message = str;
d2 = d1;
d2.message[0] = 'h';
printf("%s\n", d1.message);
printf("%s\n", d2.message);
free(str);
return 0;
}
The above will print:
hello
hello
In general, given struct T d1, d2;, d2 = d1; is equivalent to memcpy(&d2, &d1, sizeof d2);, but if the struct has padding, that may or may not be copied.
Edit: In C, you can't assign to arrays. Given:
int data[10] = { 0 };
int data_copy[10];
data_copy = data;
is illegal. So, as I said above, if you have an array in a struct, assigning to the struct has to copy the data element-wise in the array. You don't get shallow copy in this case: it doesn't make any sense to apply the term "shallow copy" to a case like this. | |
d11190 | In an more abstract way a map-structure is nothing more than a function mapping inputs of a certain type to an array. A map can thus be replaced by a array and a function. (The difference being you will have to define the function yourself)
Before I get started with the rest I would like to point out that if your model compiles generally fast, you might want to try a triple array without the function, rates_index = array3d(0..60, 1..3, 1..501, [ 15, 20, 23, ..... This will cost more memory, but will make the model more flexible.
The general way of using a map-structure would be to define a function map_index, that maps your input, in this case integers, to the index of the array, also integers. This means that we can then define a extra level array to point to the right one: rates_index = array3d(0..nr_arrays, 1..3, 1..501, ..... This means that the content of get_rates can then be: rates_index[map_index(index), dc_size, load].
The function map_index itself in its simplest form would contain another version of your if-then-else statements:
function int: map_index(int: index) =
if index == 0 then
0
else if index == 12 then
1
else if index == 16 then
2
else if index == 20 then
3
else
assert(false, "unknown index", 0)
endif endif endif endif;
However you can make it dynamic by generating an extra array containing the array number for each index, putting -1 for all arrays that are not available. For your example the mapping would look like this: array[0..20] of int: mapping = [0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 2, -1, -1, -1, 3];. The map_index function could then dynamically be defined as:
function int: map_index(int: index) =
mapping[index]; | |
d11191 | When using the extension method Find() you must be sure that in your model you have the attribute [Key] in the property representing your Id (primary key in your table).
And you can try like this:
Character character = db.Characters.Find(User.Identity.GetUserId());
The line above will work but not this one character= character.ToList(); because you declare character as an object and you can't assign it to a list of object in your case Character
If you want it to work, you can do something like this:
var myCharacters =db.Characters.Where(c=>c.someField=="someValue");
List<Character> myList = myCharacters.ToList();
Hope it will help. | |
d11192 | You can compute the mean, and analyze it the same way as you did for k-means.
For maybe better results, you can weigh each document by the responsibility factor, if these are exposed by the sklearn API. | |
d11193 | Simply use:
UpdateValue(event:any,myStock: stock) {
// ...
console.log(event.checked);
}
Here's a working stackblitz for the same.
A: Just use ngModel
<mat-cell *matCellDef="let row"> <mat-checkbox
[checked]="row.isDisabled"
[(ngmModel)]="checkValue"
(change)="UpdateValue($event,row)"></mat-checkbox> </mat-
cell>
UpdateValue(event:any,myStock: stock) {
alert(this.checkValue);
} | |
d11194 | In a nutshell, the first ELEMENT declaration is saying the child elements have to be in a specific order. The second ELEMENT declaration is saying the child elements can be in any order.
The following means: a bank element containing zero or more account elements, followed by zero or more customer elements, followed by zero or more depositor elements. (In that specific order.)
<!ELEMENT bank (account*, customer*, depositor*)>
The following means: a bank element containing zero or more account or customer or depositor elements (in any order).
<!ELEMENT bank (account | customer | depositor )*>
The ',' means "followed by" and the '|' means "or". The '*' means zero or more. Also, a '+' means one or more (at least one).
A: It denotes a regular expression. Though I'm not very good at that, I think the second tag accepts sub-element of either account or customer or depositor. | |
d11195 | Simplest Approach might be to Drop the constraint,
Perform Update Queries
Again, Introduce the Foreign Key Constraint.
A: drop the constraint and re-create the constraint with ON UPDATE CASCADE
then execute the update stament on the parent table no child table would get modified.
ALTER TTABLE b ADD CONSTARINT fk_const
FOREIGN KEY(a_id) REFERENCE a (id) ON UPDATE CASCADE
now execute this update
update A set id=lower(id); | |
d11196 | You are manually checking commonName against individual cases, and TypeScript really doesn't have good support for type checking the body of makeSound() if it is generic. Even though commonName is of the generic type C, checking commonName only narrows the type of commonName itself, it does not further constrain C. So unfortunately, even if the compiler knows that commonName is "cat", it does not know that C is "cat". It can still be "cat" | "dog", and thus worries about the (admittedly unlikely) possibility of a call like
makeSound(
Math.random() < 0.99 ? "cat" : "dog",
Math.random() < 0.99 ? dog : cat
); // no error?!
We have failed to actually make the link we intended to make, and even though it's usually good enough (I mean, really, who passes cross-correlated unions into functions like that?), the compiler is unwilling to type check the body.
There are various feature requests asking for an improvement here. For example, microsoft/TypeScript#27808 wants to make it possible to say something C extends oneof keyof TypeMap so that the full union type keyof TypeMap would be rejected. For now though nothing is implemented, and if we want to write your code we will need to refactor (or else pepper your code with type assertions to suppress the error... but let's investigate refactoring.)
Because the return type of makeSound() does not depend on C, you can refactor your call signature to a non-generic version that enforces the actual constraint you have. Essentially the parameter tuple, [commonName, animal] forms a discriminated union where the property at index 0 is the discriminant, and checking it will narrow the type of the property at index 1. You can compute this union type like this:
type MakeSoundParam = { [K in keyof TypeMap]:
[commonName: K, animal: TypeMap[K]]
}[keyof TypeMap];
/* type MakeSoundParam =
[commonName: "cat", animal: Cat] |
[commonName: "dog", animal: Dog] */
TypeScript supports control flow analysis for destructured discriminated unions, which means you can rewrite your function as:
const makeSound = function (...[commonName, animal]: MakeSoundParam) {
if (commonName === 'cat') {
return animal.purr(); // okay
} else if (commonName === 'dog') {
return animal.bark(); // okay
}
}
That compiles without error. And just to be sure that makeSound() still behaves properly from the caller's side:
const caller = function (cat: Cat, dog: Dog) {
makeSound('cat', cat); // ok
makeSound('dog', dog); // ok
makeSound('cat', dog); // error
makeSound('dog', cat); // error
makeSound(
Math.random() < 0.99 ? "cat" : "dog",
Math.random() < 0.99 ? dog : cat
); // error
}
Looks good, and even the cross-correlated call is rejected.
Playground link to code | |
d11197 | Is this a real query? I'm asking because the query is invalid - having clause is equal to writing 1 > 1, so always False... And if you replace '>' with '=' the query is always true unless the result from sum() is NULL... | |
d11198 | You cannot use the name you've given to the dimension via the interface. You'd have to use the "dimension" keyword plus the numeric index (order of creation), so the dimension that is referred to as "productSize" in the reports would in your example be addressed as "dimension1" in the code:
...
'list': 'Search Results',
'dimension1': 'L', // product scoped custom dimension
'position': 1
...
After that GA will pick your dimensions automatically from the datalayer. | |
d11199 | In jQuery we use the selector for select any elements, and we have to put . for the class and # to the id selector so please put # or . before your element.
In your case, $('#Hid_BasicSalary'); or $('.Hid_BasicSalary'); is your answer.
A: i was missing # with $.
var BasicSalary = $('Hid_BasicSalary');
i write this instead of this
var BasicSalary = $('#Hid_BasicSalary');
A: Try this
var BasicSalary = $('#Hid_BasicSalary');
A: Use This code is page load to get new value from hidden
Request.Form["hdnvalue"];
A: you missed the "#" and i think that you should use the hidden control's clientid.
var BasicSalary = $('#<%=Hid_BasicSalary.ClientID%>');
A: try this to get value of server control from javascript/jquery
var BasicSalary = document.getElementById('<%=Hid_BasicSalary.ClientID%>').value | |
d11200 | You could simply pass two, comma-separated, selectors to the find() method:
$('#select-service').find('optgroup, option').remove();
You could also just remove all children elements for the same result:
$('#select-service').children().remove();
// or:
$('#select-service > *').remove();
The most concise approach would be to just remove the element using the .empty() method:
$('#select-service').empty();
A: The simplest way
$('#select-service optgroup').remove()
Since optgroup is the parent of option it will remove it as well.
A: Like this:
$('#select-service')
.find('optgroup')
.remove();
This will not only remove your optgroup, but all contents within it, meaning your option will also be removed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.