id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23530400
|
redirect(base_url().'user/login/?redirect=site/cart_steps/steps');
and it works fine in localhost and when i uploaded it to server it didnt redirect. I checked all the codes and above this all code executes. But when it comes to redirect the page doesnt redirects. I also tried
redirect(base_url().'user/login?redirect=site/cart_steps/steps');
redirect(base_url().'user/login');
header('Location:'.base_url().'user/login?redirect=site/cart_steps/steps');
header('Location:'.base_url().'user/login');
but the page didn't redirect? and also i checked out this The header function is not working on online server?
but it cant help me too.... can any one explain what is the problem here....
A: You can use the refresh method like this:
<?php
redirect($this->input->server('HTTP_REFERER'), 'refresh'); // refresh the page
?>
Another common mistake could be echoing out / printing something before the redirection.
A: I would check your CodeIgniter error logs to verify that particular file isn't throwing any error messages that could tell you what needs fixing.
If you haven't already, you'll probably also want to make sure that the URL helper is loaded.
ex:
$this->load->helper('url');
A: Another solution
<meta http-equiv="refresh" url=http://example.com/">
A: Try to use like this,
First define your base URL as :
$base_url = "Your base url";
then apply this $base_url variable to your redirect link.
Hope this will help.
| |
doc_23530401
|
I want to do this:
date_num = '09'.gsub(/<match the zero>/, '')
date_num = '20'.gsub(/<same expression should not match the zero>/, '')
What is the best way of doing this in Ruby?
A: You can use a negative look-behind to prevent a match on zeros that are preceded by a non-zero digit. This does not require the numerical part to be at the beginning of the string.
r = /(?<![1-9])0+(?=[1-9])/
'string A 09'.gsub(r, '') #=> "string A 9"
'string B 20'.gsub(r, '') #=> "string B 20"
'string C 00000020'.gsub(r, '') #=> "string C 20"
'string D 0'.gsub(r, '') #=> "string D 0"
'string E 0a'.gsub(r, '') #=> "string E 0a"
'Agent 007'.gsub(r, '') #=> "Agent 7"
Edit: I added a positive look-ahead to deal with the penultimate and antepenultimate examples. I think @pguardiario has a better solution, though I might be inclined to replace his \B with the look-ahead I'm now using here.
A: \A0+(?=\d)
I haven't used ruby but if Regex is still Regex then that right there should match just leading 0's. The ^ tells it to look at the front of the string and then looks for a group of 0's to be the first elements. It will match 00000032423 but not 23000000
EDIT:
Added John and Jorg's comments into the solution
A: You can probably get it with just word boundaries:
'09 20 008 2020 0'.gsub(/\b0+\B/, '')
#=> "9 20 8 2020 0"
but you might want to check for decimals as well:
'00002.0002'.gsub(/(?<!\.)\b0+\B/, '')
#=> "2.0002"
| |
doc_23530402
|
Does anybody know?
Exception:
W/BugSenseHandler(2881): Transmitting ping Exception Connect to /168.63.83.24:443 timed out
A: It means the app can't connect to the IP 168.63.83.24 on port 443 (which is usually for HTTPS), it times out before it's able to connect.
| |
doc_23530403
|
I have downloaded the framework and moved to the webroot(in linux), and execute the command "yiic webapp ../../testapplication".
But i got the error as "command not found".
Install YII framework in xampp for ubuntu
I have followed these steps. But I couldn't succeed.
Please help me on this.
A: You need to run
./yiic
to explicitly name the executable (because yiic alone is not in you $PATH).
A: Syntax is:
$ /path/to/yiic webapp /path/to/webapp
I suggest you to do this:
$ cd /var/www
$ mkdir yourapp
$ cd yourapp
$ git clone git@github.com:yiisoft/yii
$ ./yii/framework/yiic webapp .
When a new version of yii is released ...
$ cd /var/www/yourapp/yii
$ git pull origin master
Very easy and fast.
A: At First Go to the xampp php.exe folder in cmd and after that run this command
php yii/framework/yiic.php webapp myfirstsite
It's only for windows xampp or wamp any server
| |
doc_23530404
|
pattern = next(p for p in pattern_list if p.method(input))
However, in my application it is common that there is no such p for which p.method(input) is true, and so this will raise a StopIteration exception. Is there an idiomatic way to handle this without writing a try/catch block?
In particular, it seems like it would be cleaner to handle that case with something like an if pattern is not None conditional, so I'm wondering if there's a way to expand my definition of pattern to provide a None value when the iterator is empty -- or if there's a more Pythonic way to handle the overall problem!
A: next accepts a default value:
next(...)
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
and so
>>> print next(i for i in range(10) if i**2 == 9)
3
>>> print next(i for i in range(10) if i**2 == 17)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> print next((i for i in range(10) if i**2 == 17), None)
None
Note that you have to wrap the genexp in the extra parentheses for syntactic reasons, otherwise:
>>> print next(i for i in range(10) if i**2 == 17, None)
File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument
| |
doc_23530405
|
The main problem I have is that the values comes in different data types, so the INT does not return as a string.
Is there a simple way to do it? or do I have to look at the examples where you create custom converter?
dynamic data = table.CreateDynamicInstance();
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(data);
_settings.Request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
jsonBody returns...
{"phone":555555,"email":"john.doe@svea.com"}
but should return...
{"phone":"555555","email":"john.doe@svea.com"}
Thanks in advance
| |
doc_23530406
|
We have the functionality to capture screenshots but after the package upgrade facing an error while screenshot capture. I am using webview to render view in the electron application.
Here is the code how I am using to load view in webview.
const webview = <webview src="path" class="webview__3kBDE" style="width: 768px; height: 576px; margin-top: 0px; margin-left: auto; margin-right: auto;"></webview>
const rawImage = await webview.capturePage()
const URL = rawImage.toPNG()
When I am printing the rawImage I am getting blank object so while rawImage.toPNG() I am facing an error. If anyone has any idea how to fix this error that would be a great help. Thank you.
A: The Electron 10 release had major changes and if you are using the Electron 10 > the remote module is now disabled by default. To use the remote module, enableRemoteModule: true must be specified in WebPreferences:
const w = new BrowserWindow({
webPreferences: {
enableRemoteModule: true
}
})
For more details check here https://www.electronjs.org/docs/latest/breaking-changes#default-changed-enableremotemodule-defaults-to-false
| |
doc_23530407
|
Building on the previous update, I think I have a better insight into doing this, but I need the answer to this question. In the current for loop there is a variable named tstring. I need to do a something like the following, but it does not work. I get the error Collection expression type 'NSString *' may not respond to countByEnumeratingWithState:objects:count:' How can I fix this for clause?
for (NSUInteger i = 1; i < match.numberOfRanges; ++i)
{
NSRange matchedRange = [match rangeAtIndex: i];
NSString* tstring = [string substringWithRange: matchedRange];
for (char* suit in tstring){ // error here ********
NSLog(@"char: %@",suit);}
NSLog(@"range %lu string: %@", (unsigned long)i, tstring);
}
update 1
update 0
Here is another approach, that does not require a search, but I still don't have any idea how to accomplish this approach in the context of the for loop.
I need a dictionary like the following schematic representation which associates with each card (2 to Ace) an integer from 0 to 12. (I think I know how to create a dictionary in C; maybe not in objective-c.)
βββ¬ββ¬ββ¬ββ¬ββ¬ββ¬ββ¬ββ¬ββ¬ββ¬βββ¬βββ¬βββ
β0β1β2β3β4β5β6β7β8β9β10β11β12β
βββΌββΌββΌββΌββΌββΌββΌββΌββΌββΌβββΌβββΌβββ€
β2β3β4β5β6β7β8β9βTβJβQ βK βA β
βββ΄ββ΄ββ΄ββ΄ββ΄ββ΄ββ΄ββ΄ββ΄ββ΄βββ΄βββ΄βββ
I need a struct with four nouns or arrays, I am not sure which, each of length 13 like this. This is similar to the original struct, but now the members are card suits, not players' positions.
struct board {
int num;
char spade[13]
char heart[13]
char diamond[13]
char club[13]
};
Assuming the following deal of Board number 1,
Q952.652.KJT4.95 T.KQT84.A865.J73 K8763.A7.Q.KQT84 AJ4.J93.9732.A62
I need the following process in the for loop of my code.
spade[10] = N
spade[7] = N
spade[3] = N
spade[0] = N
heart[4] = N
heart[3] = N
etc.
The question is, "How do you do that processing in a for loop?"
update 0
The following code is working for me but I need to alter it for the purpose described below. My console output (at least, the beginning) is provided below, also. From the output I need to retain results of range 1 and range 4 thru 19 in a special way.
The little table below contains range numbers in a 4 by 4 array with rows labeled Spades, Hearts, Diamonds, Clubs and columns labeled North, East, South, and West. When a Heart is selected, I need to search the contents of row H to determine whether that card is in N,E,S, or W and report the result. Notice that in the table the contents of each cell is a string containing either nothing (is empty) or a set of letters from '23456789TJQKA' and each row has all 13 letters somewhere in it. The numbers in the table just refer to the range number in the current output.
N E S W
S 4 8 12 16
H 5 9 13 17
D 6 10 14 18
C 7 11 15 19
I would like to learn how to store the results in anticipation of the search task. Can I create a C struct for which each member contains the integer board number (a number between 1 and 36) and the 4 strings? For example would the struct below work? And if it does, how does one search in such a struct in objective-c? I could also use some help populating the struct in my loop.
struct board {
int num;
char N[13]
char E[13]
char S[13]
char W[13]
};
Code excerpt follows.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:toMatch options:NSRegularExpressionDotMatchesLineSeparators error:&error];
NSLog(@"pattern length: %lu", (unsigned long)[toMatch length]);
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
NSLog(@"number of matches: %lu", (unsigned long)numberOfMatches);
for (NSTextCheckingResult* match in [regex matchesInString:string options:NSRegularExpressionDotMatchesLineSeparators range:NSMakeRange(0, [string length])])
{
NSLog(@"Number of ranges in match: %u", match.numberOfRanges);
for (NSUInteger i = 0; i < match.numberOfRanges; ++i)
{
NSRange matchedRange = [match rangeAtIndex: i];
NSString* tstring = [string substringWithRange: matchedRange];
NSLog(@"range %lu string: %@", (unsigned long)i, tstring);
}
}
Sample output follows.
2013-02-04 16:24:06.583 [71684:11303] string length: 22365
2013-02-04 16:24:06.591 [71684:11303] pattern length: 347
2013-02-04 16:24:06.602 [71684:11303] number of matches: 36
2013-02-04 16:24:06.613 [71684:11303] Number of ranges in match: 20
2013-02-04 16:24:06.613 [71684:11303] range 0 string:
[Board "1"]
[West ""]
[North ""]
[East ""]
[South ""]
[Dealer "N"]
[Vulnerable "None"]
[Deal "N:Q952.652.KJT4.95 T.KQT84.A865.J73 K8763.A7.Q.KQT84 AJ4.J93.9732.A62"]
2013-02-04 16:24:06.613 [71684:11303] range 1 string: 1
2013-02-04 16:24:06.613 [71684:11303] range 2 string: N
2013-02-04 16:24:06.614 [71684:11303] range 3 string: None
2013-02-04 16:24:06.614 [71684:11303] range 4 string: Q952
2013-02-04 16:24:06.614 [71684:11303] range 5 string: 652
2013-02-04 16:24:06.614 [71684:11303] range 6 string: KJT4
2013-02-04 16:24:06.614 [71684:11303] range 7 string: 95
2013-02-04 16:24:06.614 [71684:11303] range 8 string: T
2013-02-04 16:24:06.614 [71684:11303] range 9 string: KQT84
2013-02-04 16:24:06.614 [71684:11303] range 10 string: A865
2013-02-04 16:24:06.615 [71684:11303] range 11 string: J73
2013-02-04 16:24:06.615 [71684:11303] range 12 string: K8763
2013-02-04 16:24:06.615 [71684:11303] range 13 string: A7
2013-02-04 16:24:06.615 [71684:11303] range 14 string: Q
2013-02-04 16:24:06.615 [71684:11303] range 15 string: KQT84
2013-02-04 16:24:06.616 [71684:11303] range 16 string: AJ4
2013-02-04 16:24:06.616 [71684:11303] range 17 string: J93
2013-02-04 16:24:06.616 [71684:11303] range 18 string: 9732
2013-02-04 16:24:06.616 [71684:11303] range 19 string: A62
A: I feel like this question has strayed pretty far from "how do I do X?" and started to tread really close to "please do X for me." That said, I did think about it for a little while last night, and I had some thoughts to share that might be helpful to you as you move forward.
First, yes, this can be modeled with any number of C structs. You've already explored a couple of them. One thought that you haven't proposed yet would be to use a bitmap to represent hands. There are 52 cards in the deck; One way to store hands would be using a 64 bit integer, and making 52 of the bits correspond to cards in the deck. A hand contains a specific card if the bit corresponding to the specific card is set. Searching these hands then becomes a simple bitwise AND operation. You could even get creative with the interface, and use C unions to make the underlying representation be a 64 bit type while allowing structured access to subsets (like suits or positions) perhaps by saying that each suit corresponded to 16 bits of the underlying type.
That said, given the size of the data set here, there are relatively few ways to get into performance trouble, and after chewing on it for a bit, I started to feel like efforts to find the best or 'most quickly searchable' data structure constituted pre-mature optimization. Even if you made this application's data model a fully-blown out Objective-C object graph, with classes for the board, each position, each hand, even object instances for each card, you're still solving a "constant sized" problem (with an opportunity for "constant time" performance.) IIUC, there will never be more than 52 cards in the deck, nor more than 4 positions, nor more than 36 boards in a game. It's a pretty well-constrained problem. If you were planning to import tens of thousands of these games and then query across all of them, then the data structure you picked might start to matter, but at this point (ingesting one game) I feel pretty confident when I say that any Mac or iOS device would have no trouble digesting this problem with adequate performance even with the most brute-force of approaches.
Next, I would suggest abandoning the use of regular expressions in parsing the contents of the [Deal "..."] line. Could you use regexes? Sure. But it would be simpler to get the quoted string as a const char* (see -[NSString UTF8String]) and then go through the characters sequentially: First character is [NSEW] and identifies the first position (which will likely need to be stored in your structure, but is missing so far). Then a useless : to ignore. Then start reading cards for spades. When you hit a . increment the suit. When you hit a <space> increment the position. You could use regular expressions to pull out these parts, but the simple way is so much more straightforward, I'd suggest running with it. (I should mention, given the context, that this simpler way is also drastically faster, but I maintain that choosing this method solely for performance would be pre-mature optimization. So, don't choose this method for performance, choose it for simplicity!)
Lastly, I feel like I should mention that while my 2 minute google-fu has failed to find an open source, C PBN reading implementation (and hence model data structure) that was any good, I find it really hard to believe that there isn't one out there. My search was somewhat complicated by "bridge" being such an overloaded English word. I might suggest sniffing around some more and seeing if you can find a mature open source implementation to use either as is, or as inspiration, instead of rolling your own.
EDIT:
I wrote out one potential for loop to populate the structure you propose:
// Your structure, but as a typedef for clarity.
typedef struct {
int num;
char spade[13];
char heart[13];
char diamond[13];
char club[13];
} board;
// The quoted string in the [Deal "..."] line; you already know how to get this.
NSString* dealString = @"N:A8.J762.KQ742.98 KQ53.K93.A85.T52 J97.A8.J963.J743 T642.QT54.T.AKQ6";
// Set up some arrays to use as maps between ints and chars...
// ...for positions:
const char* const positionIntToCharMap = "NESW";
int positionCharToIntMap['Z'] = { 0 };
for (int i = 0, len = (int)strlen(positionIntToCharMap); i < len; ++i) positionCharToIntMap[positionIntToCharMap[i]] = i;
// and cards:
const char* const cardIntToCharMap = "23456789TJQKA";
int cardCharToIntMap['Z'] = { 0 };
for (int i = 0, len = (int)strlen(cardIntToCharMap); i < len; ++i) cardCharToIntMap[cardIntToCharMap[i]] = i;
// and suits:
const char* const suitIntToCharMap = "SHDC";
int suitCharToIntMap['Z'] = { 0 };
for (int i = 0, len = (int)strlen(suitIntToCharMap); i < len; ++i) suitCharToIntMap[suitIntToCharMap[i]] = i;
const char* dealCString = [dealString UTF8String];
const size_t dealCStringLen = strlen(dealCString);
board thisBoard = { 0 };
if (dealCStringLen)
{
char suit = 'S'; // start with spades
char pos = dealCString[0]; // first character is starting position
for (off_t i = 1; i < dealCStringLen; ++i)
{
if (dealCString[i] == ':')
{
continue;
}
else if (dealCString[i] == '.') // advance the suit
{
const int currentSuitInt = suitCharToIntMap[suit];
const int nextSuitInt = (currentSuitInt + 1) % 4;
suit = suitIntToCharMap[ nextSuitInt ];
}
else if (dealCString[i] == ' ') // advance the position and reset the suit
{
const int currentPosInt = positionCharToIntMap[pos];
const int nextPosInt = (currentPosInt + 1) % 4;
pos = positionIntToCharMap[ nextPosInt ];
suit = 'S';
}
else // read the card
{
const char charForCard = dealCString[i];
const int intForCard = cardCharToIntMap[charForCard];
// Mark the current position in the appropriate array.
if (suit == 'S')
{
thisBoard.spade[intForCard] = pos;
}
else if (suit == 'H')
{
thisBoard.heart[intForCard] = pos;
}
else if (suit == 'D')
{
thisBoard.diamond[intForCard] = pos;
}
else if (suit == 'C')
{
thisBoard.club[intForCard] = pos;
}
}
}
}
// thisBoard is now populated.
I hope this helps.
| |
doc_23530408
|
In order to aggregate by days I've tried these two ways:
aggregate(myzoo,format((index((myzoo)),"%Y-%m-%d")),sum)
aggregate(myzoo,as.Date(index(myzoo)),sum)
I don't know why they don't give the same output.
myzoo series had the weekends removed. The "as.Date way" seems to be OK but the "format way" aggregation gives me data on the weekends.
Why?
Which one is the right?
I've even tried it as.POSIXct(format(...))
A: As I mentioned in my comment, you need to be careful when changing the format of a timestamp that includes time with a time zone, because it can get shifted between days. Without any data, it's hard to say exactly what your problem is, but you might also try apply.daily from xts:
apply.daily(myzoo, sum)
Here's a working example:
> x <- zoo(2:20, as.POSIXct("2003-02-01") + (2:20) * 7200)
> apply.daily(x, sum)
> 2003-02-01 22:00:00 2003-02-02 16:00:00
65 144
| |
doc_23530409
|
A: If the UUID has changed, you can't use svn relocate. The safest thing to do is to check out a fresh working copy, then copy your changes over to it and commit them. Otherwise, see these search results for some ideas about how to do it. Warning: it involves mucking with the contents of your .svn directory, which is not supported/recommended.
It would have been easier on everyone if the people moving your repository had kept the same UUID when they did it.
A: svn diff > QQQ.txt
then
patch -p0 < QQQ.txt
or
svn patch QQQ.txt
| |
doc_23530410
|
df <- data.frame (Year = c("2010", "2010", "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
Sale = c(100,200,50,500,400,200,400,145,100,456,345,321,100,200,250,400),
Group = c("A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D"))
df$Year <- as.integer(df$Year)
ggplot(df, aes(x = Year, y = Sale, fill = Group)) +
geom_area()
A: You need to use fct_reorder() from forcats to reorder the factor Group by Sale:
df %>%
mutate(Group = fct_reorder(Group, desc(Sale))) %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
To do it by a specific year, I did the following.
ls <- df %>% filter(Year == 2013) %>% arrange(desc(Sale)) %>% select(Group)
df$Group <- factor(df$Group, levels = ls$Group)
df %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
Which was a manual reorder.
| |
doc_23530411
|
I would like to restrict the maximum file size which can be uploaded, and although I can do a client-side validation on the file-size, a pure client-side solution is not very robust and I would like to add a server-side validation as well. Is it possible to do this using IAM roles for the "S3:PutObject" action?
A: You can set minimum and maximum file size in the s3Policy you create when setting up the signed upload URK for direct browser to S3 upload.
Here is an example (JavaScript from a node.js app) - see the 'content-length-range' part at the bottom:
var s3Policy = {
'expiration': expiration,
'conditions': [{
'bucket': aws.bucket
},
['starts-with', '$key', path],
{
'acl': readType
},
{
'success_action_status': '201'
},
['starts-with', '$Content-Type', request.type],
['content-length-range', 2048, 124857600], //min and max
]
};
If the user uploads a file that exceeds S3 returns a 400 bad request with a body including a message saying that the maximum file size limit has been exceeded.
A: You can limit the uploaded object size by using the content-length-range attribute in your upload form.
Here is the relevant doc page : http://doc.s3.amazonaws.com/proposals/post.html#Limiting_Uploaded_Content
| |
doc_23530412
| ||
doc_23530413
|
<input type="text" ng-model="selected" typeahead="item.state for item in states" typeahead-editable="false" />.
The control works in that it retrieves a list from the web service and when the user selects the state it populates the text input correctly and stores the state name in the $scope.selected variable. However what I want stored is the object {"abbrev":"FL", "state":"Florida"} because I want to save the key/value pair in a database. How can I get it to select an object vs just the value?
A: This can be done by actually storing your entire object into $scope.selected. It would look something like this:
<input type="text" ng-model="selected" typeahead="item for item in states" typeahead-editable="false" typeahead-input-formatter="item.state" typeahead-template-url="results.html" />.
The changes that need to be made are:
*
*return the whole item: typeahead="item for item in states"
*format the input to show the state: typeahead-input-formatter="item.state"
*add template: typeahead-template-url="results.html"
Then in your HTML you can define your autocomplete template to show the state name:
<script type="text/ng-template" id="results.html">
<a>{{match.model.state}}</a>
</script>
| |
doc_23530414
|
What it has done is prepended the local Servers work directory to the front of the Path it had me choose.
I feel this is a Bug or how am I suppose to get the most current copy of a script in TFS when the Build Definition runs.
A: Tried with a simple powershell script on my side, but couldn't reproduce your issue, the script is working.
Only add one step in build, and map to $/teamproject in Repositity, then select the script:
To narrow down the issue, you could create a new pipeline with only one task-Powershell, check what will happen.
If you still get error, please share detail logs with system.debug=true enable.
Also take a look at this tutorial about how to use powershell fetch/change build number, which may helps-- Use a PowerShell script to customize your build pipeline
Update
According to your error info, you are lacking of the definition.
Please make sure you have specified the value in options--build number format
$(BuildDefinitionName)_$(Year:yyyy).$(Month).$(DayOfMonth)$(Rev:.r)
Then it should run without any problem:
| |
doc_23530415
|
When my SyncAdapter finished syincing i post a message into the message bus:
EventBus.getDefault().post(new EventMessagesRefreshed());
In my target class i do the following:
@Subscribe
public void onEvent(EventMessagesRefreshed event) {
this.init();
}
And in my init() i create the adapter for the recyclerview and set it:
public void init() {
if(this.listRowParent != null) {
this.adapter = new FragmentMessagesListAdapter(this.getActivity(), SingletonMessages.getInstance().getMessages());
this.listRowParent.setAdapter(this.adapter);
}
}
// listRowParent is my RecyclerView!
The fragment which receives the event is inside a of a tab view. So there are multiple tabs and sometimes ofcourse the SyncAdapter posts the EventMessagesRefreshed into the message bus when im not in the correct target tab but since it is registered it tries to call init() and to create the adapter and set it to the RecyclerView. If that happens i get the following error:
Could not dispatch event: class EventMessagesRefreshed to subscribing class class FragmentMessagesList
java.lang.IllegalStateException: Observer android.support.v7.widget.RecyclerView$RecyclerViewDataObserver@2c3421a7 was not registered.
at android.database.Observable.unregisterObserver(Observable.java:69)
at android.support.v7.widget.RecyclerView$Adapter.unregisterAdapterDataObserver(RecyclerView.java:5688)
at android.support.v7.widget.RecyclerView.setAdapterInternal(RecyclerView.java:873)
at android.support.v7.widget.RecyclerView.setAdapter(RecyclerView.java:857)
So i need to init() my adapter and RecyclerView only when the RecyclerViewDataObserver is registered.
How can i do that?
A: You need to register Data observer to listen to data changes from sync adapter.
mRecyclerViewAdapter.registerAdapterDataObserver(myObserver);
RecyclerView.AdapterDataObserver are a result of which notify methods you call. So for instance if you call notifyItemInserted() after you add an item to your adapter then onItemRangeInserted() will get called
A more detailed example
protected void setupRecyclerView() {
mAdapter = new MyAdapter(mItemList);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
checkAdapterIsEmpty();
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
checkAdapterIsEmpty();
}`
The adapter may publish a variety of events describing specific
changes. Not all adapters may support all change types and some may
fall back to a generic "something changed" event if more specific data
is not available.
| |
doc_23530416
|
In my line containing -> var result = csvParser.ReadFromString(csvReaderOptions, ReadCsvFile().ToString()).ToList();
^^I have tried taking out the '.ToString' and then placing 'await' in front of 'ReadCsvFile()'. An error then pop up in debug saying there is a 'CsvFileMapping Error = ,'
public async Task<IActionResult> OnPostAsync()
{
try
{
CsvParserOptions csvParserOptions = new CsvParserOptions(true, ',');
CsvReaderOptions csvReaderOptions = new CsvReaderOptions(new[] {Environment.NewLine});
CsvFileMapping csvMapper = new CsvFileMapping();
CsvParser<CsvData> csvParser = new CsvParser<CsvData>(csvParserOptions, csvMapper);
var result = csvParser.ReadFromString(csvReaderOptions, ReadCsvFile().ToString()).ToList();
foreach (var i in result)
{
Console.WriteLine(i);
}
}
catch(Exception e)
{
Console.WriteLine("File could not be read");
Console.WriteLine(e.Message);
}
return RedirectToAction("Index", "CartsMvc");
}
[BindProperty]
public IFormFile UploadedFile{get; set;}
public async Task<string> ReadCsvFile()
{
string results;
using (StreamReader reader = new StreamReader(UploadedFile.OpenReadStream()))
{
results = await reader.ReadToEndAsync();
}
return results;
}
A: Thanks to @SimonWilson, we were able to correct the problem of getting the CSV data read into my OnPostAsync() method.
var csv = await ReadCsvFile();
var result = csvParser.ReadFromString(csvReaderOptions, csv).ToList();
These two lines replace the one line which was as follows
var result = csvParser.ReadFromString(csvReaderOptions, ReadCsvFile().ToString()).ToList();
| |
doc_23530417
|
class SomeViewModel
{
public SomeViewModel(SomeService service)
{
service.SetViewModel(this); // <- Move this call to Autofac
}
}
class SomeService
{
public void SetViewModel(object viewModel)
{
//...
}
}
Instead of manually calling service.SetViewModel in every ViewModel, I want to move this call to the IoC Container (Autofac). I've tried using OnActivated but there are no parameters available:
builder.Register<SomeViewModel>
.AsSelf()
.OnActivated(e =>
{
var service = e.Parameters
.OfType<SomeService>()
.FirstOrDefault(); // <- There are no parameters
service.SetViewModel(e.Instance);
});
Is it possible to move the call service.SetViewModel(this); in the SomeViewModel constructor into some kind of Autofac registration?
A: I agree with @Steven. But even if we set this apart, what if there are several view models sharing the same service? Which one will get in the service - "last wins"? You'd want to think through this design one more time.
Now that you've been warned... Your solution could be following:
...
builder.Register(s => CreateViewModel(s, svc => new SomeViewModel(svc))).AsSelf();
}
private T CreateViewModel<T>(IComponentContext ctx, Func<SomeService, T> createInstance) {
var svc = ctx.Resolve<SomeService>();
var instance = createInstance(svc);
svc.SetViewModel(instance);
return instance;
}
| |
doc_23530418
|
Sarah Smith 1234566 UK
Homer Simpson 3456677 USA
Max Power 4567932 Canada
Meg Griffin 5689321 USA
Sarah Smith 345677 USA
So I wanna exctract all data for one person be in a worksheet, so Sarah Smith has her own worksheet that shows her info, homer simpson has his own that shows his info..
I wrote this code, but when i run it starts each work but it adds a row on top of each worksheet!!! so for sarah smith work sheet it starts from row 2, for Homer Simpson starts from row 3. Max power starts from row 4?? Any idea why?? I want each sheet starts from row 1
Private Sub CommandButton1_Click()
Dim WorksheetsExists As Boolean, e
Application.ScreenUpdating = False
With Range("A1").CurrentRegion
With .Offset(1).Columns(1)
For Each e In Filter(.Parent.Evaluate("transpose(if(countif(offset(" & _
.Address & ",0,0,row(1:" & .Rows.Count & "))," & .Address & ")=1," & _
.Address & ",char(2)))"), Chr(2), False)
.Offset(-1).AutoFilter 1, e
Range("A1").CurrentRegion.Offset(0, 0).Resize(.Rows.Count, 25).SpecialCells(12).Copy
On Error Resume Next
WorksheetExists = (Sheets(e).Name <> "")
If WorksheetExists = False Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = e
Sheets(e).Range("A" & Sheets(e).Range("A" & Rows.Count).End(xlUp).Row).Offset(1).PasteSpecial
On Error GoTo 0
Else
Sheets(e).Range("A" & Sheets(e).Range("A" & Rows.Count).End(xlUp).Row).Offset(1).PasteSpecial
End If
Sheets(e).Columns.AutoFit
Next
End With
.AutoFilter
End With
Application.ScreenUpdating = False
End Sub
A: I tested this, with small modifications:
Sub sof20317616ExtractingDataFrom1Worksheet2Another()
Dim lRow As Long
Dim WorksheetExists As Boolean, e
Application.ScreenUpdating = False
With Range("A1").CurrentRegion
'MsgBox .Offset(1).Columns(1).Rows.Count
With .Offset(1).Columns(1)
For Each e In Filter(.Parent.Evaluate("transpose(if(countif(offset(" & _
.Address & ",0,0,row(1:" & .Rows.Count & "))," & .Address & ")=1," & _
.Address & ",char(2)))"), Chr(2), False)
.Offset(-1).AutoFilter 1, e
'MsgBox .Rows.Count
'Range("A1").CurrentRegion.Offset(0, 0).Resize(.Rows.Count, 25).SpecialCells(xlCellTypeVisible).Copy
.Offset(0, 0).Resize(.Rows.Count, 25).SpecialCells(xlCellTypeVisible).Copy
On Error Resume Next
WorksheetExists = (Sheets(e).Name <> "")
If WorksheetExists = False Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = e
On Error GoTo 0
End If
lRow = Sheets(e).Range("A" & Rows.Count).End(xlUp).Row
Sheets(e).Range("A" & lRow).Offset(0).PasteSpecial
Sheets(e).Columns.AutoFit
Next
End With
.AutoFilter
End With
Application.ScreenUpdating = True
End Sub
With the initial datasheet as this:
A: This isn't an answer to your question per se, but I think there's a flaw in your Boolean test for WorkSheetExists. Note that once it's set to True, i.e., the first time a worksheet whose name is the value of e, exists, it won't become False again. That's because the On Error Resume next statement skips over the error when the a worksheet of that name doesn't exist. It does not set your WorkSheetExists variable back to False. You need to do that explicitly in your code like:
On Error Resume Next
WorksheetExists = False
WorksheetExists = (Sheets(e).Name <> "")
If WorksheetExists = False Then ...
Better yet, create a separate WorkSheetExists function that you just pass the name to:
Function WorkSheetExists (WorkbookToTest as Workbook, WorksheetName as String) as Boolean
On Error Resume Next
WorksheetExists = WorkbookToTest.Sheets(WorksheetName).Name <> ""
End Function
| |
doc_23530419
|
Here is my GetApiToken class with the ApiToken function
class GetApiToken {
public func ApiToken(link: String, completionBlock: @escaping (String) -> Void) -> Void
{
let url = URL(string: link)!
let jsonDict = ["username": "snow", "password": "ssssssssss"]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
var request = URLRequest(url: url)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
//self.token = json["access_token"] as? String ?? "x"
completionBlock((json["access_token"] as? String)!)
} catch {
print("error:", error)
}
}
task.resume()
}
}
Here is where I am trying to get the value
func getData(_ link:String)
{
let url = URL(string: link)!
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20)
request.httpMethod = "GET"
var output = ""
GetApiToken().ApiToken(link: "http://localhost:5000/auth", completionBlock: { str in
output = str
})
request.addValue("JWT \(output)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type") ..........
A: It's an asynchronous call, so you need to put everything that will happen once the data has been retrieved in the completion callback
func getData(_ link:String)
{
let url = URL(string: link)!
var request = URLRequest(url: url,
cachePolicy: .reloadIgnoringCacheData,
timeoutInterval: 20)
request.httpMethod = "GET"
GetApiToken().ApiToken(link: "http://localhost:5000/auth",
completionBlock:
{ output in
request.addValue("JWT \(output)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
.......
})
| |
doc_23530420
|
function update_data(storedata)
{
obj.onclick=function() {remover(this,storedata); };
}
Not able to access storedata within the inner function.
When I try using alert(obj.onclick) the result comes out to be remover(this,storedata). It seems the variable is not been replaced by its value!!
Any Ideas?
A: It is "replaced". The problem is just the way you are trying to inspect it.
When you alert a function, you get a stringified version of the function β¦ and that includes the variable names and not serialisations of every variable.
If you were to actually call the function, the variable would be available with the value you gave it.
A: You need to attach it as a property of the object which has got the event handler anyhow. When you storedata is a string and you are using HTML5, you could for example accomplish it that way:
function update_data(storedata){
obj.dataStoredata = storedata;
obj.onclick = function(){
remover(this);
};
}
Inside of your remover function them you can simply access this.dataStoredata which will contain your data.
| |
doc_23530421
|
How can I keep the display awake as long as the video chat is active?
A: You can use the org.chromium.power plugin. To install it, run:
cordova plugin install org.chromium.power
When the video chat starts, use the requestKeepAwake API:
chrome.power.requestKeepAwake('display');
When the video chat ends, use the releaseKeepAwake API:
chrome.power.releaseKeepAwake();
| |
doc_23530422
|
export const actFetchMealsRequest = () => {
return (dispatch) => {
return callApi('/Product', 'GET', null).then(res => {
dispatch(GetAllMeal(res.data));
});
}
}
/*GET_ALL_MEAL*/
export function GetAllMeal(payload){
return{
type:'GET_ALL_MEAL',
payload
}
}
A: I've solved the problem it was in my callApi as @Shyam suggested,
this was my previous code:
import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
export default function callApi(endpoint, method = 'GET', body) {
return axios({
method,
url: `${API_URL}/${endpoint}`,
data: body
}).catch(err => {
console.log(err);
});
}
and this is the updated code:
import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
export default async function callApi(endpoint, method = 'GET', body) {
try {
return axios({
method,
url: `${API_URL}/${endpoint}`,
data: body
});
} catch (err) {
console.log(err);
}
}
I just converted to an async function.
| |
doc_23530423
|
function invokeGraphApi() {
// #4: Get an access token to the Microsoft Graph API
authContext.acquireToken(azurePorperties.endpoints.graphApiUri,
function (error, token) {
// TODO: Handle error obtaining access token
if (error || !token) {
displayAlert('danger', "User details not found, Kindly relogin");
return;
}
$.ajax({
type: "GET",
url: azurePorperties.endpoints.graphApiUri + "/v1.0/me",
headers: {
"Authorization": "Bearer " + token
},
success: function (result) {
console.log(result);
//disableWaitingPointer();
}, error: function (result) {
console.log("Error at GraphApi/V1.0/Me:" + result);
displayAlert('danger', 'Error occured at Graphapi/v1.0/me ');
}
});
}
);
}
A:
The application has access to the user's authentication context and wants to avoid the Azure AD account selection prompt when multiple accounts are signed in. This can be done a few different ways:
*
*Session Id or SID
You can pass the SID in the request parameters to the acquireTokenSilent call. This will allow Azure AD to bypass the account selection. SID , you can configure SID in optional claim
*Login hint
If you do not have SID claim configured or need to bypass the account selection prompt in interactive authentication calls, you can do so by providing a login_hint in the request parameters
You can follow below doc for further reference:
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-js-sso#automatically-select-account-on-azure-ad
Also , you can find the detailed samples in below repo:
https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki#sso-between-apps
Hope it helps.
| |
doc_23530424
|
func showSearchBar(searchBar: UISearchBar, navigationItem: UINavigationItem) {
searchBar.alpha = 0
navigationItem.titleView = searchBar
searchBar.showsCancelButton = true
navigationItem.setRightBarButtonItem(nil, animated: true)
for subView in searchBar.subviews {
for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
textField.attributedPlaceholder = NSAttributedString(string:NSLocalizedString("Search", comment:""),
attributes:[NSForegroundColorAttributeName: UIColor(red: 25/255, green: 128/255, blue: 214/255, alpha: 1)])
textField.font = UIFont(name:"AvenirNext-Medium", size: 15)
textField.textColor = UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
}
}
}
UIView.animateWithDuration(0.5, animations: {
searchBar.alpha = 1
}, completion: { finished in
searchBar.becomeFirstResponder()
})
}
func hideSearchBar(searchBar: UISearchBar, navigationItem: UINavigationItem, navigationController: UINavigationController, leftButton: UIBarButtonItem) {
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "showSearchBar:")
searchBar.alpha = 0
navigationController.navigationBar.topItem?.rightBarButtonItem = button
navigationItem.setLeftBarButtonItem(leftButton, animated: true)
searchBar.clipsToBounds = true
UIView.animateWithDuration(0.3, animations: {
navigationController.navigationBar.alpha = 1
}, completion: { finished in
})
}
I've error after func hideSearchBar called
I don't know but i think error because I call showSearchBar in hideSearchBar but on showSearchBar have 2 parameters but i not send it... how can I send 2 parameters on action
I have try
showSearchBar:
showSearchBar::
but it still error, what should i do?
or i have another error on my code?
A: To get the name right, you need to translate from a Swift method declaration to the Objective-C name of that method. This translation is simple and follows rules that are completely mechanical, but you will be entering the name as a literal string and it is all too easy to make a typing mistake, so be careful:
*
*The name starts with everything that precedes the left parenthesis in the method name.
*If the method takes no parameters, stop. Thatβs the end of the name.
*If the method takes any parameters, add a colon.
*If the method takes more than one parameter, add the external names of all parameters except the first parameter, with a colon after each external parameter name.
Observe that this means that if the method takes any parameters, its Objective-C name will end with a colon. Capitalization counts, and the name should contain no spaces or other punctuation except for the colons.
To illustrate, here are three Swift method declarations, with their Objective-C names given as a string in a comment:
func sayHello() -> String // "sayHello"
func say(s:String) // "say:"
func say(s:String, times n:Int) // "say:times:"
It is possible to crash even though your selector name corresponds correctly to a declared method. For example, hereβs a small test class that creates an NSTimer and tells it to call a certain method once per second:
class MyClass {
var timer : NSTimer? = nil
func startTimer() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1,
target: self, selector: "timerFired:",
userInfo: nil, repeats: true)
}
func timerFired(t:NSTimer) {
println("timer fired")
}
}
Thereβs nothing wrong with that class structurally; it compiles, and can be instantiated when the app runs. But when we call startTimer, we crash. The problem is not that timerFired doesnβt exist, or that "timerFired:" is not its name; the problem is that Cocoa canβt find timerFired. This, in turn, is because our class MyClass is a pure Swift class; therefore it lacks the Objective-C introspection and message-sending machinery that would permit Cocoa to see and call timerFired. Any one of the following solutions will solve the problem:
*
*Declare MyClass as a subclass of NSObject.
*Declare MyClass with the @objc attribute.
*Declare timerFired with the @obc attribute.
*Declare timerFired with the dynamic keyword. (But this would be overkill; you should reserve use of dynamic for situations where it is needed, namely where Objective-C needs the ability to alter the implementation of a class member.)
Here is Documentation.
In your case do this way:
"showSearchBar:navigationItem:"
UPDATE:
Remove General.swift from your project and replace your code in Home.swift with this code:
@IBAction func searchBarAction(sender: AnyObject) {
showSearchBar(self.searchBar, navItem: self.navigationItem)
}
func showSearchBar(searchBar: UISearchBar, navItem navigationItem: UINavigationItem) {
searchBar.alpha = 0
navigationItem.titleView = searchBar
searchBar.showsCancelButton = true
navigationItem.setRightBarButtonItem(nil, animated: true)
for subView in searchBar.subviews {
for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
textField.attributedPlaceholder = NSAttributedString(string:NSLocalizedString("Search", comment:""),
attributes:[NSForegroundColorAttributeName: UIColor(red: 25/255, green: 128/255, blue: 214/255, alpha: 1)])
textField.font = UIFont(name:"AvenirNext-Medium", size: 15)
textField.textColor = UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
}
}
}
UIView.animateWithDuration(0.5, animations: {
searchBar.alpha = 1
}, completion: { finished in
searchBar.becomeFirstResponder()
})
}
//MARK: UISearchBarDelegate
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
hideSearchBar(self.searchBar, navigationItem: self.navigationItem, navigationController: self.navigationController!, leftButton: btnMenu)
}
func hideSearchBar(searchBar: UISearchBar, navigationItem: UINavigationItem, navigationController: UINavigationController, leftButton: UIBarButtonItem) {
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchBarAction:") //add your button action here.
searchBar.alpha = 0
navigationItem.rightBarButtonItem = button
navigationItem.setLeftBarButtonItem(leftButton, animated: true)
searchBar.clipsToBounds = true
UIView.animateWithDuration(0.3, animations: {
navigationController.navigationBar.alpha = 1
}, completion: { finished in
})
}
| |
doc_23530425
|
Server Error in '/DatingGridView' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 52:
Line 53:
Line 54:
Line 55:
Line 56:
Source File: D:\VSProjects\DatingGridView\web.config Line: 54
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.
=== Pre-bind state information ===
LOG: User = PassionFruit-PC\PassionFruit!!!
LOG: DisplayName = System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
(Fully-specified)
LOG: Appbase = file:///D:/VSProjects/DatingGridView/
LOG: Initial PrivatePath = D:\VSProjects\DatingGridView\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\VSProjects\DatingGridView\web.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: Attempting download of new URL file:///C:/Users/PassionFruit!!!/AppData/Local/Temp/Temporary ASP.NET Files/datinggridview/5a514f00/39d65547/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///C:/Users/PassionFruit!!!/AppData/Local/Temp/Temporary ASP.NET Files/datinggridview/5a514f00/39d65547/System.Web.Extensions/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///D:/VSProjects/DatingGridView/bin/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///D:/VSProjects/DatingGridView/bin/System.Web.Extensions/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///C:/Users/PassionFruit!!!/AppData/Local/Temp/Temporary ASP.NET Files/datinggridview/5a514f00/39d65547/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///C:/Users/PassionFruit!!!/AppData/Local/Temp/Temporary ASP.NET Files/datinggridview/5a514f00/39d65547/System.Web.Extensions/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///D:/VSProjects/DatingGridView/bin/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///D:/VSProjects/DatingGridView/bin/System.Web.Extensions/System.Web.Extensions.EXE.
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
A: Your error clearly states:
Could not load file or assembly 'System.Web.Extensions'
Check that you are referencing this in your project and that your .NET framework is installed correctly.
A: System.Web.Extensions is required for MS Ajax and will appear in your D:\VSProjects\DatingGridView\web.config to enable the correct handlers for ASP.Net 2.0 (comes built in for 3.5). If you haven't installed the MS Ajax Extensions on the machine where you are running this site you'll have the kind of error you've posted.
| |
doc_23530426
|
A: I appreciate this tutorial, perhaps can help you:
http://nhforge.org/blogs/nhibernate/archive/2008/09/17/value-objects.aspx
The author explain the concept of value object, using them like components.
A: That helped me a lot maybe you should try.
A: Here is a 4-part blog posting about FluentNHibernate. Not sure exactly what you're looking for, but then you didn't say either. ;)
A: Fluent Nhibernate has a wiki, have you checked it out?.
A: http://www.dreamincode.net/forums/topic/161638-fluent-nhibernate-tutorial/
A: The wiki is your best bet. I've had a few Fluent NHibernate posts on my blog, but most of that content is mirrored on the wiki anyway.
A: This video tutorial added to youtube.com on 10/5/2011 got me up in running in about 30 minutes.
Fluent NHibernate Tutorial
Update: It's been a few months, but if you need advanced mapping and don't mind 3rd party tools, use DevArt's Entity Developer tool which creates all of your entities and mappings for up to 10 tables/entities for free. The source code for the entity mappings is readily available for you to learn from. If you look at it you can learn a lot. http://www.devart.com/entitydeveloper/
A: I like NHibernate 3.0 tutorial with Fluent Nhibernate and LINQ 2 NHibernate
A: The GitHub project page has got all the basic examples you need: https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started
| |
doc_23530427
|
Example:
class loadFile{
function loadObject($object){
//load object here
}
}
$loadmefiles = new loadFile();
//use $loadmefiles->loadObject() as autoloader
spl_autoload_register();
$goat = new Animal('goat');
Hopefully you understand what I am getting at.
A: This is done by passing an array to spl_autoload_register: the first element being the object, the second being the name of the method as a string:
spl_autoload_register(array($loadmefiles, 'loadObject'));
From the callable documentation:
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
A: You can make it static as an alternative.
spl_autoload_register(function($class)
{
Pi_loader::autoload($class);
});
If not...
spl_autoload_register(function($class)
{
$loader = new Pi_loader();
$loader->autoload($class);
});
| |
doc_23530428
|
name: CI
on:
push:
release:
types: [published]
jobs:
test:
runs-on: ubuntu-latest
steps:
# ...
deploy-staging:
runs-on: ubuntu-latest
needs: test
if: github.event_name == 'push' && github.ref == 'staging'
steps:
# ...
I went through the following steps:
*
*Make some commits on the develop branch, and push those changes.
*After build passes on GitHub Actions I did a fast forward merge from develop into staging.
I expected GitHub Actions to run both the test and deploy-staging jobs after item 2. But instead it just ran test again without running deploy-staging.
As you can see above even after pushing to staging it still ran it on the develop branch instead of the staging branch. I'm kinda assuming this might be due to some weird behavior with fast forward merges. But GitHub obviously recognized that I pushed to staging as it offered to create a PR from that branch into master.
So that makes me rethink my theory about why it's trying to run on develop instead of staging.
Why would this be happening? Is there anyway to fix this so merging into staging actually runs the workflow on staging as opposed to develop?
A: My approach would be so separate the triggers and related jobs into different workflows.
So, to mimic your example, instead of a ci.yml I would have two files:
*
*test.yml
*deploy-staging.yml
In .github/workflows/test.yml:
name: Test
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
# ...
In .github/workflows/release-staging.yml:
name: Release Staging
on:
push:
branches:
- staging
jobs:
deploy-staging:
runs-on: ubuntu-latest
steps:
# test steps ...
# release ...
Admittedly this is annoying because the release doesn't run on the same test run as the test, but you want to make sure the tests all pass before deploying.
If you wanted to chain the test run workflow to run the deploy workflow I might change release-staging to use the Check suite event instead of push.
A: ${{ github.ref }} will be refs/heads/staging not just staging.
The best thing to do in these situations is simply to echo the variable values you want to check in a step before it:
steps:
- name: Check inputs
run: |
echo github.ref is: ${{ github.ref }}
echo github.event_name is: ${{ github.event_name }}
| |
doc_23530429
|
The files have certain columns with DATE datatype (yyyy-mm-dd).
The pipeline runs fine but inserts NULL into all the Date type columns.
A: The DATE values may be getting written to Parquet as int64 with a timestamp logical type annotation (https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#timestamp). MemSQL doesn't currently automatically convert these to a format compatible with e.g. DATETIME or TIMESTAMP, but rather attempts to assign to the destination column as if by assigning an integer literal with the raw underlying value. This gives NULL rather than an error for MySQL compatibility reasons, though set global data_conversion_compatibility_level="7.0" will make it an error.
You can investigate by temporarily giving the problem column TEXT type and looking at the resulting value. If it's an integer string, the issue is as described above and you can use the SET clause of CREATE PIPELINE to transform the value to a compatible format via something like CREATE PIPELINE P AS LOAD DATA .... INTO TABLE T(@col_tmp <- parquet_field_name) SET col = timestampadd(microsecond, @col_tmp, from_unixtime(0));.
The value will be a count of some time unit since the the unix epoch in some time zone. The unit and time zone depends on the writer, but should become clear if you know which time it's supposed to represent. Once you know that, modify the expression above to correct for units and perhaps call convert_tz as necessary.
Yes, it's a pain. We'll be making it automatic.
| |
doc_23530430
|
So, this code right here works just fine, the pygame window is present, and you can close it by pressing X button:
#pygame initialization code and etc.
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#code for drawing stuff out
But let's say I want to make a function to just handle closing the window just for the sake of it:
#pygame initialization code and etc.
running = True
def handle_quit_event():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
else:
return True
while running:
running = handle_quit_event()
#code for drawing stuff out
Now it doesn't work the same way anymore, the pygame window appears for a blink moment, and then program finishes, leaving me with this unease feeling that my idea of abstracting stuff using functions is all wrong.
[EDIT]: So in my code the function checks for only the first event in the list, but it still doesn't explain why the program finishes right after running it, because even if it checks for the first event, it still should return true by running else clause. So what am I missing?
A: Abstracting functionality into functions is a great idea! Unfortunately your re-write has introduced a bug that might be causing your broken game. Without a stacktrace or error messages, it's hard to say exactly why the game is broken.
Onto the bug:
The function handle_quit_event doesn't iterate through all the events in pygame.event.get(). It returns True or False after checking the first event.
You probably wanted to write it more like:
def handle_quit_event():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
return True
A more pythonic approach that uses list-comprehension and any():
def handle_quit_event():
return not any([event.type == pygame.QUIT for event in pygame.event.get()])
Note the flipped logic with not is required because your function is currently returning True if there is not a QUIT event.
| |
doc_23530431
|
I wish to learn a Cox PH model on in-sample data and then use the parameters derived on out of sample data as follows:
# learn IS params
model.PH <- coxph(Surv(days.IS, outcome.IS) ~ predictor.IS)
# apply IS params to OOS data to make predictions
predictions.raw <- predict(model.PH, newdata = predictor.OS)
# binarise predictions
predictions.OS <- rep(0,length(predictions.raw))
predictions.OS[which(predictions.raw>0)]<- 1
# fit survival model
fittedModel <- survdiff(Surv(days.OS, outcome.OS) ~ predictions.OS)
predictor.IS is of dimensionality Y_1 x D, predictor.OS is of dimensionality Y_2 x D
However, this does not work as the number of elements in predictions.OS is Y_1 NOT Y_2.
What am I doing wrong?
A: This would probably work more cleanly if you passed values to ``coxph using a data=dfrm argument and then passed a newdata argument to predict as a different dataframe with the same column names. I get the sense you are passing matrices that may not have the same column names as a re found in the model. Dimensionality matching is not the only requirement for the predict.coxph function.
| |
doc_23530432
|
string sChar = "$$VIC123-456-789pppEEX";
I would like to parse the above examples of sChar to result in the following value
123-456-789
What this regex would do is find the first Number in the string as well as the next 10 characters. The next 10 characters can be special characters, alpha, or numberic.
A: Here the solution for you:
var sChar = "_$$$ASDF 123-456-789123123XXX";
//string sChar = "$$VIC123-456-789pppEEX";
var indexDigit = sChar.search(/[\d]/);
var str = sChar.substring(indexDigit, indexDigit+11);
alert(str);
I see an answer like this:
var str = sChar.match(/\d.{10}/);
alert(str)
That won't work:
Try the following:
var sChar = "_$$$ASDF 123-4$6-7";
var sChar2 = "$$VIC987-6$4-3";
var indexDigit = sChar.search(/[\d]/);
var str = sChar.substring(indexDigit, indexDigit+11);
alert(str);//returns "123-4$6-7"
var str2 = sChar2.match(/\d.{10}/);
alert(str2);//returns null
| |
doc_23530433
|
Here's my code:
PImage floorImage;
void setup() {
size(1200, 600, P3D);
smooth(8);
floorImage = loadImage("floor3.png");
}
void draw() {
background(0);
ambientLight(255,255,255);
camera(0.0,100.0,-300.0,mouseX-width/2.0,-(mouseY-height/2.0),0.0,0.0,-1.0,0.0);
for(int x=-20;x<20;x++)
{
for(int z=-20;z<20;z++)
{
pushMatrix();
translate(x*32.0,0.0,z*32.0);
beginShape();
textureMode(NORMAL);
texture(floorImage);
vertex(-32.0,0.0,-32.0,0.0,0.0);
vertex(32.0,0.0,-32.0,1.0,0.0);
vertex(32.0,0.0,32.0,1.0,1.0);
vertex(-32.0,0.0,32.0,0.0,1.0);
endShape(CLOSE);
popMatrix();
}
}
}
And here's the texture:
The end result, however, looks terrible!
Why?
A: Looks like you have quad size = 64, but you move it by 32 in x and z directions.I think you have intersections here. Try to replace to this:
translate(x*64.0,0.0,z*64.0);
| |
doc_23530434
|
The first two items (blue column and green column) are 50% width each and stretch to fill the screen.
See picture:
HTML:
<div id='container-row'>
<section class='container-column pic-bkg'>
<nav id='main-nav'>
<ul id='main-nav-list'>
<li>Home</li>
<li>Link</li>
<li>Link</li>
</ul>
</nav>
</section>
<section class='container-column solid-bkg'>
</section>
<section class='container-column contact-box'>
contact box
</section>
</div>
<!-- close id container-row -->
<!-- id container-row is for flexbox 2 column layout -->
This is my first time using Flexbox, I cannot figure out how to move just one flex item.
CSS:
body {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
height: 100%;
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
color: #fff;
}
#container-row {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
justify-content: center;
width: 100%;
}
.container-column {
width: 50%;
padding: 4em;
}
#main-nav-list {
display: inline-flex;;
flex-wrap: wrap;
flex-direction: row;
list-style: none;
}
#main-nav-list li {
margin-right: 1em;
}
.solid-bkg {
background-color: #0C3134;
}
.pic-bkg {
background-color: blue;
}
.container-column:nth-child(3){
background-color: grey;
height: 30px;
width: 30%;
}
Codepen here:
A: Please use '.container-column:nth-child(3)' classes content like below and you will get the result.
.container-column:nth-child(3) {
background-color: grey;
height: 30px;
width: 30%;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
}
| |
doc_23530435
|
main program
use my_module
call my_subroutine()
end program main
module my_module
contains
subroutine my_subroutine()
print *, "Hello World!"
end subroutine my_subroutine
end module my_module
When I try to compile this file I get:
Fatal Error: Can't open module file 'my_module.mod' for reading at (1): No such file or directory
A: Yes, Fortran does allow modules to be contained in the same file as the main program. However, modules must be written before the main program:
module my_module
contains
subroutine my_subroutine()
print *, "Hello World!"
end subroutine my_subroutine
end module my_module
program main
use my_module
call my_subroutine()
end program main
| |
doc_23530436
|
ServerDetails servers = ConfigurationManager.GetSection("serverDetails") as ServerDetails;
var server = from s in servers
where s.Name == serverName
select s;
I get the error:
Could not find an implementation of the query pattern for source type
'MyNamespace.ServerDetails'. 'Where' not found.
The ServerElement has two properties:
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("ip")]
public string IP
{
get { return (string)base["ip"]; }
set { base["ip"] = value; }
}
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
}
ServerDetails
public sealed class ServerDetails : ConfigurationSection
{
[ConfigurationProperty("ServerCollection")]
[ConfigurationCollection(typeof(ServerCollection), AddItemName = "add")]
public ServerCollection ServerCollection
{
get { return this["ServerCollection"] as ServerCollection; }
}
}
ServerCollection
public sealed class ServerCollection : ConfigurationElementCollection
{
public void Add(ServerElement ServerElement)
{
this.BaseAdd(ServerElement);
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
}
protected override ConfigurationElement CreateNewElement()
{
return new ServerElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ServerElement)element).Name;
}
}
Am I missing something? Do I need to add something in so that I can use Linq with a custom configuration element?
By the way, I have using System.Linq; defined as I'm using it else where within the same class.
A: Okay, given that it's all weakly typed, you'll need to either call Cast<> or OfType<> explicitly, or give an explicit type to the range variable. You'll also need to specify the ServerCollection property on your ServerDetails. For example:
ServerDetails servers = (ServerDetails) ConfigurationManager.GetSection("serverDetails");
var server = from ServerElement s in servers.ServerCollection
where s.Name == serverName
select s;
A: var server = ((ServerDetails) ConfigurationManager.GetSection("serverDetails")).
ServerCollection.Cast<ServerElement>().FirstOrDefault(x => x.Name == serverName);
A: Using Brian Gideon's simple example of yield return in his IEnumerable<T> implementation, I was able to enumerate over my ConfigurationElementCollection.
It would look something like this (using the original question):
public sealed class ServerCollection : ConfigurationElementCollection,
IEnumerable<ServerElement>
{
...
public new IEnumerator<ServerElement> GetEnumerator()
{
foreach (var key in this.BaseGetAllKeys())
{
yield return (ServerElement)BaseGet(key);
}
}
}
While I was NOT getting the error:
Could not find an implementation of the query pattern for source type 'MyNamespace.ServerDetails'. 'Where' not found
...I was not able to iterate over my ConfigurationElementCollection using LINQ, either. This solution fixed my problem so that I could use LINQ to iteration over my collection.
A: A very late answer, I would use this extension class to turn any ConfigurationElementCollection into an IEnumerable safely.
public static class ConfigurationElementCollectionExtension
{
public static IEnumerable<T> ToEnumerable<T>(this ConfigurationElementCollection collection)
{
foreach (var element in collection)
{
if (element is T)
yield return (T)element;
yield return default;
}
}
}
Example usage below
ConfigurationManager
.GetSection("serverDetails"))
.ServerCollection
.ToEnumerable<ServerElement>()
.FirstOrDefault(x => x.Name == serverName);
| |
doc_23530437
|
Thanks for any answers.
Bye
A: As it is this question is incredibly vague. Any more specifics you could add about what you are trying to accomplish would likely lead to a better answer.
I would think you can override onKeyDown or dispatchKeyEvent in your Activity and you'll get callbacks when a key on the keyboard is pressed. It will send you the action and keycode in a KeyEvent object.
A: textView1.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
{
if(keyCode == ?) //check it
{
//do some stuff
}
}
return false;
}
});
A: This method just fires when you're using the hardware keyboard, with the soft keyboard it didn't fire. Some suggestion are to use a TextWatcher.
| |
doc_23530438
|
<textarea readonly class="form-control prj-info"></textarea>
And my Jquery code:
$(".btn-get-prj-info").click(function () {
if ($('.edt-prj-code').val().length < 7) {
$("textarea.prj-info").html("ERROR");
}
else {
setTimeout(
function () {
$("textarea.prj-info").html("OK")
}, 1500);
}
})
But it has a weird problem! in the else condition when the Textarea's text changed, the page's content blinked!!
This problem is only in Google Chrome.
I have googled it, but I don't find anything.
A: As @mplungjan suggests it seems like you're not preventing the button's default action. In HTML, a submit button's action is to reload the page.
You need to pass the event as a parameter to the callback function attached to the button, and prevent it's default action.
A: Thank you guys.
Finally, the problem solved.
For who may have this question:
I used the character β in my code, it makes the page refresh on Chrome that I don't know really why!
$("textarea.prj-info").html("β title one");
| |
doc_23530439
|
server.R
library(shiny)
shinyServer(
function(input, output) {
output$species_table <- renderTable({ iris[iris$Species == input$species,] })
output$json <- RJSONIO::toJSON(iris[iris$Species == input$species,], byrow=T, colNames=T) # error line
}
)
ui.R
require(shiny)
specs = as.character(unique(iris$Species))
names(specs) = specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
tableOutput("species_table")
)
)
Which returns the server error:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside
a reactive expression or observer.)
.. because it's obviously the wrong approach. Without server.R's line output$json <- ... the outcome works and looks like this, so the rest of the code is ok. But I also want to get the json (or any alternative format) across somehow and trigger a subsequent javascript action to read it in as an array object. Grateful for any pointers, and apologies in advance if my description is unclear.
A: For benefit of others this is the working formula. If anyone can suggest a more elegant solution I'd be grateful. Open the browser's javascript console log to see object 'data' being updated..
server.R
library(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))
shinyServer(
function(input, output) {
output$json <- reactive({
paste('<script>data=',
RJSONIO::toJSON(iris[iris$species == input$species,], byrow=T, colNames=T),
';console.log(data[0]);', # print 1 data line to console
'</script>')
})
}
)
ui.R
require(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))
specs <- as.character(unique(iris$species))
names(specs) <- specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
htmlOutput("json")
)
)
A: So, that error generally means that you need to wrap reactive({}) around something, in this case your toJSON command. This works, and displays the JSON data.
ui.r
require(shiny)
specs = as.character(unique(iris$Species))
names(specs) = specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
#tableOutput("species_table")
textOutput("json")
)
)
server.r
library(shiny)
shinyServer(
function(input, output) {
output$species_table <- renderTable({ iris[iris$Species == input$species,] })
output$json <-reactive({ RJSONIO::toJSON(iris[iris$Species == input$species,],
byrow=T, colNames=T) })# error line
}
)
| |
doc_23530440
|
library(TeachingDemos)
txtStart("command_split_1000/dir_1.txt")
files <- list.files(path="data/split_1000/dir_1", pattern="x*", full.names=TRUE)
total.coefs <- data.frame()
for (x in files) {
message('Running: ', x)
output <- tryCatch({
ulfasQTL::findSqtl(x, geneObjectName = "gene_after_preprocess", snpFileCate = 1)
}, print(x), error=function(e) {
cat("ERROR :", conditionMessage(e), "\n")
})
total.coefs <- rbind(total.coefs, output)
write.table(total.coefs, file = 'output_split_1000/dir_1', sep='\t')
}
txtStop()
A: Consider nesting a list.files loop inside a list.dirs loop. Also, avoid using rbind inside a loop as it leads to excessive copying in memory (see Patrick Burns' R Interno: Circle 2 - Growing Objects). Instead use lapply to build a list of data frames for a rbind outside of looping.
# RETRIEVE ALL NEEDED DIRECORIES
dirs <- list.dirs(path="data/split_1000")
for (d in dirs) {
txtStart(paste0("command_split_1000/", basename(d), ".txt"))
# RETRIEVE ALL FILES IN CURRENT DIRECTORY
message('Directory: ', d)
files <- list.files(path=d, pattern="x*", full.names=TRUE)
# LIST OF DATA FRAMES
df_list <- lapply(files, function(x) {
message('--Running: ', x)
output <- tryCatch({
ulfasQTL::findSqtl(x, geneObjectName = "gene_after_preprocess", snpFileCate = 1)
}, print(x), error=function(e) {
cat("ERROR :", conditionMessage(e), "\n")
})
})
# ROW BIND ALL NON-NULL DF ELEMENTS
df_list <- Filter(NROW, df_list)
total.coefs <- do.call(rbind, df_list)
# SAVE OUTPUT WITH BASE NAME OF CURRENT DIRECTORY
out_path <- paste0('output_split_1000/', basename(d), '.txt')
write.table(total.coefs, file = out_path, sep='\t')
txtStop()
# RELEASE RESOURCES
rm(df_list, files, total.coefs)
gc()
}
| |
doc_23530441
|
The trouble is that the column must exist to be referenced. However through the UI there doesn't appear to be any way to hide the column. You can set its width to 0 and the border around it has a de-emphasized look. Though it holds some width. And then if you need to add columns (because stupidly you deleted them when trying to fix this problem!), the "there is not enough space" error occurs.
Is there a best way to make zero width columns in AEM tables?
A: After writing this question I went back to it and tried again and worked out a solution. And I'm happy to know if there is some better solution.
*
*Firstly don't delete columns
*Right-click on the table in the Data View and Generate Fields (or just drag it to the page). This will have every column.
*This next step is slow and tedious and this is where an answer with a more efficient method would be nice. However it works to provide the desired outcome.
*
*One by one click on each column's arrow and choose select column
*Window (menu) > Object > Cell (tab) > Presence = Invisible
*Window (menu) > Layout > Width = 0.0001mm and press return
I haven't experimented with different values to 0.0001mm except that 0 does not have the same effect.
Now each column is hidden. It can be restored by working with it from the Hierarchy pane.
| |
doc_23530442
|
It's still pretty basic but I've managed to send and receive messages with a user Loged In with Spark and another at the emulator.
After some SO reading I decided to create a service for my XMPP connection that I bind to every Activity. I currently have three activities
*
*MainActivity ( user logIn and connection to XMPPconnection).
*RosterActivity ( a listview containing the users contacts )
*ChatActivity
My question is twofold :
*
*Is it necessary to bind every activity to the Service, or would it be possible to just bind MainActivity to it and pass the XMPPConnection as an extra ? If so, how can the passing be done?
*After I log in and start the RosterActivity, I bind the service in the onCreate() method. In the onStart method, if I check the mBound variable, it's always false. I've tried SystemClock.sleep() just to see if it would work and it didn't. What really puzzles me is that when I first wrote this Activity, I used a button that, when clicked, would start the procedure to populate the list. That worked perfectly.
So what is it that I am missing? I obviously don't want the user to have to press a button just to see the contacts, I want the list to be populated at onStart(). Why is the Service bound when I try to reach it from inside the onClickListener and why does it simply not work at onStart.
I'm guessing it has everything to do with the binding being asynchronous, but I'm trying to find out exactly what.
MainActivity :
package com.example.smack_text;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
XMPPService mService;
boolean mBound = false;
Button logBtn;
Button disBtn;
EditText userTxt;
EditText passTxt;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// BIND SERVICE
Intent intent = new Intent(getApplicationContext(), XMPPService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStart()
{
super.onStart();
userTxt = (EditText) findViewById(R.id.userTxt);
passTxt = (EditText) findViewById(R.id.passTxt);
logBtn = (Button) findViewById(R.id.logBtn);
disBtn = (Button) findViewById(R.id.disBtn);
logBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final String user = new String(userTxt.getText().toString());
final String pass = new String(passTxt.getText().toString());
if(user=="" || pass=="")
{
Toast.makeText(getApplicationContext(), "Enter name and pass",
Toast.LENGTH_LONG).show();
}
if(mBound)
{
mService.connect(user,pass);
Log.d("Alex","connected");
}
else
{
Log.d("Alex","error in connecting");
}
Intent roster = new Intent();
roster.setClass(getApplicationContext(), RosterActivity.class);
startActivity(roster);
}
});
disBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(mBound)
{
mService.disconnect();
Log.d("Alex","disconnected");
}
else
{
Log.d("Alex","error in disconnecting");
}
}
});
}
@Override
protected void onDestroy()
{
// Unbind from the service
if (mBound)
{
unbindService(mConnection);
mBound = false;
}
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
mService = ((XMPPService.LocalBinder)service).getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name)
{
mBound = false;
}
};
}
RosterActivity :
package com.example.smack_text;
import java.util.Collection;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Presence;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class RosterActivity extends ListActivity{
boolean mBound = false;
XMPPService mService;
Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.roster);
Intent intent = new Intent(getApplicationContext(), XMPPService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onStart(){
super.onStart();
// btn = (Button) findViewById(R.id.button1);
// btn.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
if(mBound){
Log.d("Alex","roster connected");
Roster roster = mService.connection.getRoster();
// XWRIS TO RELOAD DN DOULEYEI
roster.reload();
Integer length = roster.getEntryCount();
String[] users = new String[length];
String[] userPresence = new String[length];
Integer i=0;
Collection<RosterEntry> entries = roster.getEntries();
for(RosterEntry entry:entries){
users[i] = entry.getName();
Presence tmpPres = roster.getPresence(entry.getUser());
userPresence[i] = tmpPres.toString();
Log.d("RosterActivity" , entry.getUser().toString());
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (RosterActivity.this,
android.R.layout.simple_expandable_list_item_1, users);
setListAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "service not bound yet", Toast.LENGTH_LONG).show();
}
}
// });
// }
@Override
protected void onDestroy() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onDestroy();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Creating the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Object o = l.getItemAtPosition(position);
String str = o.toString();
Log.d("Roster Activity",str);
builder.setTitle("Start Chat?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent chat = new Intent();
chat.setClass(getApplicationContext(), ChatActivity.class);
startActivity(chat);
}
});
AlertDialog alert = builder.create();
alert.show();
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ((XMPPService.LocalBinder)service).getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
XMPPService:
package com.example.smack_text;
import java.io.File;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class XMPPService extends Service{
XMPPConnection connection;
private final IBinder mBinder = new LocalBinder();
@Override
public void onCreate(){
super.onCreate();
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
XMPPService getService() {
return XMPPService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void connect(final String user, final String pass) {
Log.d("Xmpp Alex","in service");
ConnectionConfiguration config = new ConnectionConfiguration("10.0.2.2",5222);
// KEYSTORE SETTINGS
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setTruststoreType("AndroidCAStore");
config.setTruststorePassword(null);
config.setTruststorePath(null);
} else {
config.setTruststoreType("BKS");
String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null)
path = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
config.setTruststorePath(path);
}
// Create XMPP Connection
connection = new XMPPConnection(config);
// THELEI TO RUNNABLE ALLIWS DN TREXEI
new Thread(new Runnable() {
@Override
public void run() {
try {
connection.connect();
connection.login(user, pass);
if(connection.isConnected()){
Log.d("Alex", "connected biatch!");
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
else{
Log.d("Alex","not connected");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
public void disconnect(){
if(connection.isConnected()){
connection.disconnect();
}
else{Toast.makeText(getApplicationContext(), "not connected",Toast.LENGTH_LONG).show();
}
}
}
And the layouts:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context=".MainActivity" >
<EditText
android:id="@+id/userTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="30dp"
android:layout_marginTop="27dp"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/userTxt"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="52dp"
android:background="#FFFFFF"
android:text="User Name :" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/userTxt"
android:layout_marginTop="62dp"
android:background="#FFFFFF"
android:text="Password :" />
<EditText
android:id="@+id/passTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/userTxt"
android:layout_below="@+id/textView2"
android:layout_marginTop="58dp"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/logBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/passTxt"
android:layout_marginTop="66dp"
android:background="#FFFFFF"
android:text="Log In" />
<Button
android:id="@+id/disBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/logBtn"
android:layout_alignRight="@+id/userTxt"
android:background="#FFFFFF"
android:text="disconnect" />
</RelativeLayout>
roster.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
A: I always think things like this can be a bit confusing, so I wrote support for making this simpler in to Vapor API - an Android framework designed to make app dev easier.
It manages all the bindings for you implicitly, and also allows you to retrieve a binding purely by the class of the Service (you needn't maintain the connection object in your code, it's done for you).
If you wanted to try it out you could do what you want like this (using VaporActivity and VaporServiceBindable):
public class RosterActivity extends VaporActivity{
public void create(VaporBundle bundle){
$.srv(XMPPService.class); // optionally, first start the service
// set up the callback for when the service is bound
$.hook(SERVICE_BIND).hookIn(new $$hookee(){
public void call(String hookName, VaporBundle args){
// put your code here that depends on the binding...
}
});
// bind to the service
$.bind(XMPPService.class);
}
}
That's obviously a simplified skeleton of the kind of problem you describe, based on the fact binding is asynchronous.
What's more, if you want to then use a method from your Service inside your Activity you can do that easily from anywhere:
this.service(XMPPService.class).foo(); // some method in the service
Under-the-hood this retrieves the earlier ServiceConnection that was automatically created for you, and provides you access to the IBinder for the service.
You should check out VaporService too if you're interested. It runs the Service inside it's own thread that you can arbitrarily pause, sleep, and restart, giving you total control over your service without worrying about the gory details.
Hope that helps.
| |
doc_23530443
|
Can't open /usr/local/share/GeoIP/GeoLite2-Country.mmdb.gz
The GeoIP directory exists in that location, and it already had some .dat files from other things I was trying with the GeoIP Python library, but the .mmdb.gz file is not present before or after running the command. Here's the configuration file I have in /usr/local/etc
# Please see http://dev.maxmind.com/geoip/geoipupdate/ for instructions
# on setting up geoipupdate, including information on how to download a
# pre-filled GeoIP.conf file.
# Enter your user ID and license key below. These are available from
# https://www.maxmind.com/en/my_license_key. If you are only using free
# GeoLite databases, you make leave the 0 values.
UserId 999999
LicenseKey 000000000000
# Enter the product IDs of the databases you would like to update.
# Multiple product IDs are separated by spaces.
ProductIds GeoLite2-Country GeoLite2-City GeoLite-Legacy-IPv6-City GeoLite-Legacy-IPv6-Country 506 517 533
# The following are for the GeoLite Legacy databases. To update them,
# uncomment.
# ProductIds 506 517 533 GeoLite-Legacy-IPv6-Country GeoLite-Legacy-IPv6-City
# The remaining settings are OPTIONAL.
# The directory to store the database files. Defaults to /usr/local/share/GeoIP
# DatabaseDirectory /usr/local/share/GeoIP
# The server to use. Defaults to "updates.maxmind.com".
# Host updates.maxmind.com
# The desired protocol either "https" (default) or "http".
# Protocol https
# The proxy host name or IP address. You may optionally specify a
# port number, e.g., 127.0.0.1:8888. If no port number is specified, 1080
# will be used.
# Proxy 127.0.0.1:8888
# The user name and password to use with your proxy server.
# ProxyUserPassword username:password
# Whether to skip host name verification on HTTPS connections.
# Defaults to "0".
# SkipHostnameVerification 0
# Whether to skip peer verification on HTTPS connections.
# Defaults to "0".
# SkipPeerVerification 0
Is it possible I missed a step when installing geoipupdate? How can I get the command to check for and download an updated database?
A: You should run the command in verbose mode:
geoipupdate -v
This way you'll understand why the file isn't updated (most probably a faulty DatabaseDirectory, or perhaps a wrong ProductIDs or EditionIDs which will prevent other downloads to complete).
| |
doc_23530444
|
This is how the date variable looks like
1.383160e+10
Is there a way to convert this format to datetime using Python?
I've tried various ways of using the datetime module and time module. But what I get is a date from the year 2408
# Here I'm using the float from the first row in the dataframe
time.gmtime(13831603200)
The results
time.struct_time(tm_year=2408, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=113, tm_isdst=0)
When I use the datetime module:
python_date = datetime.fromtimestamp(13831603200).strftime('%d-%b-%Y, %H:%M:%S')
print(python_date)
22-Apr-2408, 00:00:00
[How the datetime variable (Vdatesub) is showing when using Python][1]
[1]: https://i.stack.imgur.com/I7yza.png
A: This is answered under these two posts (one Python, one R):
Convert 'seconds since October 14, 1582' to Python datetime
Read SPSS file into R, the data format for date is wrong, and generate more variable
In short: the date is stored as number of seconds from 14 Oct 1582, while Python starts at the Epoch date (01 Jan 1970).
You would need to calculate the number of seconds between 1582-10-14 and 1970-01-01 to adjust the timestamp value as per this post:
Timestamp out of range for platform localtime()/gmtime() function
(Possibly 12,218,515,200 seconds)
| |
doc_23530445
|
Microsoft.Office.Interop.Word.Application objword = new Microsoft.Office.Interop.Word.Application();
objword.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;
Microsoft.Office.Interop.Word.Document objDoc = objword.Documents.Add();
Microsoft.Office.Interop.Word.Paragraph para1;
para1 = objDoc.Paragraphs.Add();
String text = "";
for (int r = 0; r < dgvlib.RowCount; r++)
{
text = text + dgvlib.Rows[r].Cells[1].Value.ToString();
if (dgvlib.Rows[r].Cells[11].Value.ToString()!="")
text = text + " Comments:" + dgvlib.Rows[r].Cells[11].Value.ToString() + " ";
if (dgvlib.Rows[r].Cells[10].Value.ToString() != "")
text = text + " ( Bold Text:" + dgvlib.Rows[r].Cells[10].Value.ToString() + ")";
text = text + "\n";
}
para1.Range.Font.Size = 9;
para1.Range.Font.Name = "Arial";
para1.Range.Text = text;
para1.Range.Paragraphs.Add();
objDoc.SaveAs2(fNameExportWord);
objword.Visible = true;
I want to bold only this text dgvlib.Rows[r].Cells[10].Value.ToString() (second if condition). If I use different ranges or para then it creates new paragraphs.
In fact datagrid view dgblib rows are being written line by line so in each new line the value to be bold is dynamic. Sample to be written is below (if rows are 3).
this is row to be written to the word. Comments: these are comments. (Bold Text: 456)
this is row2 to be written to the word. Comments: these are comments. (Bold Text: 789)
this is row3 to be written to the word. Comments: these are comments. (Bold Text: 123)
A: As always, there's more than one way to solve a problem with text insertion and formatting. One way would be to store or mark the values that need to be formatted differently and, after inserting them, use Find to locate them and apply that formatting.
Another way, that the sample code below demonstrates, is basically what the code in the question is trying to do: format as the text is inserted. This does not allow inserting the entire text as a string, however. The text needs to be broken down: each section requiring different formatting needs to be inserted individually.
In order to do this, it's necessary to work with Range objects. The sample code uses two Range objects: one for the entire new content and one for inserting the sections of text. When appending new content to a Range, as long as nothing needs to be done to it, the InsertAfter method can be used.
As soon as the new content needs to be manipulated in some way it's necessary to first "collapse" the Range to a "point", then append the new content. At this point, the Rangecontains only the new content so any formatting applied affects only the new content.
In the sample code I've tried to stay as close to the original as possible in order to make it easier to follow and understand in relation to the original - so it's not optimized...
Microsoft.Office.Interop.Word.Application objword = new Microsoft.Office.Interop.Word.Application();
objword.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;
Microsoft.Office.Interop.Word.Document objDoc = objword.Documents.Add();
Microsoft.Office.Interop.Word.Range rngFull = objDoc.Content;
Microsoft.Office.Interop.Word.Range rngTarget = rngFull.Duplicate;
rngTarget.InsertAfter("\n");
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
rngTarget.Collapse(ref oCollapseEnd);
String text = "";
for (int r = 0; r < dgvlib.RowCount; r++)
{
text = text + dgvlib.Rows[r].Cells[1].Value.ToString();
if (dgvlib.Rows[r].Cells[11].Value.ToString()!="")
{
text = text + " Comments:" + dgvlib.Rows[r].Cells[11].Value.ToString() + " ";
rngTarget.InsertAfter(text);
text = "";
rngTarget.Collapse(ref oCollapseEnd);
}
else if (dgvlib.Rows[r].Cells[10].Value.ToString() != "")
{
text = text + " ( Bold Text:";
rngTarget.InsertAfter(text);
text = "";
rngTarget.Collapse(ref oCollapseEnd);
rngTarget.Text = dgvlib.Rows[r].Cells[10].Value.ToString();
rngTarget.Font.Bold = -1;
rngTarget.Collapse(ref oCollapseEnd);
rngTarget.InsertAfter(")");
rngTarget.Font.Bold = 0;
}
text = text + "\n";
}
rngFull.Font.Size = 9;
rngFull.Font.Name = "Arial";
//para1.Range.Text = text;
//rngFull.Paragraphs.Add();
objDoc.SaveAs2(fNameExportWord);
objword.Visible = true;
| |
doc_23530446
|
<SelectLocation city={cityValue} />
I use 2 JSON files. This is city1.json
[{"value":"city1","towns":[{"value":"town1_1"},{"value":"town1_2"}]}]
and city2.json
[{"value":"city2","towns":[{"value":"town2_1"},{"value":"town2_2"}]}]
'cityValue' is a string and is the index to determine the value of the array of JSON's files used in the child. The child 'SelectLocation.js' is the following
import React, {useState, useEffect} from 'react'
import Select from 'react-select'
import City1 from './city1.json'
import City2 from './city2.json'
export default function SelectLocation(props) {
const allData ={City1,City2}
const [val, setVal] = useState('')
const [town,setTown] = useState([])
useEffect(() => {
var cityChoose = props.city // Example: if props.city = "City1"
console.log(cityChoose) // "City1"
var newData = allData[cityChoose]
console.log(newData) // 0:{"value":"city1","towns":[{"value":"town1_1"},{"value":"town1_2"}]}
setTown(newData[0].towns) //error "can't read 'towns' from undefined "
}, [])
return (
<div className='row'>
...code to use the array "town"
</div>
)
}
I don't know the reason of the error, because if I made this
...
var cityChoose = "City1"
var newData = allData[cityChoose]
console.log(newData) // 0:{"value":"city1","towns":[{"value":"town1_1"},{"value":"town1_2"}]}
setTown(newData[0].towns) // Town=[{"value":"town1_1"},{"value":"town1_2"}]
...
What is wrong?
| |
doc_23530447
|
For example, When I run the stored procedure in sql server management studio:
CALL x_prodcedure 1,2
It outputs (not a rowset): Invalid ID/data
When I make the same call in php, no rowset data is found and errorinfo returns:
Array
(
[0] => 00000
[1] => 0
[2] => (null) [0] (severity 0) [(null)]
[3] => 0
[4] => 0
)
Not sure which other functions I can use to get the "Invalid ID/data" message
A: Actually PDO ERROR 000 is the value of the error when a query executed successfully.
You should only print when it fails, otherwise you should ignore.
In your case something along the lines:
if(!$stmt->execute(array(...))){
var_dump($dbh->errorInfo()); //not outside of the failure block
}else{
var_dump($stmt->fetchAll());
}
Most likely not a rowset is not considered as an error for PDO
A: So far the best way I found to capture MS SQL Server messages in PHP was using the sybase extension built with ct library, freetds and using the sybase_set_message_handler() function. Example code:
<?
$con = sybase_connect("server", "sa", "password");
sybase_set_message_handler("dbMsg", $con);
sybase_min_client_severity(0); // In case you want all messages
sybase_min_server_severity(0); // In case you want all messages
$rs = sybase_query("PRINT 'OK'; WAITFOR DELAY '00:00:05'; PRINT 'OK1';");
$rs = sybase_query("USE SOMEDB; PRINT 'OK'; SE LECT 1"); // Intentionally with error
function dbMsg($number, $severity, $state, $line, $text) {
echo microtime(1) . " [{$number}] [{$severity}] [{$state}] [{$line}] [{$text}]\n";
}
?>
Example build on a Debian Jessie:
cd /usr/src
apt-get source php5
cd [php source folder]/ext/sybase_ct
phpize
./configure --with-sybase-ct=/usr
make
make install
Note that this build procedure is not compatible with the mssql extension as the mssql one aliases the sybase functions.
| |
doc_23530448
|
/Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require': /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/html5-0.10.0/lib/html5/inputstream.rb:305: too short escaped multibyte character: /^ (SyntaxError)
( [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)/x
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/html5-0.10.0/lib/html5/tokenizer.rb:2:in `<top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/html5-0.10.0/lib/html5/html5parser.rb:2:in `<top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/html5-0.10.0/lib/html5.rb:1:in `<top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/xss_terminate-0.2/lib/xss_terminate.rb:2:in `<top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:72:in `block (2 levels) in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `each'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:70:in `block in require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in `each'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler/runtime.rb:59:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.5/lib/bundler.rb:132:in `require'
from /Users/jday/git/forks/shoptap-server/config/application.rb:8:in `<top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/railties-3.2.13/lib/rails/commands.rb:53:in `require'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/railties-3.2.13/lib/rails/commands.rb:53:in `block in <top (required)>'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/railties-3.2.13/lib/rails/commands.rb:50:in `tap'
from /Users/jday/.rvm/gems/ruby-2.0.0-p0@rails3.2/gems/railties-3.2.13/lib/rails/commands.rb:50:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
A: All right, turns out if I'd actually read the error message I would've realized this is a syntax error in the html5 gem, which is a dependency of xss_terminate. Replacing xss_terminate with loofah-activerecord (see xss_foliate) fixed the issue.
| |
doc_23530449
|
However, I would like to log some messages from those classes. So I have tried to use slf4j-api with the android binding. With the intention to provide the simple binding on my tests.
But the "test" module start with complaining that there are two slf4j binding in the classpath and that he is using the android-binding.
So my question is, How can I exclude the slf4j-android dependency from the "test" module ?
Here is the build.gradle of my "test" module
evaluationDependsOn(":app")
apply plugin: 'java'
dependencies {
def app = project(':app')
testCompile project(path: ':app', configuration: 'debugCompile')
def debugVariant = app.android.applicationVariants.find({it.name == 'debug'})
testCompile debugVariant.javaCompile.classpath
testCompile debugVariant.javaCompile.outputs.files
testCompile files(app.plugins.findPlugin("com.android.application").getBootClasspath())
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock-api-mockito:1.6.1'
testCompile 'org.assertj:assertj-core:1.7.1'
}
[1] http://blog.blundell-apps.com/how-to-run-robolectric-junit-tests-in-android-studio/
A: Use the "exclude" attribute to remove dependent libraries. Something like the following:
testCompile 'junit:junit:4.12' {
exclude 'slf4j-android'
}
I'm not sure which library you need to exclude it from. To find out, use gradle to list the library dependencies.
gradle dependencies
| |
doc_23530450
|
Some facts:
*
*The balls are SKSpriteNode's.
*Each ball is a parent node that has a child node (an overlay with the opposite rotation of the ball to provide the illusion of lighting/shadow). So, we're talking about 2 nodes for each ball.
*The balls' textures are preloaded up front and stored in memory via textureNamed(_:).
*I have set view.ignoresSiblingOrder = true.
*There is no SpriteKit background image that would make the balls render on top of another node; the background is transparent. So, the balls do not overlap other content.
*zPosition is not set -- not on the parent and not on the child.
Based on what I've learned about how the scene is rendered, I would expect to see all the parent nodes rendered in a single pass, with additional passes for the child nodes (though, even that is suspicious since I have ignoresSiblingOrder set to true).
What am I not understanding, here? Why does my draw count increase so drastically as more balls are added to the scene?
Thank you!
UPDATE:
If I don't add the child nodes to the balls, the draw count for the balls is 1 regardless of how many balls there are. So, it's definitely an issue with the child nodes, not the parents.
A: I solved the problem by setting zPosition to the same value on both the parent and child.
parentNode.zPosition = 1.0
childNode.zPosition = 1.0
There are now a total of 2 draws for the balls regardless of how many balls there are.
| |
doc_23530451
|
I am able to see the extra ListViewItems in Snoop(having Visibility as Collapsed), ListView too shifts the items upwards but it doesn't adjusts its height to remove the empty space!
I can surely say that this is happening due to VirtualizedStackPanel as changing the ItemsPanel to StackPanel solves the issue. Here is the relevant ListView XAML:
<ListView
x:Class="Wizards.FieldBinderModelListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Margin="0"
VerticalAlignment="Top"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Top"
Background="White"
BorderThickness="0"
Grid.IsSharedSizeScope="True"
KeyboardNavigation.DirectionalNavigation="Continue"
Padding="1"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
SelectionChanged="ListViewSelectionChanged"
SelectionMode="Single">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<!--Works fine with StackPanel but not with VirtualizingStackPanel
Explicitly added this PanelTemplate to show that it works with
StackPanel;ListView uses VirtualizingStackPanel as default panel
and causes same problem-->
<!--<StackPanel Orientation="Vertical" VerticalAlignment="Top"/>-->
<VirtualizingStackPanel Orientation="Vertical"
VerticalAlignment="Top"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Black" />
</Trigger>
<DataTrigger Binding="{Binding Status}"
Value="{x:Static local:Status.NotExisting}">
<!--Hide the fields which are in NotExisting state;
Need a trigger here as Status can be different -->
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type View:FieldViewModel}">
<local:FieldEditor
Margin="0,2,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Top"
Padding="0">
<!--<local:FieldEditor.Style>
<Style TargetType="{x:Type local:FieldEditor}">
<Style.Triggers>
<DataTrigger
Binding="{Binding Status}"
Value="{x:Static local:Status.NotExisting}">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</local:FieldEditor.Style>-->
</local:FieldEditor>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Is this a bug in VirtualizingStackPanel? Anyone else faced a similar issue? Any workarounds?
Update:
Reported this bug to MS on connect - https://connect.microsoft.com/VisualStudio/feedback/details/734113/virtualizingstackpanel-not-handling-collapsed-items-correctly
A: I managed to reproduce your problem. It certainly looks like a bug in VirtualizingStackPanel.
A work around is to set the height of the hidden items to zero instead of collapsing them:
<DataTrigger Binding="{Binding Status}" Value="False">
<Setter Property="Height" Value="0" />
<Setter Property="IsEnabled" Value="False"/>
<!--<Setter Property="Visibility" Value="Collapsed" />-->
</DataTrigger>
A: For anyone else looking for a way to continue relying on Visibility but also remove the extra spacing, I fixed it by removing the Padding in the style for the ListBoxItem:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>
It seems the ListBoxItem's default Padding is 3.
| |
doc_23530452
|
@Component
@Order(1)
public class CarsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("X", "XX");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
Did I forget to do smth?
A: The problem was in the absent of pom dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Instead the Filter was loaded from some java library and therefor compilation was successful (can be removed in module settings)
| |
doc_23530453
|
DateTimeZone timeZone = <Code that gets a TimeZone instance>
int offset = timeZone.getStandardOffset(new Date().getTime());
I'm wondering why the call to timezone.getStandardOffset() requires that a number of milliseconds be passed in. My suspicion is that this is to take into account historical variations in a time zone's offset? (e.g. we need to account for that crazy day back in 2005 when Mr. Bush decided that central time would be UTC+13 for just that day, since 13 is a bigger number than -2)
Is this correct?
A: In the very rare event that a location's standard time changes, this will account for it. The best example I can think of is when Alaska changed from being part of Russia to being part of USA (and literally hopped across the international dateline, which used to run down the border of Canada and Alaska). A DateTimeZone representing Alaska would have a different standard offset before and after that date.
| |
doc_23530454
|
Remove color gradient from scaled unit bitmap, the answer works with 1x1 pixel. How to achieve the same result with, for example, 2x2 pixels with red, blue, green and yellow colour, how to remove gradient in that case (stretched image) with SetPixel?
| |
doc_23530455
|
Private timer As DispatcherTimer
Private CountUp As Integer
Public Sub DispatcherTimerSetup()
timer = New DispatcherTimer()
timer.Interval = New TimeSpan(0, 0, 1)
AddHandler timer.Tick, AddressOf timer_Tick
timer.Start()
End Sub
Private Sub timer_Tick(sender As Object, e As Object)
CountUp += 1
txblCountdown.Text = CountUp.ToString("00\:00")
'timeformat
End Sub
best regards,
Polina
A: You can use a TimeSpan to do this.
Private Sub timer_Tick(sender As Object, e As Object)
CountUp += 1
Dim counter As TimeSpan
counter = TimeSpan.FromSeconds(CountUp)
txblCountdown.Text = counter.ToString("mm\:ss")
End Sub
| |
doc_23530456
|
I can use either one of them, but the problem is I can't set the collider on any of them mesh collider isn't working correctly.
The maze which was built by ProBuilder has mesh in the mesh collider component but my player still falls through.
If there is a better way please let me know. Thank you
I have convex ticked to show collider.
A: Having a convex collider on the entire maze is like putting the entire maze in a cardboard box. It's not going to work. You need to deconstruct the maze to the point that you have wall segments, and then you can put convex colliders on each wall segment.
I don't see a rigidbody in the screenshot you posted. There might be a chance you could clear the convex setting on the collider, add a Rigidbody, and use the isKinematic setting on the Rigidbody and get what you want.
Really though, if I were you, I'd deconstruct the map to wall segments, represent your map with an array, and dynamically create the maze in Awake (which triggers before Start). This also allows you to put colliders on the floor and wall segments individually, lets you easily create different mazes, etc.
| |
doc_23530457
|
class PersonController extends RestfulController<Person> {
static responseFormats = ['json', 'xml']
PersonController() {
super(Person)
}
}
However, now I want to add a search option to this. What is the Grails way of making this possible?
I thought of adding the following:
def search(Map params) {
println params
}
But that makes Grails (2.3) crash (| Error Fatal error during compilation org.apache.tools.ant.BuildException: Compilation Failed (Use --stacktrace to see the full trace)).
So what is the right way of adding this? I'm looking for some solution which I can call using http://localhost:8080/foo/person/search?q=erik
This is my UrlMappings:
static mappings = {
"/$controller/$action?/$id?(.${format})?"{
constraints {
// apply constraints here
}
}
"/rest/persons"(resources:'Person')
I've changed the above to:
def search() {
println params
}
And that doesn't give the compilation error anymore, but I still get this error:
TypeMismatchException occurred when processing request: [GET] /declaratie-web/rest/medicaties/search - parameters:
q: erik
Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String. Stacktrace follows:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String
I also found out that it doesn't matter how I call the controller:
http://localhost:8080/foo/person/search?q=erik
http://localhost:8080/foo/person/search222?q=erik
http://localhost:8080/foo/person/search39839329?q=erik
All fails with the above error, so it seems my method is ignored (maybe caused by my URLmapping?)
A: You really aren't being RESTful by doing that. q should just be a parameter for the index action. You can override that method to include your functionality.
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def c = Person.createCriteria()
def results = c.list(params) {
//Your criteria here with params.q
}
respond results, model:[personCount: results.totalCount]
}
A: @james-kleeh solution is right, but you can do it more clean by override the listAllResources method which is called by index
@Override
protected List<Payment> listAllResources(Map params) {
Person.createCriteria().list(params) {
// Your criteria here with params.q
}
}
| |
doc_23530458
|
public RequestTest Test(string url)
{
var test = new RequestTest() { Url = url };
var sw = new Stopwatch();
var request = WebRequest.CreateHttp(test.Url);
request.AllowAutoRedirect = true;
request.Method = "HEAD";
request.UserAgent = "Accept-Language: en-US,en;q=0.5";
try
{
sw.Start();
using (var response = (HttpWebResponse)request.GetResponse())
{
sw.Stop();
test.Time = (int)sw.ElapsedMilliseconds;
test.StatusCode = response.StatusCode;
}
return test;
}
catch (WebException ex)
{
test.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
return test;
}
}
URL is http://monosnap.com/page/faq , which must be redirected to the some language area, for example - http://monosnap.com/ru/page/faq
But it throws WebException, with Message "The remote name could not be resolved: 'page'".
UPD: I add useragent
request.UserAgent = "Accept-Language: en-US,en;q=0.5";
But I still get the same exception "The remote name could not be resolved: 'page'"
Also, redirect works properly from my browser. So, problem is in code.
A: For the site you are attempting to access, it is sufficient to add an "Accept-Language" header like this:
using System;
using System.Diagnostics;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
public class RequestTest
{
public string Url { get; set; }
public int Time { get; set; }
public HttpStatusCode StatusCode { get; set; }
}
public static RequestTest Test(string url)
{
var test = new RequestTest() { Url = url };
var sw = new Stopwatch();
var request = WebRequest.CreateHttp(test.Url);
request.AllowAutoRedirect = true;
request.Method = "HEAD";
request.Headers.Add("Accept-Language: ru-RU, en; q = 0.5");
try
{
sw.Start();
using (var response = (HttpWebResponse)request.GetResponse())
{
sw.Stop();
test.Time = (int)sw.ElapsedMilliseconds;
test.StatusCode = response.StatusCode;
}
return test;
}
catch (WebException ex)
{
test.StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
return test;
}
}
static void Main(string[] args)
{
var x = Test("http://monosnap.com/page/faq");
Console.WriteLine(x.StatusCode + " " + x.Time.ToString());
Console.ReadLine();
}
}
}
Sample output:
OK 186
It appears that the redirector does not have a default setting if it cannot determine the language.
Further information on setting Accept-Language: Setting language preferences in a browser.
| |
doc_23530459
|
A: You could make them custom buttons in a TableLayout or use a GridView and incorporate it like a ListView
| |
doc_23530460
|
columnvalues = List(df.columns.values)
['ColA','ColB','ColC','ColD','ColE']
rowData=df.loc[df['ColA']=='apple']
ColA ColB ColC ColD ColE
13 apple NaN height width size
I have columnValues, but if I could also row values I can easily use
dict(zip(colValues, rowValues)) method to create columnKey rowValue based dictionary then by calling dictionary to write output excel files. Because in Excel file which is output file, column numbers and column places differ from how they are set up in dataframe object.
Any ideas on how I can achieve this result, even with a different approach, would be greatly appreciated.
I need method to get this result below;
rowValuesList=['apple', NaN, 'height','width','size']
A: We could do
rowValuesList = rowData.iloc[0].tolist()
| |
doc_23530461
|
Date A B C
01/04/2012 2 5 Y
05/04/2012 3 4 Y
06/05/2012 7 6 Y
09/05/2012 8 2 N
11/05/2012 1 4 Y
15/06/2012 5 4 Y
That continues on with more rows.
I want to plot a bar chart with date on the bottom axis converted to show just the month (i.e. April, May, July) and then on the y-axis I want the average of the sum of the A and B column so for the month of April it would be 7 (14 total over two instances) and for May it would be 9.33 (28 total over 3 instances).
I'm really struggling with how to do this and I'd prefer not to create another column that sums up A and B.
A: You can use groupby on month_name then mean+eval:
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df.groupby([df['Date'].dt.month_name()], sort=False).mean().eval('A+B')\
.plot(kind='bar')
print(df.groupby([df['Date'].dt.month_name()], sort=False).mean().eval('A+B'))
Date
April 7.000000
May 9.333333
June 9.000000
dtype: float64
| |
doc_23530462
|
i7-860 (12GB RAM, 120GB SSD) running Ubuntu 14.04 and MySQL 5.5 (OLD)
To a new machine:
i7-7560U (16GB RAM, 512GB SSD) running Ubuntu 16.04 and MySQL 5.7 (NEW)
Both machines have the same PHP configuration (7.1) and the out of the box MySQL configuration for their respective versions.
On the OLD machine, my phpunit test suite ran in 5.5 seconds and on the NEW machine, it runs in 20 seconds. I have narrowed the problem down to MySQL. Each test boots the framework and resets the database (drops/adds schema). I believe the database reset is the cause of the slowdown.
I know my new machine has 1/2 the cores/threads but could that cause the slow down I am seeing? I ran sysbench on both machines and received comparable results (MySQL had more transactions/second on the new machine).
Is there any configuration tuning for MySQL 5.7 I could do to improve performance?
Something I'm missing?
A: You could use this tool to generate an optimised my.cnf mysql server configuration for your server https://tools.percona.com
We have used this tool's output in production server to get really good speed in the past as opposed to the default setting mysql server comes out of the box.
| |
doc_23530463
|
@app.get("/movies/", response_model=schemas.Movie)
def read_movie_by_title(title: str, db: Session = Depends(get_db)):
db_movie = crud.get_movie_by_title(db, title=title)
return db_movie
@app.get("/movies/", response_model=List[schemas.Movie])
def read_movies(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
db_movies = crud.get_movies(db, skip=skip, limit=limit)
return db_movies
As You can see, the first one is for getting a movie by its title and has a query parameter (title) and the second one is for getting a list. When I check the generated docs, the one for read_movie_by_title is missing.
I tried to solve this by changing the path for read_movie_by_title to /movies by removing /, but I don't like this solution at all.
So the question is: Is there a way to have two equal paths, but one with query parameters, or do I need to do this in a different way? Any suggestions?
A: You could use Path Parameters instead of Query parameters for the first one, by changing the endpoint to "/movies/{title}":
@app.get("/movies/{title}", response_model=schemas.Movie)
def read_movie_by_title(title: str, db: Session = Depends(get_db)):
db_movie = crud.get_movie_by_title(db, title=title)
return db_movie
# 2nd remains the same
@app.get("/movies/", response_model=List[schemas.Movie])
def read_movies(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
db_movies = crud.get_movies(db, skip=skip, limit=limit)
return db_movies
A: The answer to your question (Is there a way to have two equal paths, but one with query parameters) is no, the only way to differentiate a path is by its method (GET, PUT, POST, DELETE, ...).
You do however have multiple ways of achieving your desired result.
REST approach
The standard REST approach to this would be to define a different path for the title based retrieval, such as /movies/{title}, like in the first example shown in the documentation for path parameters @ FastAPI.
If you want to implement a search feature instead of a direct retrieval by unique title method, you can do something like this:
@app.get("/movies", response_model=List[schemas.Movie])
def read_movies(title: Optional[str] = None, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
# list of filters
filters = []
if title: # if it's not none
filters.append(models.Movie.title.ilike(f"%{title}%"))
db_movies = crud.get_movies(db, filters=filters, skip=skip, limit=limit)
return db_movies
and within your crud operation you would query it something like:
return session.query(models.Movie).filter(*filters).all()
Simpler approach that does what you want with one method
@app.get("/movies", response_model=List[schemas.Movie])
def read_movies(title: Optional[str] = None, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
if title: # if it's not none
return crud.get_movie_by_title(db, title=title)
return crud.get_movies(db, filters=filters, skip=skip, limit=limit)
Though the latter might confuse the consumer of your API, hence the REST approach will be the most recommended one.
| |
doc_23530464
|
I can see that my get request is successfull and that data is retrieved from my backend however when rendering I get this error :
TypeError: startup.map is not a function
CardList
C:/personalworkspace/unicorn/front/src/components/CardList.js:30
27 |
28 | return (
29 | <div className="card list">
> 30 | <Grid container spacing={4}>
| ^ 31 | {startup.map((startups) => (
32 | <Grid key={startups.id} item xs={4}>
33 | <Link to={{ pathname: `product/${startups.id}` }}>
Here is my code :
import React from 'react';
import CardComponent from './CardComponent';
import { Grid } from '@material-ui/core';
import { Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import StartUpService from './../Services/StartUpService';
const CardList = () => {
const [startup, setstartups] = useState([]);
useEffect(() => {
retrieveTutorials();
}, []);
const retrieveTutorials = () => {
StartUpService.getAll()
.then((response) => {
const myData = response.data;
setstartups(myData);
console.log(myData);
})
.catch((e) => {
console.log(e);
});
};
return (
<div className="card list">
<Grid container spacing={4}>
{startup.map((startups) => (
<Grid key={startups.id} item xs={4}>
<Link to={{ pathname: `product/${startups.id}` }}>
<CardComponent
className="cards"
key={startups.id}
id={startups.id}
image={startups.image}
header={startups.header}
title={startups.title}
category={startups.category}
summary={startups.summary}
/>
</Link>
</Grid>
))}
</Grid>
</div>
);
};
export default CardList;
I am not sure what's wrong with my map function?
Here is first object of my API response :
{"data":[{"id":1,"header":"First Start Up Header","title":"Title for
Startup 1","category":"First Start Up Category","description":"First
Start Up description","tags":
["FINTECH"],"card_image":"http://localhost:8000/media/card_images/card1.jpg","logo_image":"http://localhost:8000/media/logo_images/1.png"},
A: Nothing is wrong with map. startup isn't an array (or other type supporting .map). console.log the api response and you'll see what it really is.
You're code is probably fine the API is just returning data in a format other than what you expect.
| |
doc_23530465
|
GLEW=%THIRD_PARTY_ROOT%\GLEW
GLEW_1_5_5=%GLEW%\glew-1.5.5
GLEW_BIN_PATH=%GLEW_ROOT%\bin
GLEW_INCLUDE_PATH=%GLEW_ROOT%\include
GLEW_LIB_PATH=%GLEW_ROOT%\lib
GLEW_ROOT=%GLEW_1_5_5%
OSG=%THIRD_PARTY_ROOT%\OpenSceneGraph
OSG_2_8_3=%OSG%\OpenSceneGraph-2.8.3
OSG_BIN_PATH=%OSG_ROOT%\bin
OSG_INCLUDE_PATH=%OSG_ROOT%\include
OSG_LIB_PATH=%OSG_ROOT%\lib
OSG_ROOT=%OSG_2_8_3%
THIRD_PARTY_ROOT=C:\dev\third-party
But I was having a heck of a time getting them to actually expand properly. For a while when I looked at the output of set, I was just getting what looked like they were being expanded in order and so any ones that depended on foo_ROOT weren't being expanded properly. I tried enabling delayed expansion and that didn't help, but restarting seemed to... so maybe delayed expansion required a restart..
Either way, I have GLEW_BIN_PATH and OSG_BIN_PATH in my PATH variable and they refuse to expand. This is really frustrating because the dll's are residing there and of course I can get evvvverything else to expand... any thoughts?
Edit: I have them in the PATH variable as:
[everything else....];%GLEW_BIN_PATH%;%OSG_BIN_PATH%
So I'm not seeing an obvious cause to keep them from expanding out..
A: It looks like there is a lexicographic dependency on the variables definition.
Windows expands and populates the Enviroment Variables on lexicographic order (:-O)
You can only use on your variable, variables that are "lexicographically" lower than your variable.
Example:
Following Definition:
VAR_01=1
VAR_02=%VAR_01%-2
VAR_03=%VAR_02%-3
Produces
VAR_01 is 1
VAR_02 is 1-2
VAR_03 is 1-2-3
But
VAR_01=1
VAR_02=%VAR_03%-2
VAR_03=%VAR_01%-3
Produces
VAR_01 is 1
VAR_02 is -2
VAR_03 is 1-3
Due VAR_03 is not defined when VAR_02 is expanded.
A: Yeah, this is driving me crazy. Full repro by:
System Properties, Environment Varialbles, set up like so:
one = c:
two = %ONE%\two
three = %TWO%\three
Then click OK, and run cmd. Here's what I see:
C:\>set one
one=C:
C:\>set two
two=C:\two
C:\>set three
three=%TWO%\three
This link explains for Vista, but does not mention that it happens on Win7.
http://support.microsoft.com/kb/911089
...Jonas
A: I've had success with escaping the percent sign:
GLEW=%%THIRD_PARTY_ROOT%%\GLEW
THIRD_PARTY_ROOT=C:\dev\third-party
C:\>set GLEW
GLEW=C:\dev\third-party\GLEW
When viewing the variable from the Windows Environment Variable window, it will display as
GLEW | %THIRD_PARTY_ROOT%\GLEW
Note: The double percent signs will only work inside a script. If using on the command line, use the caret escape character (e.g. GLEW=^%THIRD_PARTY_ROOT^%\GLEW).
A: Have you saved all of the needed variables in the System Variables as well? Because in order to expand the values, the system will have to have a "permanent" memory of all the needed variables.
If you do all these together in a row on the command line, just saying X=something and Y=%X%;else, then when you set the path to PATH=%PATH%;%Y%, the shell expands the values of all the variables before it saves the new value of PATH; but as soon as you close the Command Prompt window, the system has forgotten %X% and %Y% entirely.
However, if you use the System Properties Control Panel to set the PATH to include the unexpanded variables, than all those variables are going to have to exist as system variables when you reboot, or they'll fail to expand.
To ensure that you are saving all the variables in the system so that they are still there after the reboot, either use the System Properties Control Panel or the SETX.EXE command. If you are going to use them in the system PATH (not just your user account's path), then you'll want to use SETX /M X=blah or the bottom part of the System Properties | Environment Variables tab, labeled "System variables".
A: I have been experiencing this in Windows 10, build 1903.
For me, the solution was to remove the PATH variable from 'user' (the upper half of the system properties dialog) and keep only the path in 'system'. Restart the cmd.exe shell or use refreshenv to reload the properties, and expansion should work again.
This looks like a bug in Windows for how it resolves user vs system properties, or possibly the processing order. For me it was not replacing values in the user PATH with values from the 'system' set of env vars. It might work better if all the variables are in user, but I've not tested this hypothesis.
| |
doc_23530466
|
For example my program wants the user to guess a number between 1-1000. My program works perfectly, except when the user inputs any other character other than a number it goes CRAZY. Anyways, I want it to check and make sure that the user is inputting numbers, not something silly. So I have been going in circles trying to figure this part out. I am sure it is a easy fix, but I am new to programming and this has got me stumped. Any help would be appreciated.
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
bool isGuessed=true;
while(isGuessed)
{
srand(time(0));
int number=rand()%1000+1;
int guess;
char answer;
cout<<"Midterm Exercise 6\n";
cout<<"I have a number between 1 and 1000.\n";
cout<<"Can you guess my number?\n";
cout<<"Please type your first guess:\n\n";
cin>>guess;
while(guess!=number)
{
if(guess>number)
{
cout<<"\nToo high. Try again!\n\n";
cin>>guess;
}
if(guess<number)
{
cout<<"\nToo low. Try again!\n\n";
cin>>guess;
}
}
if(guess==number)
{
cout<<"\nExcellent! You have guess the number!\n";
}
cout<<"Would you like to play again (y or n)?\n\n";
cin>>answer;
cout<<"\n";
if(answer!='y')
{
isGuessed=false;
cout<<"Thanks for playing!\n\n";
system ("PAUSE");
return 0;
}
}
return 0;
}
A: Here's a snippet I like to keep around for using in these sorts of situations.
int validInput()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std:numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
return x;
}
Then any place you want to use cin>>guess, instead, use guess = validInput();
A: Since spreading around code similar to what @nhgrif suggests for every acquisition is tedious and error-prone, I usually keep around the following header:
#ifndef ACQUIREINPUT_HPP_INCLUDED
#define ACQUIREINPUT_HPP_INCLUDED
#include <iostream>
#include <limits>
#include <string>
template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result)
{
do
{
Os<<Prompt.c_str();
if(Is.fail())
{
Is.clear();
Is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Is>>Result;
if(Is.fail())
Os<<FailString.c_str();
} while(Is.fail());
}
template<typename InType> InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString)
{
InType temp;
AcquireInput(Os,Is,Prompt,FailString,temp);
return temp;
}
#endif
Usage example:
//1st overload
int AnInteger;
AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger);
//2nd overload (more convenient, in this case)
int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n");
The AcquireInput function allows to read any type for which there's an operator>> available and automatically retries (cleaning up the input buffer) if the user inserts invalid data. It also prints the given prompt before asking the data and the error message in case of invalid data.
| |
doc_23530467
|
Does it have to do with strsep? I didn't use strtok because I want to catch the null tokens if the string consisted of ",," multiple delimiters with nothing in between them.
Since tempStr has malloced well over the necessary amount, it should be sufficient to as a *dest for strcpy. I have been stuck on this for hours. If anyone could point out my mistake, I will greatly appreciate it. Thank you.
int main(int argc, char * argv[])
{
char* one = "hello, my, name, is, code monkey, \"This, is a title\", more, random, stuff\n";
char* two = "blah blah blah";
char* tempStr= malloc(1000);
void* freeTempStr = tempStr;
strcpy(tempStr, one);
char* fronttoken = strsep(&tempStr, "\"");
char* title = strsep(&tempStr, "\"");
char* backtoken = strsep(&tempStr, "\n");
char* token;
strcpy(tempStr, fronttoken);
token = strsep(&tempStr, ",");
while (token != NULL)
{
printf("Front tokens: %s\n", token);
token = strsep(&tempStr, ",");
}
printf("Title: %s\n", title);
strcpy(tempStr, backtoken);
token = strsep(&tempStr, ",");
while (token != NULL)
{
printf("Back tokens: %s\n", token);
token = strsep(&tempStr, ",");
}
//2nd strcpy gives segmentation fault
free(freeTempStr)
return 0;
}
Output...
Front tokens: hello
Front tokens: my
Front tokens: name
Front tokens: is
Front tokens: code monkey
Front tokens:
Title: This, is a title
Segmentation fault
A: Having looked harder at the code and compiled and experimented with it, I agree with M.M's analysis that the immediate problem is that you're
trying to copy to a null pointer.
However, I suspect you've not carefully considered the memory management in general. When you do strcpy(tempStr, one);, you copy the source string into allocated memory. (Un)fortunately, you allocated far more memory than the copy needed. When you subsequently do strcpy(tempStr, fronttoken);, you are copying the fronttoken to a location after the original copy of one in tempStr. You then split that up.
You crash because you stop when tempStr has been set to null, and then you try strcpy(tempStr, backtoken), copying to the null pointer.
If you fix that, you could run into the problem of overlapping string copy. Your current set of back tokens is small enough that it isn't a problem, but if you had a 100 bytes of back tokens, you would have an overlapping string copy and undefined behaviour.
This code shows the problem and fixes it. Note that it includes square brackets around the tokens so it is easier to see exactly what is found.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* one = "hello, my, name, is, code monkey, \"This, is a title\", more, random, stuff\n";
char* tempStr= malloc(1000);
void* freeTempStr = tempStr;
strcpy(tempStr, one);
printf("tempStr = [%p .. %p)\n", (void *)tempStr, (void *)(tempStr + 1000));
char* fronttoken = strsep(&tempStr, "\"");
printf("tempStr = %p; fronttoken = %p\n", (void *)tempStr, (void *)fronttoken);
char* title = strsep(&tempStr, "\"");
printf("tempStr = %p; title = %p\n", (void *)tempStr, (void *)title);
char* backtoken = strsep(&tempStr, "\n");
printf("tempStr = %p; backtoken = %p\n", (void *)tempStr, (void *)backtoken);
char* token;
printf("tempStr = %p; fronttoken = %p - before strcpy 1\n", (void *)tempStr, (void *)fronttoken);
strcpy(tempStr, fronttoken);
token = strsep(&tempStr, ",");
while (token != NULL)
{
printf("Front tokens: %p [%s]\n", (void *)token, token);
token = strsep(&tempStr, ",");
}
printf("Title: [%s]\n", title);
printf("tempStr = %p; backtoken = %p - before strcpy 2 (unfixed)\n", tempStr, backtoken);
tempStr = freeTempStr;
printf("tempStr = %p; backtoken = %p - before strcpy 2 (fixed - but beware overlap)\n", tempStr, backtoken);
strcpy(tempStr, backtoken);
token = strsep(&tempStr, ",");
while (token != NULL)
{
printf("Back tokens: %p [%s]\n", (void *)token, token);
token = strsep(&tempStr, ",");
}
free(freeTempStr);
return 0;
}
Sample output (Mac running macOS High Sierra 10.13.1, with the security update 2017-001 installed β macOS 10.13.1 (17B1002) β install it if you've not already done so!):
tempStr = [0x7fb91ac02880 .. 0x7fb91ac02c68)
tempStr = 0x7fb91ac028a3; fronttoken = 0x7fb91ac02880
tempStr = 0x7fb91ac028b4; title = 0x7fb91ac028a3
tempStr = 0x7fb91ac028ca; backtoken = 0x7fb91ac028b4
tempStr = 0x7fb91ac028ca; fronttoken = 0x7fb91ac02880 - before strcpy 1
Front tokens: 0x7fb91ac028ca [hello]
Front tokens: 0x7fb91ac028d0 [ my]
Front tokens: 0x7fb91ac028d4 [ name]
Front tokens: 0x7fb91ac028da [ is]
Front tokens: 0x7fb91ac028de [ code monkey]
Front tokens: 0x7fb91ac028eb [ ]
Title: [This, is a title]
tempStr = 0x0; backtoken = 0x7fb91ac028b4 - before strcpy 2 (unfixed)
tempStr = 0x7fb91ac02880; backtoken = 0x7fb91ac028b4 - before strcpy 2 (fixed - but beware overlap)
Back tokens: 0x7fb91ac02880 []
Back tokens: 0x7fb91ac02881 [ more]
Back tokens: 0x7fb91ac02887 [ random]
Back tokens: 0x7fb91ac0288f [ stuff]
Note that using a debugger would also allow you to find this problem pretty quickly.
A: Your code doesn't compile as posted; there is a missing semicolon. Moreover, numerous standard headers are missing.
On 64 bit Ubuntu 16 with gcc 6.2.6, a crash occurs other than where you are observing it. Because the <string.h> header is missing, the strsep function is implicitly declared as returning int, which is wrong. Because of this, the fronttoken variable receives a garbage value and the very first strcpy fails.
The first thing to do is get a clean build with no errors or warnings (after turning on any diagnostics that are widely recommended by the community of users of your compiler).
After all that is fixed you have a simple logic problem:
while (token is not null) {
token = strsep(&tempStr, ...)
}
strcpy into tempStr
Since the while loop contains no break statements, the only way it terminates is if token becomes null.
The only way token becomes null is if strsep returns null.
The only way strsep returns null, according to the documentation, is if tempStr is null.
I.e. the fact that token is null proves that tempStr must be null, which means that we must not use tempStr as the destination of a strcpy.
How tempStr becomes null is that in a previous call to strsep, no token delimiter was found. In that case strsep returns the whole string as the extracted token, and overwrites the pointer with null.
In other words, after extracting the last token from the string, strsep overwrites the pointer with null. Then the next time strsep is called, it returns null, indicating "no more tokens are available". This makes strsep easy to use: just keep calling it until you get a null. But you have to understand that the temporary context pointer gets nulled out in the process.
| |
doc_23530468
|
Does Rails have the same structure as Java when testing If statements like:
IF text1 = text2 Then
... do something ...
Else
... do something ...
Thanks,
Nick
A: if text1 == text2
...
elsif text2 == text3
...
else
...
end
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if_expression
http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#if
A: In controller
if params[:text_box_name_1].to_s == params[:text_box_name_2].to_s
----
else
end
A: I think this might help: http://www.howtogeek.com/howto/programming/ruby/ruby-if-else-if-command-syntax/
| |
doc_23530469
|
Here's a snippet of the code I'm using:
for (int l = 0; l < tmxMap.Tilesets[k].Tiles.Count; l++)
// This line throws an error
if (tmxMap.Tilesets[k].Tiles[l].Properties != null)
// and if I remove the above line, this line throws an error
for (int m = 0; m < tmxMap.Tilesets[k].Tiles[l].Properties.Count; m++)
The error I get says The given key was not present in the dictionary. But... I'm not even checking for a key.
Am I missing something?
Any help would be appreciated.
A:
The error I get says The given key was not present in the dictionary. But... I'm not even checking for a key.
Yes you are checking for a key. This is your code:
if (tmxMap.Tilesets[k].Tiles[l].Properties != null)
You are checking for Tilesets with key k and then checking Tiles with key l. If the Tilesets does not contain an item with key k, you will get that error. The same is true for Tiles with key l.
You can do the following when working with dictionaries:
Option 1
The lookup is performed twice: once to see if the item exists, and then a second time to get the value:
var items = new Dictionary<string, string>();
items.Add("OneKey", "OneValue");
if(items.ContainsKey("OneKey"))
{
var val = items["OneKey"];
}
Option 2
And here is another approach where the lookup is performed once:
string tryVal;
if (items.TryGetValue("OneKey", out tryVal))
{
// item with key exists so you can use the tryVal
}
A: As far as I can see in your code I think that Tiles is a Dictionary and when you try to iterate by tmxMap.Tilesets[k].Tiles[l] it throws error because it searches for key l, not for the l-element.
You can try tmxMap.Tilesets[k].Tiles[tmxMap.Tilesets[k].Tiles.Keys.ElementAt(l)]
A: You are trying to get a value based on keys k,l.
if (tmxMap.Tilesets[k].Tiles[l].Properties != null) statement is basically getting the value corresponding to the k key in Tilesets dictionary. If Tilesets dictionary doesn't contain a value for the key k, an exception will be thrown. Also if there is no value corresponding to the l key, in Tiles dictionary, exception will be thrown.
You can use TryGetValue extension method, which will give you the value if the item was found.
TileSet ts = null;
if(tmxMap.Tilesets.TryGetValue(k, out ts)
{
for (int l = 0; l < ts.Tiles.Count; l++)
{
Tiles tl = null;
if(ts.TryGetValue(l,out tl)
{
if (tl.Properties != null)
{
for (int m = 0; m < tl.Properties.Count; m++)
{
//Do something
}
}
}
}
}
| |
doc_23530470
|
plist = ['p5', 'p14', 'p23', 'p32', 'p41', 'p50', 'p59', 'p68', 'p77', 'p85', 'p95']
for pltcount in range(len(plist)):
plt.plot(data1[pltcount], np.exp(data2)[pltcount], marker='o', label=str(plist[pltcount]))
plt.legend()
plt.show()
This is using the plt.style.use('fivethirtyeight') to make the plots nicer. I have found examples where I manually assign the colors. What if I want it to be automatic and from some well-known palettes?
A: How about the colors of the rainbow? The key here is to use ax.set_prop_cycle to assign colors to each line.
NUM_COLORS = len(plist)
cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle('color', [cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
# Or,
# ax.set_prop_cycle(color=[cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
for i, p in enumerate(plist):
ax.plot(data1[i], np.exp(data2)[i], marker='o', label=str(p))
plt.legend()
plt.show()
Borrowed from here. Other options possible.
| |
doc_23530471
|
*
*Create an object
*Read in an enormous amount of data for that
*After calculating that object's score, print it out
*Delete the object from memory because each object has a lot of variables attributed to it
*Loop it 1000 times
It seems simple enough but after looking around I see things about destructors but I don't know if that's what I am looking for.
for(int i=0; i<1000; i++){
applicants object1;
object1.readin();
cout<<object1.calculate();
//How do I delete object1 and start again?
}
Thank you so much for any help. I don't know hardly anything about this language. Also, do I even need objects? I'm confused
A: It is not necessary to delete object1.
For every iteration of the loop, a new object object1 will be created (using default constructor) and destructed after the "cout" statement.
A: You don't need to call the destructor of object1, it would be called at the end of the loop body.
Technically, destructors are called at the end (right brace) of the block declaring the object.
This is why the right brace } is sometimes jokingly called the most important statement in C++. A lot of things may happen at that time.
It is however generally considered bad style to do real computations in constructors or destructors. You want them to "allocate" and "deallocate" resources. Read more about RAII and the rule of five (or of three).
BTW, if an exception happens, the destructors between the throw and the matching catch are also triggered.
Please learn more about C++ containers. You probably want your applicants class to use some. Maybe it should contain a field of some std::vector type.
Also learn C++11 (or C++14), not some older version of the standard. So use a recent compiler (e.g. GCC 4.9 at least, as g++, or Clang/LLVM 3.5 at least, as clang++) with the -std=c++11 option (don't forget to enable warnings with -Wall -Wextra, debugging info with -g for debugging with gdb, but enable optimizations e.g. with -O2 at least, when benchmarking). Modern C++11 (or C++14) has several very important features (missing in previous standards) that are tremendously useful when programming in C++. You probably should also use make (here I explain why), see e.g. thisΒ and others examples. See also valgrind.
A: Object one will be deleted automatically when it goes out of scope at the end bracket. You are already doing it. Be wary as if you create a pointer it will not be destructed when it goes out of scope. But your current code is working fine.
http://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm
| |
doc_23530472
|
You can reproduce this error(?) when you often click the "Add button". The first view clicks, both messages were printed and some clicks later only the first listener further works.
Runnable example:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
final ObservableList<String> list = FXCollections.observableArrayList();
primaryStage.setTitle("Demonstrator");
// Button
Button addButton = new Button();
addButton.setText("Add Element");
addButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
list.add("TEST");
}
});
// ListView
ListView<String> lv = new ListView<String>();
lv.setItems(list);
// Add elements to root
VBox root = new VBox();
root.getChildren().add(addButton);
root.getChildren().add(lv);
// Show scene
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
// This listener works correct
list.addListener(new ListChangeListener<String>() {
@Override
public void onChanged(Change<? extends String> c) {
System.out.println("#listener1: " + list.size());
}
});
// This listener stops working after 10-30 clicks on the button
Bindings.size(list).addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("#listener2: " + newValue);
}
});
}
}
I tried it with jdk-8u112-windows-x64 and jdk-8u112-windows-i586
Does anybody have an idea, if there is any mistake in my code, or if it's really a problem with JavaFX?
I got the solution:
The binding was removed from the garbage collector. You have to store the binding as field.
Thanks!
A: After the line 61 is executed. The instance created in Bindings.size() is not strongly reachable by anything, so it is eligible for garbage collection. It is softly reachable through the listener, but that will not prevent garbage collection.
So eventually it will get garbage collected and stop working.
The solution is: make it strongly reachable, e.g. by storing it in a field in the class.
| |
doc_23530473
|
1) File info :
Testval.txt :
10,10
2) Reading the file and storing the values into variable.
code :
val rangetab = spark.read.format("csv").option("header","false").option("inferSchema","true").load("s3a://clientbucket/Check/TestVal.txt")
val a = rangetab.first()
println(a)
Then i am getting out like (10,10). I want to store the values like
a = 10 and b = 10.
kindly help me how to do this?
A: Try: val res = rangetab.first()
val (a,b)=(res.get(0),res.get(1))
println(a)
println(b)
| |
doc_23530474
|
When I try to add a Test target from the + button it asks me to choose a Target to be tested either A or B. my tests are the same on both targets.
This is where I am confused. How can I have same units tests across all targets? Thanks .
A: You can't have two host applications in single test target. You have to select (n)one.
But if the code is the same for both targets, it doesn't really matter which one you choose, I guess?
Of course you could do the same as you probably did for your logic code, that means to make the same (test) code "member" of two test targets. However I don't see the point in testing the same stuff twice.
It also seems to be possible to set up your tests, so that they don't depend on a specific host application, like described in the following link, but this also comes with some restrictions.
https://clean-swift.com/how-to-make-your-unit-tests-run-faster
I would go with the first approach: Just choose one host (app target), and go for it.
A: Instead of maintaining two targets for basically same code I will advise you two maintain a single target and customize each flavours with schemes and configs. This also allows you to share those schemes and configs in your single test target allowing you to test different flavours of the same app.
| |
doc_23530475
|
This is my device:
vctl config get platform.driver registry_configs/33333.csv
That prints:
[
{
"Reference Point Name": "signal_payload",
"Volttron Point Name": "signal_payload",
"Units": "percent",
"Unit Details": "(default 0.0)",
"BACnet Object Type": "analogValue",
"Property": "presentValue",
"Writable": "FALSE",
"Index": "0",
"Write Priority": "",
"Notes": "Open ADR Payload Signal"
},
{
"Reference Point Name": "int_signal_duration",
"Volttron Point Name": "int_signal_duration",
"Units": "percent",
"Unit Details": "(default 0.0)",
"BACnet Object Type": "analogValue",
"Property": "presentValue",
"Writable": "FALSE",
"Index": "1",
"Write Priority": "",
"Notes": "Integer Signal Duration"
}
]
device address:
vctl config get platform.driver devices/slipstream_internal/slipstream_hq/33333
this will print:
{
"driver_config": {
"device_address": "10.200.200.224",
"device_id": 33333
},
"driver_type": "bacnet",
"registry_config": "config://registry_configs/33333.csv"
}
I think I have something wrong in my agent code in the dr_level = self.vip.rpc.call as shown in the snip below as the code errors out right after the ACTUATOR AGENT SCHEDULE SUCCESS:
dr_status = self.vip.rpc.call(
'platform.actuator', 'request_new_schedule', self.agent_id, 'my_test', 'HIGH', schedule_bac0_request).get(
timeout=4)
_log.info(f'*** [Setter Agent INFO] *** - ACTUATOR AGENT SCHEDULE SUCCESS')
dr_level = self.vip.rpc.call('platform.actuator','get_point', dr_topic, point="signal_payload").get(timeout=15)
the dr_topic is slipstream_internal/slipstream_hq/33333
Any ideas to try greatly appreciated...
Full traceback:
2021-06-15 14:36:27,597 (actuatoragent-1.0 403031) __main__ DEBUG: handle_get: slipstream_internal/slipstream_hq/33333
2021-06-15 14:36:27,598 (master_driveragent-4.0 403069) volttron.platform.vip.agent.subsystems.rpc ERROR: unhandled exception in JSON-RPC method 'get_point':
Traceback (most recent call last):
File "/var/lib/volttron/volttron/platform/vip/agent/subsystems/rpc.py", line 158, in method
return method(*args, **kwargs)
File "/home/volttron/.volttron/agents/55fbfb56-beac-4e6d-a201-1ab17b11d42b/master_driveragent-4.0/master_driver/agent.py", line 448, in get_point
return self.instances[path].get_point(point_name, **kwargs)
File "/home/volttron/.volttron/agents/55fbfb56-beac-4e6d-a201-1ab17b11d42b/master_driveragent-4.0/master_driver/driver.py", line 341, in get_point
return self.interface.get_point(point_name, **kwargs)
AttributeError: 'DriverAgent' object has no attribute 'interface'
2021-06-15 14:36:27,599 (actuatoragent-1.0 403031) volttron.platform.vip.agent.subsystems.rpc ERROR: unhandled exception in JSON-RPC method 'get_point':
Traceback (most recent call last):
File "/var/lib/volttron/volttron/platform/vip/agent/subsystems/rpc.py", line 158, in method
return method(*args, **kwargs)
File "/home/volttron/.volttron/agents/8f4ee1c0-74cb-4070-8a8c-57bf9bea8a71/actuatoragent-1.0/actuator/agent.py", line 897, in get_point
return self.vip.rpc.call(self.driver_vip_identity, 'get_point', path,
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 335, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 323, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 303, in gevent._gevent_cevent.AsyncResult._raise_exception
File "/var/lib/volttron/env/lib/python3.8/site-packages/gevent/_compat.py", line 66, in reraise
raise value
volttron.platform.jsonrpc.RemoteError: builtins.AttributeError("'DriverAgent' object has no attribute 'interface'")
2021-06-15 14:36:27,600 (setteroccvavagent-0.1 471606) volttron.platform.vip.agent.core ERROR: unhandled exception in periodic callback
Traceback (most recent call last):
File "/var/lib/volttron/volttron/platform/vip/agent/core.py", line 117, in _loop
method(*self.args, **self.kwargs)
File "/home/volttron/.volttron/agents/9c13ec66-7d7a-4f3d-a607-409a82e012ed/setteroccvavagent-0.1/setteroccvav/agent.py", line 252, in raise_setpoints_up
dr_level = self.vip.rpc.call('platform.actuator','get_point', dr_topic, point="signal_payload").get(timeout=4)
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 335, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 305, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 323, in gevent._gevent_cevent.AsyncResult.get
File "src/gevent/event.py", line 303, in gevent._gevent_cevent.AsyncResult._raise_exception
File "/var/lib/volttron/env/lib/python3.8/site-packages/gevent/_compat.py", line 66, in reraise
raise value
volttron.platform.jsonrpc.RemoteError: volttron.platform.jsonrpc.RemoteError('builtins.AttributeError("\'DriverAgent\' object has no attribute \'interface\'")')
A: driver = DriverAgent(self, contents, slot, self.driver_scrape_interval, topic,
group, self.group_offset_interval,
self.publish_depth_first_all,
self.publish_breadth_first_all,
self.publish_depth_first,
self.publish_breadth_first)
gevent.spawn(driver.core.run)
self.instances[topic] = driver
When the Platform Driver's configure method is called (which happens during a callback from the config store), the Platform Driver creates a driver instance with an interface class per the config that was passed. If the config that was passed is somehow incorrect or improperly passed, then the Platform Driver will be unable to actually instantiate the driver, and therefore it will not be added to the "self.instances" dictionary (above). When you make a call to the Platform Driver, you include a topic. That path MUST match the key that maps to the driver instance value in the "self.instances" dictionary.
As such, I have a couple of spots to suggest investigating. 1) Re-load the configs into the config store and watch the VOLTTRON log file as you do so. If you do not see a dictionary representation of the config file in the VOLTTRON log (while running in verbose logging mode) then you have likely given it an improperly formatted config. 2) Double check the topic you're using in your RPC calls. If the topic is not in the "self.instances" dictionary, it will throw an error as it's asking for a key that does not exist.
The configs you have posted above appear to me to be correct, so the topic in the RPC call or the commands used to store the configs appear to me to be the most likely culprits.
A: Actually what seemed to fix this is I restarted the actuator agent, bacnet proxy, and masteragent all at the same time. Was it maybe the master agent that needed a restart?
UPDATE
IF YOU HAD TO CHANGE SOMETHING IN THE CONFIG STORE FOR A DEVICE, for example make a BACnet point writeable instead of read ONLY; and something got fat fingered incorrectly this will ALSO CAUSE THE SAME ERROR! And also hard to troubleshoot.
For example on a live system if you had to modify something like this through vctl:
vctl config edit platform.driver registry_configs/1100.csv
And you create a syntax error with a fat finger this will also throw the same error!!!!!
| |
doc_23530476
|
Would flatten help? Looks so to me, but I just cannot get it working. Take a look how far I am now at https://jqplay.org/s/6bxD-Wq0QE, anyone can make it working?
BTW,
*
*.data.search.edges[].node | {name, topics: ..|.topics?} works, but I want all topics from the same node to be in one array, instead of having same name in all different returned results.
*flatten alone will give me Cannot iterate over null, and
*that's why I'm trying to use map(select(.? != null)) to filter the nulls out. However, I'd get Cannot iterate over null as well for my map-select.
So now it all comes down to how to filter out those nulls?
UPDATE:, by "collect into a single array" I meant to get something like this:
[
{
"name": "leumi-leumicard-bank-data-scraper",
"topics": ["banking", "leumi", "api", "puppeteer", "scraper", "open-api"]
}
]
instead of having same name duplicated in all different returned results. Thus recursively descends seems to me to be the option, but I'm open to any solution as long as I can get result like above. Is that possible? Thx.
A: Not sure what you're expecting to get in your results... but it seems like you're trying to get all the repositories and their topics in a flat array. I don't see any reason why you should use recurse here, you're only selecting from one class of objects. Just reference them directly.
[.data.search.edges[].node | {name,topic:(.repositoryTopics.nodes[].topic.topics)}]
For your particular input produces:
[
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "banking"
},
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "leumi"
},
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "api"
},
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "puppeteer"
},
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "scraper"
},
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": "open-api"
}
]
https://jqplay.org/s/G2inYAJNLS
If you wanted to have an array of topics within the nodes instead, just collect them in an array by putting the filter that selects the topics within [].
[.data.search.edges[].node | {name,topic:[.repositoryTopics.nodes[].topic.topics]}]
[
{
"name": "leumi-leumicard-bank-data-scraper",
"topic": [
"banking",
"leumi",
"api",
"puppeteer",
"scraper",
"open-api"
]
},
{
"name": "echarts-scrappeteer",
"topic": []
}
]
https://jqplay.org/s/0AFneNK89i
A: One way to collect the non-falsey values:
.data.search.edges[].node
| {name, topics: [.. | .topics? | select(.)]}
The result would be:
{
"name": "leumi-leumicard-bank-data-scraper",
"topics": [
"banking",
"leumi",
"api",
"puppeteer",
"scraper",
"open-api"
]
}
{
"name": "echarts-scrappeteer",
"topics": []
}
| |
doc_23530477
|
There is an Access table that is displayed in the datagrid in wpf. I'm trying to change the data in wpf so that they write to the access table, but I get an error. Did by analogy with localdb Code below
var accessUpdate = $@"UPDATE ORDERS SET
email = @emailAccess,
product_number = @product_number,
product_name = @product_name
WHERE Id = @idAccess";
daAccess.UpdateCommand = new OleDbCommand(accessUpdate, accessConnection);
daAccess.UpdateCommand.Parameters.Add("@emailAccess", OleDbType.WChar, 0, "email");
daAccess.UpdateCommand.Parameters.Add("@product_number", OleDbType.WChar, 0, "product_number");
daAccess.UpdateCommand.Parameters.Add("@product_name", OleDbType.WChar, 0, "product_name");
wpf
<DataGrid x:Name="gridViewAccess"
ItemsSource="{Binding}"
CurrentCellChanged="ChangedAccess"
CellEditEnding="ChangedEndingAccess"
AutoGenerateColumns="False"
CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="idAccess"
Binding="{Binding Id}"
Header="Id"
IsReadOnly="True"/>
<DataGridTextColumn x:Name="emailAccess"
Binding="{Binding email}"
Header="email"/>
<DataGridTextColumn x:Name="product_number"
Binding="{Binding product_number}"
Header="ΠΠΎΠ΄ ΡΠΎΠ²Π°ΡΠ°"/>
<DataGridTextColumn x:Name="product_name"
Binding="{Binding product_name}"
Header="ΠΠ°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅ ΡΠΎΠ²Π°ΡΠ°"/>
</DataGrid.Columns>
ChangedAccess and ChangedEndingAccess
private void ChangedAccess(object sender, EventArgs e)
{
if (drAccess == null) return;
drAccess.EndEdit();
daAccess.Update(dtAccess);
}
private void ChangedEndingAccess(object sender, DataGridCellEditEndingEventArgs e)
{
drAccess = (DataRowView)gridViewAccess.SelectedItem;
drAccess.BeginEdit();
}
DataTable dtAccess;
OleDbDataAdapter daAccess;
DataRowView drAccess;
if i add daAccess.UpdateCommand.Parameters.Add("@idAccess", OleDbType.Integer, 0, "Id");
The error "Data type mismatch in criteria expression."
id type is integer
id field properties
how can i fix this
| |
doc_23530478
|
>>> pattern = re.compile(r'^<HTML>')
>>> pattern.match("<HTML>")
<_sre.SRE_Match at 0x1043bc8b8>
>>> pattern.match("β’ β’ <HTML>", 2) # β’ stands for whitespace character.
None
When we are using ^ metacharacter and matching pattern then any whitespace character at the beginning as given below doesn't give a match even if the
'pos' argument is equal to 2, and the reason being given was that the
metacharacter ^ couldn't be matched in such cases( < is at position 2, and it cannot be matched with ^).
>>> pattern = re.compile(r'<HTML>$')
>>> pattern.match("<HTML>β’", 0,6) # β’ stands for whitespace character.
<_sre.SRE_Match object at 0x1007033d8>
>>> pattern.match("<HTML>β’"[:6])
<_sre.SRE_Match object at 0x100703370>
But, when we are using $ at the end of regular expression and giving the 'end' argument there is a match? Why the difference?
A: You'd have to dig a little into the docs, but the answer lies there. You will find the following information in the docs for pattern.search, the same description applies to pattern.match as well.
The optional second parameter pos gives an index in the string where
the search is to start; it defaults to 0. This is not completely
equivalent to slicing the string; the '^' pattern character matches at
the real beginning of the string and at positions just after a
newline, but not necessarily at the index where the search is to
start.
So, this means the SOL anchor ^ will match from the true beginning of the string (and not from the position dictated by pos. OTOH,
The optional parameter endpos limits how far the string will be
searched; it will be as if the string is endpos characters long, so
only the characters from pos to endpos - 1 will be searched for a
match.
Emphasis mine. Meaning that a pattern with the EOL anchor ^ will actually match upto endpos only (unlike pos).
| |
doc_23530479
|
I have an activerecord People, with attributes a,b,c. How can I do indexing only when b equals "type1", not indexing otherwise?
Currently what I know is
def search_data
{
a:a,
b:b,
c:c,
}
end
A: A bit late but a teammate came up through this question earlier today and I think the topic deserves a more detailed answer.
As far as I can tell, you have two options to control which records are indexed by searchkick:
*
*At the class level, you can limit the records searchkick index by defining an ActiveRecord scope search_import. This scope is used, essentially, when indexing multiple records at once, like when running searchkick:reindex task.
*At the instance level, you can define a should_index? method which gets called on every record just before indexing, it determines whether a record should be added or removed from the index.
So, if you want to index only records that have b equals 'type1' you could do something like below:
class People < ApplicationRecord
scope :search_import, -> { where(b: 'type1') }
def should_index?
b == 'type1'
end
end
Note that returning false from should_import? will remove the record form the index as you can read here.
A: Per the docs:
By default, all records are indexed. To control which records are indexed, use the should_index? method together with the search_import scope.
This should work for your case:
class People < ApplicationRecord
searchkick # you probably already have this
scope :search_import, -> { where(b: "type1") }
def should_index?
self.search_import # only index records per your `search_import` scope above
end
def search_data # looks like you already have this, too
{
a:a,
b:b,
c:c,
}
end
end
A: If you want to use the :search_import scope in should_index?, as seen in BigRon's answer above, you need to access the scope via self.class.search_import.
class People < ApplicationRecord
searchkick # you probably already have this
scope :search_import, -> { where(b: "type1") }
def should_index?
self.class.search_import # only index records per your `search_import` scope above
end
def search_data # looks like you already have this, too
{
a:a,
b:b,
c:c,
}
end
end
| |
doc_23530480
|
e.g Table_A
col
------
aaa
bbb
aaa
ccc
e.g Table_B
aaa
ccc
ddd
bbb
and likewise similar data for Table_C. I want to have the following as the result:
aaa 3
bbb 2
ccc 2
ddd 1
Currently, I have this
select col, count(*) from Table_A UNION select col, count(*) from Table_B UNION select col, count(*) from Table_C group by col order by count(*) desc
But this does not give me the results I wanted. thanks
A: select col
,count(*) as cnt
from ( select col from Table_A
union all select col from Table_B
union all select col from Table_C
) t
group by col
order by cnt desc
,col
;
OR
select col
,sum(cnt) as sum_cnt
from ( select col,count(*) as cnt from Table_A group by col
union all select col,count(*) from Table_B group by col
union all select col,count(*) from Table_C group by col
)
group by col
order by sum_cnt desc
,col
;
A: First, use union all, then do the aggregation. The correct syntax is:
select col, count(*) as cnt
from (select col from Table_A
union all
select col from Table_B
union all
select col from Table_C
) abc
group by col
order by col;
You can also pre-aggregate the data, but you need to aggregate again:
select col, sum(cnt) as sum_cnt
from (select col, count(*) as cnt from Table_A group by col
union all
select col, count(*) from Table_B group by col
union all
select col, count(*) from Table_C group by col
) abc
group by col
order by col;
A: Each select needs its own group by-clause.
select col, count()
from Table_A
group by col
UNION
select col, count()
from Table_B
group by col
UNION
select col, count(*)
from Table_C
group by col
order by 2 desc;
| |
doc_23530481
|
I need to be able to find the WebView that Phonegap uses when it calls:
super.loadUrl("file:///android_asset/www/index.html");
I've tried creating a new WebView in the main.xml file and loading the index.html page into it which only causes a Null Pointer Exception.
Any help would be great.
///
Edit:
The code below appears to now actually take a screenshot of the view as the file has a size of 823bytes..however, it is displaying as just a black image, nothing is shown..
Could this be to it taking a screenshot too quickly, before the view is loaded? or am I doing something else wrong?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
View html = (View)super.appView.getParent();
Bitmap bm2 = Bitmap.createBitmap(200, 300, Bitmap.Config.ARGB_8888);
Canvas c2 = new Canvas(bm2);
html.draw(c2);
OutputStream stream = null;
try {
stream = new FileOutputStream(Environment.getExternalStorageDirectory() +"/bm2.png");
bm2.compress(CompressFormat.PNG, 80, stream);
if (stream != null) stream.close();
} catch (IOException e) {
} finally {
bm2.recycle();
}
}//end
A: I had the same question--how do I get a reference to the WebView - so I will post my solution for posterity (and so I can find it again in the future).
Looking at https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaActivity.java, the WebView used appears to be the protected variable appView, which is accessible from your main Android class. So just use the appView variable.
A: If I had to guess, WebView doesn't honor the drawing cache.
Try using capturePicture(), then rendering that Picture to a Bitmap-backed Canvas, and saving the resulting bitmap. See:
*
*Generate bitmap from HTML in Android
*Capture picture from android webview
| |
doc_23530482
|
The code works. However, it seems as though I'm repeating myself unnecessarily. In particular, the only operations that differs between the queue and the stack is the push operation (do we push new objects onto the front or the back of the list?). It seems as though there should be some way to define the common operations in the typeclass definition. Is that, in fact, possible?
module Queue (
Queue,
FifoQueue(FifoQueue),
Stack(Stack),
empty,
isEmpty,
push,
pop,
top
) where
class Queue q where
empty :: q a
isEmpty :: q a -> Bool
push :: a -> q a -> q a
pop :: q a -> (a, q a)
top :: q a -> a
data Stack a = Stack [a] deriving (Show, Eq)
instance Queue Stack where
empty = Stack []
isEmpty (Stack xs) = null xs
push x (Stack xs) = Stack (x:xs)
pop (Stack xs) = (head xs, Stack (tail xs))
top (Stack xs) = head xs
data FifoQueue a = FifoQueue [a] deriving (Show, Eq)
instance Queue FifoQueue where
empty = FifoQueue []
isEmpty (FifoQueue xs) = null xs
push x (FifoQueue xs) = FifoQueue (xs ++ [x])
pop (FifoQueue xs) = (head xs, FifoQueue (tail xs))
top (FifoQueue xs) = head xs
A: Well, there is just a small amount of duplication, but lets get rid of it.
The key is that we can provide a defaults to Queue given that we know how to turn it into a list, furthermore provided with a queue we can make a list. Therefor we just add two functions to your definition, toList and fromList, and make sure that either giving toList and fromList, or giving the other functions, make a complete definition.
import Control.Arrow
class Queue q where
empty :: q a
empty = fromList []
isEmpty :: q a -> Bool
isEmpty = null . toList
push :: a -> q a -> q a
push a b = fromList (a : toList b)
pop :: q a -> (a, q a)
pop qs = (head . toList $ qs,fromList . tail . toList $ qs)
top :: q a -> a
top = head . toList
toList :: q a -> [a]
toList queue = if isEmpty queue then []
else uncurry (:) . second toList . pop $ queue
fromList :: [a] -> q a
fromList = foldr push empty
As you can see, any implementation of queue either has to provide toList and fromList or
the other functions, and so the implementations of your two queues become the following:
data Stack a = Stack [a] deriving (Show, Eq)
instance Queue Stack where
toList (Stack a) = a
fromList a = Stack a
data FifoQueue a = FifoQueue [a] deriving (Show, Eq)
instance Queue FifoQueue where
toList (FifoQueue a) = a
fromList a = FifoQueue a
push x (FifoQueue xs) = FifoQueue (xs ++ [x])
A: You can shave off the two implementations for top if you add a default implementations in the Queue type class:
top = fst . pop
but besides that, I don't think there's much to do here. There isn't a lot of duplication, anyway.
A: It seems the "duplication" you are concerned about is the similarity in some of the implementation:
instance Queue Stack where
empty = Stack []
isEmpty (Stack xs) = null xs
...
instance Queue FifoQueue where
empty = FifoQueue []
isEmpty (FifoQueue xs) = null xs
...
But sadly, there just isn't a way to merge parts of these two instances. You could remove the typeclass, and simply have Stack and FifoQueue be two different constructors of the same type. From here, HaskellElephant's solutions mostly apply (substituting toList with lst).
data Queue a = Stack { lst :: [a] }
| FifoQueue { lst :: [a] }
deriving (Eq, Show)
-- "empty" obviously cannot be preserved as it was
-- you need to specify whether you want an empty Stack or empty FifoQueue
emptyS = Stack []
emptyQ = FifoQueue []
-- but some functions are the same either way
isEmpty = null . lst
top queue = head . lst
-- other functions behave *mostly* the same for both cases...
pop queue = (top queue, liftQ tail queue)
-- ...they just need a little helper to abstract over the slight difference
liftQ :: ([a] -> [b]) -> Queue a -> Queue b
liftQ f (Stack xs) = Stack (f xs)
liftQ f (FifoQueue xs) = FifoQueue (f xs)
-- then for functions where the implementation is completely different,
-- you just pattern match
push x (Stack xs) = Stack (x:xs)
push x (FifoQueue xs) = FifoQueue (xs ++ [x]) -- this is slow, by the way
The drawback to this, of course, is that instead of an open typeclass, your module now provides a closed ADT.
There is some middle ground, though. Sort of. Consider this alternate approach:
data QueueImpl q a = QueueImpl { _empty :: q a
, _isEmpty :: q a -> Bool
, _top :: q a -> a
, _pop :: q a -> (a, q a)
, _push :: a -> q a -> q a
}
-- partially applied constructor!
shared :: (a -> [a] -> [a]) -> QueueImpl [] a
shared = QueueImpl empty' isEmpty' top' pop'
where empty' = []
isEmpty' = null
top' = head
pop' (x:xs) = (x, xs)
stack :: QueueImpl [] a
stack = shared push'
where push' = (:)
fifoQueue :: QueueImpl [] a
fifoQueue = shared push'
where push' x = (++[x])
By turning the typeclass into a data type, we are able to partially apply the constructor, thus sharing implementations for most of the methods. The catch is that we don't have access to functions that are polymorphic in the same way as before. To access the methods we need to do top stack or top fifoQueue. This leads to some interesting changes in designing "polymorphic" functions: since we reified the typeclass, we need to pass in an implementation explicitly to any compound functions:
-- if you haven't figured out by now, "impl" is short for "implementation"
_push3 :: QueueImpl [] a -> a -> [a] -> [a]
_push3 impl x = push x . push x . push x
where push = _push impl
-- _push3 as implemented by a stack:
sPush3 :: a -> [a] -> [a]
sPush3 = _push3 stack
Note that we lose out on some type safety here; the representation of both a Stack and FifoQueue is exposed as a raw list. There might be some newtype hackery that could make this a little safer. The takeaway message is this: each approach has its own advantages and drawbacks. Typeclasses are a Pretty Good Idea, but don't confuse them for a Silver Bullet; be aware of other options, such as these.
| |
doc_23530483
|
*
*keras code of mean squared error use return mean -> 1 / N -> is N batchsize?
*keras code of categorical crossentropy use return reduce_sum -> 1. I remember categorical crossentropy also need divided by batchsize.
Please explain this.
This is code of mean squared error:
def mean_squared_error(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
This is code of categorical cross entropy:
def categorical_crossentropy(target, output, from_logits=False, axis=-1):
"""Categorical crossentropy between an output tensor and a target tensor.
# Arguments
target: A tensor of the same shape as `output`.
output: A tensor resulting from a softmax
(unless `from_logits` is True, in which
case `output` is expected to be the logits).
from_logits: Boolean, whether `output` is the
result of a softmax, or is a tensor of logits.
axis: Int specifying the channels axis. `axis=-1`
corresponds to data format `channels_last`,
and `axis=1` corresponds to data format
`channels_first`.
# Returns
Output tensor.
# Raises
ValueError: if `axis` is neither -1 nor one of
the axes of `output`.
"""
output_dimensions = list(range(len(output.get_shape())))
if axis != -1 and axis not in output_dimensions:
raise ValueError(
'{}{}{}'.format(
'Unexpected channels axis {}. '.format(axis),
'Expected to be -1 or one of the axes of `output`, ',
'which has {} dimensions.'.format(len(output.get_shape()))))
# Note: tf.nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
# scale preds so that the class probas of each sample sum to 1
output /= tf.reduce_sum(output, axis, True)
# manual computation of crossentropy
_epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
output = tf.clip_by_value(output, _epsilon, 1. - _epsilon)
return - tf.reduce_sum(target * tf.log(output), axis)
else:
return tf.nn.softmax_cross_entropy_with_logits(labels=target,
logits=output)
def categorical_crossentropy(y_true, y_pred):
return K.categorical_crossentropy(y_true, y_pred)
| |
doc_23530484
|
Vertical viewport was given unbounded height.
I tried to use flexible on GridView it worked but I need to use GridView.Builder Specifically
and if I tried to wrap it with Flexible or specific height container it doesn't scroll ,any tips?
import 'package:flutter/material.dart';
class Products extends StatefulWidget {
@override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
var productList=[
{
"name":"Blazer",
"picture":"images/products/blazer1.jpeg",
"oldPrice":120,
"price":100
},
{
"name":"Dress",
"picture":"images/products/dress1.jpeg",
"oldPrice":120,
"price":100
},
{
"name":"hills",
"picture":"images/products/hills1.jpeg",
"oldPrice":11,
"price":10
},
{
"name":"pants",
"picture":"images/products/pants2.jpeg",
"oldPrice":12,
"price":200,
}
];
@override
Widget build(BuildContext context) {
return GridView.builder(
scrollDirection: Axis.vertical,
itemCount: productList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (context,index){
return SingalProduct(
name: productList[index]['name'],
picture: productList[index]['picture'],
oldPrice: productList[index]['oldPrice'],
price: productList[index]['price'],
);
},
);
}
}
class SingalProduct extends StatelessWidget {
final name,picture,oldPrice,price;
SingalProduct({this.name,this.picture,this.oldPrice,this.price});
@override
Widget build(BuildContext context) {
return Card(
child: Hero(
tag: name,
child: InkWell(
onTap: (){},
child: GridTile(
footer: Container(
height: 40,
color: Colors.white,
child: Padding(
padding: EdgeInsets.fromLTRB(8, 12, 0, 0),
child: Text(name,textAlign: TextAlign.start,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),),
),
),
child: Image.asset(picture,fit: BoxFit.cover, ),
),
),
),
);
}
}
| |
doc_23530485
|
I have a field with a currency ( β¬ 245,78 ) and I can't read with my tool.
If I use this code:
$get_data_ab = utf8_encode($data->val(4,6,$sheet_def));
the result is:
Β¬ 246246246246.246246
If I use:
$get_data_ab = $data->val(4,6,$sheet_def);
the result is empty.
What is wrong? How can I charge the β¬ values in a variable?
A: After many researches i found the fix method, i paste it here for who encounter the same problem.
The first thing to do is "add" a true value to the definition of the file:
$data = new Spreadsheet_Excel_Reader($nome_file,true);
After for read a custom number as β¬ 245,78 you have to use this
$get_data_ab = number_format($data->raw(4, 6, $sheet_def), 2);
Hope it helps someone !
| |
doc_23530486
|
HTML
<body>
<canvas id="bg_canvas" width="" height=""></canvas>
</body>
jQuery
// Expand canvas to full viewport size
var vp_width = window.clientWidth;
var vp_height = window.clientHeight;
$("#bg_canvas").css({
"width" : vp_width,
"height" : vp_height
});
// Canvas Drawing
var canvas = document.getElementById("bg_canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle="#cbf7ed";
ctx.fillRect(100,100,vp_width,100);
Also tried the Javascript window.innerheight and window.innerWidth, but that also creates scrollbars.
A: The default browser stylesheet is likely giving the <body> element a margin. Because, the canvas is within the body, that would make the canvas larger than its parent, creating a scrollable view.
If you want the canvas to span the width of the window, remove margin and padding from the body element via CSS. You can verify this with inline styling: <body style="margin:0 padding:0"> (though its generally best practice to place styling in discrete files or at least in the html header).
Alternatively, if you want the canvas to span the body, use something like:
var vp_width = $('body').innerWidth;
var vp_height = $('body').innerHeight;
| |
doc_23530487
|
*
*The completion of a state inserts a "completion event" at the beginning of the event queue and the "completion transition" is thus only executed then the state machine is explicitly stepped, OR
*completion of a state immediately triggers the "completion transition" (and possibly subsequent "completion transitions") and the state machine thus may execute multiple steps for each explicit stepping.
Both cases suggest, that a state's unguarded "completion transition" effectively makes any other defined transitions (whether event-triggered or guarded) redundant.
Am I understanding this correctly?
A: The answer is closer to #2 ('completion of a state immediately triggers the "completion transition"'), but you then mention "multiple steps for each explicit stepping." I don't know what you mean by that.
The UML 2.5 spec, in section 14.2.38.3, says:
A special kind of Transition is a completion Transition, which has an implicit trigger. The event that enables this trigger
is called a completion event and it signifies that all Behaviors associated with the source State of the completion
Transition have completed execution. In case of simple States, a completion event is generated when the associated entry
and doActivity Behaviors have completed executing. If no such Behaviors are defined, the completion event is generated
upon entry into the State.
The spec goes on to describe how a completion event is generated for composite or submachine states. Since you're asking about this simpler case, I'll skip that.
The spec also says "Completion events have dispatching priority. That is, they are dispatched ahead of any pending Event occurrences in the
event pool." Thus, other defined transitions are not dispatched.
| |
doc_23530488
|
HTML:
<table width="700" align="center" class="ui-corner-bottom background_grey border_bottom_blue border_left_blue border_right_blue">
<tbody>
<tr>
<td valign="top"><table width="600" align="center" style="margin-top: 25px;" class="ui-corner-all background_white border_all_grey" id="line_items">
<thead>
<tr>
<th align="left">Property</th>
<th align="left">Account Number</th>
<th align="left">Description</th>
<th align="left" colspan="2">Total Amount</th>
</tr>
</thead>
<tbody>
<tr style="display: block;" id="clone_me">
<td align="left"><input type="text" onclick="new_edit_area('modal_popup_detail', 'HTML_bills_new', '', 'modal_popup_detail', 'html.acctg.bills.php', 'sql_acctg_bills.php');$('#modal_popup_detail').dialog('option','width',800).dialog('option','title', 'Property - Add').dialog('open');" class="item_detail" id="property_id" title="no"></td>
<td align="left">
<select class="input_editable_white item_detail" name="acctg_chart_of_accounts_id_n" id="acctg_chart_of_accounts_id">
<option selected="selected" value="1">1100 - Management Operating Account</option>
<option value="2">1101 - Petty Cash</option>
<option value="3">1102 - Security Deposit Account</option>
<option value="4">1103 - Trust Account</option>
<option value="5">1104 - Credit Card</option>
<option value="6">1200 - Accounts Receivable</option>
<option value="7">1201 - Accounts Payable</option>
<option value="8">1300 - Mortgage Escrow</option>
<option value="9">1301 - Undeposited Funds</option>
<option value="10">1400 - Mortgage Principal</option>
<option value="11">1401 - Pet Deposit</option>
<option value="12">1402 - Security Deposit</option>
<option value="13">1500 - Bank Transfer</option>
<option value="14">1501 - Owner Contribution</option>
<option value="15">1502 - Owner Draw</option>
<option value="16">1600 - Adjustment</option>
<option value="17">1601 - Application Fee</option>
<option value="18">1602 - Bank Interest</option>
<option value="19">1603 - Common Area Maintenance</option>
<option value="20">1604 - Convenience Fee</option>
<option value="21">1605 - Discount/Promotion</option>
<option value="22">1606 - Fee for Bounced Check</option>
<option value="23">1607 - HOA Fees</option>
<option value="24">1608 - Late Fee</option>
<option value="25">1609 - Laundry Room</option>
<option value="26">1610 - Maintenance Fee</option>
<option value="27">1611 - Management Income</option>
<option value="28">1612 - Management Income - Cleaning</option>
<option value="29">1613 - Opening Balance</option>
<option value="30">1614 - Prepayments</option>
<option value="31">1615 - Refunds</option>
<option value="32">1616 - Rent</option>
<option value="33">1617 - Sales Tax Due</option>
<option value="34">1618 - Security Deposit Forfeit</option>
<option value="35">1619 - Taxes Due</option>
<option value="36">1620 - Utilities</option>
<option value="37">1621 - Utility Charge</option>
<option value="38">1700 - Advertising</option>
<option value="39">1701 - Bad Debt/Uncollectible</option>
<option value="40">1702 - Bank Fees</option>
<option value="41">1703 - Cleaning and Maintenance</option>
<option value="42">1704 - Common Area Maintenance</option>
<option value="43">1705 - Insurance</option>
<option value="44">1706 - Leasing Fee</option>
<option value="45">1707 - Legal and Professional</option>
<option value="46">1708 - Management Fees</option>
<option value="47">1709 - Mortgage Interest</option>
<option value="48">1710 - Other Interest</option>
<option value="49">1711 - Reconciliation Discrepencies</option>
<option value="50">1712 - Repairs</option>
<option value="51">1713 - Repairs-Upgrades</option>
<option value="54">1713 - Utility Expense</option>
<option value="52">1714 - Supplies</option>
<option value="53">1715 - Tax Expense</option>
</select></td>
<td align="left"><input type="text" style="width: 20px;" class="input_editable_white item_detail" title="no" name="description_n" id="description"></td>
<td align="left"><input type="text" style="width: 20px;" class="input_editable_white item_detail" name="amount_curr_n" title="no" id="amount_curr"></td>
<td align="right"><img width="10" height="10" class="a_hand" onclick="$(this).parent().parent().remove();" title="Remove" src="images/delete.png"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="left" colspan="5"><img onclick="add_item();" class="a_hand" title="Add" src="images/plus_green.png"></td>
</tr>
</tfoot>
</table>
</td>
</tr>
<tr>
<td valign="bottom" align="right"><span onclick="var xx=update_new('xml/xml_update_db.php', 'bill_info_main', 'SQL_insert_one_bill', 'new', 'sql_acctg_bills.php','true'); update_multi_row('xml/xml_update_db.php', '', 'item_detail', 'SQL_insert_bill_item_detail', 'new', 'sql_acctg_bills.php','acctg_bill_id',xx,,true); display_html('xml/display_html.php', 'main_container', 'HTML_bills_display','SQL_SELECT_all_bills', '', '', 'html.acctg_bills.php', 'sql_acctg_bills.php');" title="Add"><span class="universal_pad"><span class="a_hand FIELD_name button_text_bg ui-corner-all">Add</span></span></span></td>
</tr>
</tbody>
</table>
A: The display value for the tr tag should not be block. Change it to table-row, and your table should be fine.
A: Replace
<th align="left">
with
<th style="text-align:left;">
| |
doc_23530489
|
The above line of code statement shows false.
Even though 8 is an int.
How does this work?
I would like to know how is operator works in this case.
Thank you.
A: just a small mistake in your syntax. You should have written type(8) is int in your condition statement which is the correct syntax. type(object) returns the class of the object so you can compare it with the is operator. So for example:-
Bonjour is an object of class Greeting
So the following code:-
if type(Bonjour) is Greeting:
print("Bonjour is a Greeting!")
would print out:-
Bonjour is a Greeting
| |
doc_23530490
|
List<String> objects = Arrays.asList(arr);
long northCount = (objects.contains("NORTH")) ? objects.stream().filter("NORTH"::contains).count() : 0;
long southCount = (objects.contains("SOUTH")) ? objects.stream().filter("SOUTH"::contains).count() : 0;
long eastCount = (objects.contains("EAST")) ? objects.stream().filter("EAST"::contains).count() : 0;
long westCount = (objects.contains("WEST")) ? objects.stream().filter("WEST"::contains).count() : 0;
Map<String, Long> doubleBraceMap = new HashMap<String, Long>() {{
put("NORTH", (long)((northCount >= southCount) ? (northCount - southCount) : 0));
put("SOUTH", (long)((southCount >= northCount) ? (southCount - northCount) : 0));
put("EAST", (long)((eastCount >= westCount) ? (eastCount - westCount) : 0));
put("WEST", (long)((westCount >= eastCount) ? (westCount - eastCount) : 0));
}};
List<String> formattedArray = new ArrayList<String>();
doubleBraceMap.keySet().forEach(key ->{
for(int i = 0; i < doubleBraceMap.get(key); i++) {
formattedArray.add(key);
}
});
return formattedArray.toArray(new String[0]);
}
the code above simplifies the locations BUT not in order, in order being that the positions of the elements don't change only redundant movements do, for example {"SOUTH", "NORTH", "EAST"} becomes "EAST" as south and north cancel out, my algorithm above doesnt look at positions, it just simplifies it by calculating the number of souths, norths etc, then doing some basic maths. PS, i'd like this problem to be solved without nested loops, if possible.
Problem,
Write a function dirReduc which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side).
A: Seriously, use a plain old for-each loop:
public static String[] dirReduc(String[] arr) {
int northsouth = 0, eastwest = 0;
for (String dir : arr) {
switch (dir) {
case "NORTH" -> northsouth++;
case "EAST" -> eastwest++;
case "SOUTH" -> northsouth--;
case "WEST" -> eastwest--;
}
}
int size = Math.abs(northsouth) + Math.abs(eastwest);
String[] result = new String[size];
if (northsouth > 0) {
Arrays.fill(result, 0, northsouth, "NORTH");
} else {
Arrays.fill(result, 0, -northsouth, "SOUTH");
}
if (eastwest > 0) {
Arrays.fill(result, size-eastwest, size, "EAST");
} else {
Arrays.fill(result, size+eastwest, size, "WEST");
}
return result;
}
No need to get fancy here.
| |
doc_23530491
|
var elem = document.getElementById('scroll-area'),
track = elem.children[1],
thumb = track.children[0],
height = parseInt(elem.offsetHeight, 10),
cntHeight = parseInt(elem.children[0].offsetHeight, 10),
trcHeight = parseInt(track.offsetHeight, 10),
distance = cntHeight - height,
mean = 50, // For multiplier (go faster or slower)
current = 0;
elem.children[0].style.top = current + "px"; // Set default `top` value as `0` for initiation
thumb.style.height = Math.round(trcHeight * height / cntHeight) + 'px'; // Set the scrollbar thumb hight
var doScroll = function (e) {
// cross-browser wheel delta
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
// (1 = scroll-up, -1 = scroll-down)
// Always check the scroll distance, make sure that the scroll distance value will not
// increased more than the content height and/or less than zero
if ((delta == -1 && current * mean >= -distance) || (delta == 1 && current * mean < 0)) {
current = current + delta;
}
// Move element up or down by updating the `top` value
elem.children[0].style.top = (current * mean) + 'px';
thumb.style.top = 0 - Math.round(trcHeight * (current * mean) / cntHeight) + 'px';
e.preventDefault();
};
if (elem.addEventListener) {
elem.addEventListener("mousewheel", doScroll, false);
elem.addEventListener("DOMMouseScroll", doScroll, false);
} else {
elem.attachEvent("onmousewheel", doScroll);
}
And the markup:
<div id="scroll-area">
<div><!-- CONTENT --></div>
<span class="scrollbar-track"><span class="scrollbar-thumb"></span></span>
</div>
My problem is on mean = 50. When you scroll the container until the bottom of content, the red line that I made in the demo page should stop right at the bottom of the container, not higher than that.
Anyone have an idea for the accurate result?
PS: I also want to add a function that will enable user to scroll the content by dragging the scrollbar thumb. But I think I want to focus on this issue first. Thanks for your help.
DEMO: http://jsfiddle.net/tovic/2B8Ye/
A: You could have done this much much easier.
Instead of calculating the top property for the container you can set its scrollTop property, and you guess what - you don't have to check if the content moves upper than 0 or lower than height because scrollTop property can not be set to a value smaller than 0 or greater than container's height!
Here's your modified fiddle
Notice that I had to wrap everything with additional <div id="everything">...</div> so the scrollbar won't be scrolled together with the #scroll-area div.
Also I assume using clientHeight instead of offsetHeight for .scroll-content div to include padding in the cntHeight variable.
More info on the scrollTop property you can find in this article.
| |
doc_23530492
|
Up to now, I've set the TextLabel and DetailTextLabel text to be something really long (so that it'll take up the entirety of the width assigned to the blue labels), set the font to UIColor.Clear, and then taken their measurements each time they're rendered. That's horrible for lots of reasons, but it works in a fashion.
I'd like to accomplish this with a custom UIView and a custom Draw method. This is a prettier solution but now i'm missing a vital piece of information: the width of the area used to display a TextLabel. I could hard code it, which seems the accepted way to do things on iOS (even if it makes me feel dirty), but then I have to hard code it for iPad and iPhone both in Horizontal and Vertical orientations. And then it'd probably break as soon as my UITableView is plain instead of grouped, or somesuch.
Where can I get the standard, current width of this stupid label area?
Thanks!
A: Each UITableViewCell has a textLabel and a detailTextLabel. On UITableViewCellStyleValue2, the textLabel is on the left side and the detailTextLabel is on the right side. Thus, you can access the left label's area like this:
cell.textLabel.frame
and you can access the right label's area like so:
cell.detailTextLabel.frame
A: Have you thought about making the cell in Interface Builder and using a static UINib to load it? That seems fast enough for me, but I have not tested on anything slower then a 3GS.
If it is fast enough for your app I strongly recommend it, you will be able to make small (and large!) tweaks in the future with far less effort.
A: Just subclass a UIView, and inside your drawRect do the following.
- (void) drawRect:(CGRect)rect {
NSString *label = @"Label 1";
CGSize size = [label sizeWithFont:[UIFont boldSystemFontOfSize:12.0f]
constrainedToSize:CGSizeMake(self.frame.size.width, 100.0f)
lineBreakMode:UILineBreakModeCharacterWrap];
[label drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height) withFont:[UIFont boldSystemFontOfSize:12.0f]];
[super drawRect:rect];
}
| |
doc_23530493
|
Is there a way to do this or am I ahead of my time?
A: I think you could use the debug mode to see all methods called
A: Run DEBUG in your IDE, your each step in application will move you to the right place in the code, during your program you can see each variable value.
Also you can follow each code line which your code is doing.
http://www.vogella.com/tutorials/EclipseDebugging/article.html
Regards!
| |
doc_23530494
|
"Yowza, thatβs a big file. Try again with a file smaller than 25MB."
My project folder size is in Kb's even not in Mb's.
A: Try and list all the files of your current repository, sorted by size.
Chances are, you have, by mistake, included one large binary.
| |
doc_23530495
|
public class Item
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public ItemCategory Category { get; set; }
}
and an ItemCategory class:
public class ItemCategory
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Name { get; set; }
}
I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:
When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.
How do I achieve that?
A: I would create a function that gets or creates the unique ItemCategory. You did not post the full code so I am not sure how your repository looks like. But here is an idea:
// assuming _dbServices is the injected dbcontext
public void AddItem()
{
var item = _dbServices.Context.Entry(new Item()
{
Name = "First book",
Category = GetOrCreateItemCategory(new ItemCategory() { Name = "Book" })
}).State = EntityState.Added;
_dbServices.Context.SaveChanges();
}
public ItemCategory GetOrCreateItemCategory(ItemCategory category)
{
var findCategory = _dbServices.Context.Set<ItemCategory>().Where(x => x.ID == category.ID).FirstOrDefault();
if (findCategory == null)
{
_dbServices.Context.Entry(category).State = EntityState.Added;
_dbServices.Context.SaveChanges();
return category;
}
return findCategory;
}
I havent tested this but should be ok. If not, please comment and I would fix it.
Also I would create unique index for ItemCategory.Name field.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ItemCategory>()
.HasIndex(p => new { p.Name })
.IsUnique(true);
}
A: You must define foreign key property in the dependent entity class And when you add a new item, set the CategoryID instead of Category .
public class Item
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
public int CategoryID { get; set; }
public ItemCategory Category { get; set; }
}
A: Use a navigation property in the Item class.
public class ItemCategory
{
[Key]
public Guid ID { get; set;}
public string Name { get; set; }
}
public class Item
{
[Key]
public Guid ID { get; set; } // Primary Key
[Required]
public string Name { get; set; }
public virtual ItemCategory ItemCategory { get; set; } //Navigation Property
}
| |
doc_23530496
|
How can I recreate that font with the engraved look?
Thanks in advance for your help!
A: Simply set the shadow color to white:
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
| |
doc_23530497
|
Here is an example fiddle: https://jsfiddle.net/vn6t3nwd/
HTML:
<div id="timer-container">
<div id="timermode">up</div><div id="timermode">down</div>
<div id="timercontrol">stop</div>
<div id="timercontrol">go</div>
</div>
CSS:
#timer-container {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: table;
background-color: black;
}
#timermode {
position: absolute;
width: 30%;
font-family: "Avenir-Light";
font-size: 40px;
color: white;
vertical-align: top;
display: inline-block;
}
#timercontrol {
position: absolute;
display: inline-block;
font-size: 40px;
font-family: "Avenir-Light";
color: white;
}
Edit: The problem was having position: absolute, however removing it causes the height of my background to increase slightly. I think it is due to my 56.25% padding on the bottom but I need to have that. Anyway to have it both ways?
Edit2: Updated the fiddle with the answer. I got around my height increase by adding another container.
A: You have overlapping because of position: absolute;
Also, id is made to be unique identifier, if you need to use same css for multiple html elements you should define it as a class
HTML:
<div id="timer-container">
<div class="timermode">up</div>
<div class="timermode">down</div>
<div class="timercontrol">stop</div>
<div class="timercontrol">go</div>
</div>
CSS:
#timer-container {
...
}
.timermode {
...
}
.timercontrol {
...
}
A: I'm a young aspiring programmer so my answer may and may not help you. I think it's because of the position absolute. I edit your code in JSFiddel and notice that when I remove the absolute style it position all of the elements according to their relative position. Hope it helps. Happy coding.
A: Removing the absolute positioning of the child elements will allow them to display inline as intended. Also, as stated only use id attributes for unique elements, use classes for repeating elements as in the example below.
#timer-container {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: table;
background-color: black;
}
.timermode {
width: 30%;
font-family: "Avenir-Light";
font-size: 40px;
color: white;
vertical-align: top;
display: inline-block;
}
.timercontrol {
display: inline-block;
font-size: 40px;
font-family: "Avenir-Light";
color: white;
}
<div id="timer-container">
<div class="timermode">up</div>
<div class="timermode">down</div>
<div class="timercontrol">stop</div>
<div class="timercontrol">go</div>
</div>
| |
doc_23530498
|
(document.getElementById("ipv") as HTMLInputElement).value;
instead of:
document.getElementById("ipv").value;
?
A: The function getElementById returns object with type HTMLElement.
From lib.dom.d.ts:
/**
* Returns a reference to the first object with the specified value of the ID or NAME attribute.
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement | null;
HTMLElement type is the base type for the other tag types of the DOM.
For example, the type HTMLInputElement extends HTMLElement and have the property value that the type HTMLElement doesn't have.
From lib.dom.d.ts:
interface HTMLInputElement extends HTMLElement {
...
/**
* Returns the value of the data at the cursor's current position.
*/
value: string;
...
Since HTMLInputElement extends HTMLElement, the next lines can compile:
const inputTag = document.getElementById('name-input') as HTMLInputElement;
const value = inputTag.value;
A: document.getElementById() won't be able to return a specific element type since it doesn't know in advance what that element will be, so you need to cast the result as an HTMLInputElement after the fact so that the value property of that class can be recognized.
| |
doc_23530499
|
import pandas as pd
from matplotlib import pyplot as plt
n = 0.4
k = 53
d = 0.000264
r = 0.000132
p = 15000
u = (n/n+1)*(p*1/2*k)**(1/n)*(d**((n+1)/n) - r**((n+1)/n))
plt.plot(u)
Graph produced:
A: First off, note that (p*1/2*k) is a very confusing way to write a multiplication. In (about all) programming languages, the multiplications and divisions are done left to right, so, (p*1/2*k) equals (p*k/2) while perhaps you meant (p/(2*k)).
When plotting a 2D graph, you have to think what you want in the x direction, and what in the y direction. As you only give an x, there is nothing to plot. Also, plot default want to draw lines and for a line at least 2 xy pairs are needed. To only draw a point, plot accepts a third parameter, for example 'ro' to represent a red dot. Supposing u is meant to be the y direction and you don't have an x, you could give it a zero:
plt.plot(0, u, 'ro')
Now, probably you want to draw a curve of u for different values of some x. As in your equation there is no x nor a t, it is hard for me to know what you would like to see on the horizontal direction.
Let's suppose you want to show u as a function of d and that d goes from 0.0 to 0.0005. Typically, with numpy you create a sequence of values for d, lets say split into 200 small intervals: d = np.linspace(0.0, 0.0005, 200). Then, there is the magick of numpy, that when you write u = f(d), numpy makes an array for u with as many entries as d.
Example:
import numpy as np
from matplotlib import pyplot as plt
n = 0.4
k = 53
d = np.linspace(0.0, 0.0005, 200) # 0.000264
r = 0.000132
p = 15000
u = (n / n + 1) * (p * 1 / 2 * k) ** (1 / n) * (d ** ((n + 1) / n) - r ** ((n + 1) / n))
plt.plot(d, u)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.