id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23536800
|
GC::Profiler.enable
In my app. However when I call this in Jruby I am getting a
org.jruby.exceptions.RaiseException: (NameError) uninitialized
I know that the garbage collection is done in the JVM on Jruby - so this might be why it is not initialized Which makes sense, what is the alternative to use in Jruby?
A: That's a MRI specific API - there's not an API equivalent for JRuby probably due the way the JVM works (there are multiple GC strategies with most VMs and there's no consistent API to work with the GC, even a System.gc() call does not necessary trigger garbage-collection immediately).
But there's a standart monitoring API (called MX) available for Java applications and since your JRuby app is a Java app you can use those, of course you might need to understand some of the internals e.g. how your ruby classes are seen by the JVM, but it ain't that hard.
Try starting here: http://www.engineyard.com/blog/2010/monitoring-the-jvm-heap-with-jruby/
Here's a summary of Java tools available you can use with JRuby as well: http://blog.headius.com/2010/07/browsing-memory-jruby-way.html
Don't forget to check the wiki as well, e.g. there's a page on profiling object allocations:
https://github.com/jruby/jruby/wiki/Profiling-Object-Allocations
| |
doc_23536801
|
Everything in my component works fine, but the click event in this isolated component is behaving irregularly. By clicking .filter__toggle the .filter element which is rendered in renderHeader should change its class but it is not working on every click.
Here's the code, any ideas?
export default ({DOM, results$, props$}) => {
// what to show on start
const initialResults$ = props$.map(props => props.initial).first();
// data from the db
const newResults$ = results$.withLatestFrom(
props$,
(results, props) => _.filter(results, (o) => o.type === props.type )
);
// mix of initial and new values
const body$ = initialResults$.concat(newResults$);
// block title
const title$ = props$.map(props => props.title).first();
// click events from the filter toggler
const filter$ = DOM.select('.filter__toggle')
.events('click')
.startWith(false)
.scan((prev, next) => !prev);
// view elements
//---------------------------------------------------------------------------------------
const headerTree$ = Observable
.combineLatest(title$, filter$, (title, state) => {
return renderHeader(title, state);
});
const bodyTree$ = body$.map(body => {
return div('.m-space-items-top-2.m-space-h-2', body.map(item =>
renderItem(item.title, item.url)
));
});
const vtree$ = Observable.combineLatest(headerTree$, bodyTree$, (headerElement, bodyElement) => {
return section('.menu__block', [
headerElement,
bodyElement
]);
});
return {
DOM: vtree$
};
};
function renderHeader(title, filter){
return header('.f-meta.filter' + (filter ? '.is-active' : ''), [
div('.filter__header', h1([
title,
button('.filter__toggle', [
svg('svg', {'class': 'u-icon', 'width': 10, 'height': 10},
svg('use', {'xlink:href': '#icon-arrow'})
)
])
]
)),
div('.filter__container', [...])
]);
}
| |
doc_23536802
|
I am studying computer applications (software development) and will graduate in a year, i will be taking a year off to get my coding skills up to scratch as i have recently come to love code and development. i tried getting rails working on my windows 7 machine but that was painful.
My question is, is it worth it to go out and buy a Macbook if i'm going to be doing a lot of code in rails and java? over the next few years? does it make life easier?
A: Ubuntu is the way to go man. You'll love the ease of use and installation, too.
A: UNIX variants, of course. Actually, Mac OS is very nice, because of TextMate and some similar tools.
A: Mac would probably ideal for Ruby, but for Java I'm not too sure. For Java, the safest bet would be either Linux or Windows. But Ruby on Windows (with regards to tools and utilities) is pretty dismal.. so for the best of both worlds I would go with Linux. The OS is free and there's no need for specific hardware, or to run a virtual machine.
A: I started using Ubuntu for Rails development a few weeks ago and have noticed a big improvement over Windows (although I still dual boot) due to the following:
*
*Terminal in linux is alot more robust than command prompt
*Rails commands seem to run faster in Ubuntu
*vim is a nice lightweight editor
If your going to use an IDE, I would suggest NetBeans for Rails and Java.
A: I have always worked on Windows systems, mostly working on C++ and later C#. I started working with Ruby on Rails more than a year ago. I did that on windows, and actually that worked out pretty well for me (just make sure to use a ruby version from rubyinstaller.org).
Although lately i have switched employer, and i am developing on ubuntu 10.04, and i even switched my home-system. I would recommend Ubuntu 10.04, but there are some very valid reasons to keep using Windows as well (some commercial software totally not being available on Ubuntu).
A: Lets hope this does not turn into a Linux vs Mac flamewar.
At work and on my private machines, I use Ubuntu/Linux for RubyOnRails and Java development.
Sure, under OS X you have many nice tools available (like TextMate), but there are many others in Ubuntu/Linux available too. For free.
GEdit can replace TextMate quite well when using the right plugins, and for big projects I would always prefer NetBeans (for Rails and Java).
Also Ubuntu's package management and package feeds make it very easy to set up a working development environment.
And finally:
*
*Apple is really expensive, you will pay many bucks just for the logo on your device.
*Ubuntu is absolutely free on the other hand and can run nicely on almost any hardware (200$ Netbooks for example).
My suggestion:
try out Ubuntu on your current device - if you don't like it you can still go for the white fruit. And don't even think about using Windows for Rails Development.
A: There's no need to go out and pay top dollar for Mac hardware. You can get a stacked and rock-solid Toshiba laptop, put the latest Ubuntu on it, and you'll have a great Rails devleopment system.
A: I have worked with ruby on rails in ubuntu, mac OS X and windows. Windows only was the worse but I prefer it with a virtual machine loaded with a ubuntu server 10.04 (it helps you in deployment also, as the most servers have linux), I have samba - access to the ubuntu files through windows explorer and it is working like a charm. You also have snapshots to revert if you do something wrong (through virtual machine), so you can destroy and recover it very easily and keep backup without any problem. Also you can transfer it everywhere with just copy paste.
Mac OS X is also a good choice, but it isn't as good as ubuntu for me, I am used to windows graphical environment and the commands in the command line sometimes is a little different (mac OSX is unix, it isn't linux and it doesn't use X windows), so it is a little tricky to feel comfortable, you have to learn a lot more to get the productivity you already have with windows. Also textmate needs time to get used to it, so better invest in a better solution like vim or emacs.
A: I've had great results running Java under Ubuntu. The UNIX environment is great IMO for scripting, running web application servers etc. In your position it is probably also a useful skill set to acquire.
In the past I've also run quite a few of my Java applications on Macs. They ran perfectly well, but I wasn't totally satisfied with performance of the JVM. That may have well have improved in recent versions of course.
A: I prefer uBuntu
Lets remember there are a couple of uBuntu specific setups that are required. Here are a couple links:
https://www.digitalocean.com/community/articles/how-to-install-ruby-on-rails-on-ubuntu-12-04-lts-precise-pangolin-with-rvm
http://gorails.com/setup/ubuntu is my favorite
| |
doc_23536803
|
fatal: '/C/GitRepository/NAV.git' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The folder is there and is accessible on the remote server.
We are aware this question is asked about a dozen times here on SO, but the fix still eludes us. Can anyone provide some Windows specific assistance in how to go about setting up the keys (or, if those keys from PuTTY and WinSCP sessions are usable, what else could be the problem)?
A: The slashes in the path portion need to be forward slash, not the windows backslash separator. Include the semi-colon.
/C:/GitRepository/NAV
| |
doc_23536804
|
I have added sample code.
public ActionResult Authenticate(string password)
{
try
{
IdentityTheftEntities context = new IdentityTheftEntities();
Admin user = context.Admins.Where(x => x.Password == password && x.IsActive == true).FirstOrDefault();
if (user != null)
{
Session.Add("userID", user.ID);
}
else
{
ViewBag.errorMessage = "Please put correct password!";
return View("requests");
}
}
catch (Exception ex)
{
ViewBag.errMes = ex.Message.ToString();
}
return RedirectToAction("requests", "home"); ;
}
Checking the validity by @if (Session["userID"] != null).
When I enter the password and hit submit nothing happens.
| |
doc_23536805
|
//Sieve of Eratosthenes, as seen in WWDC 2015
func primes(n: Int) -> [Int] {
var numbers = [Int](2..<n)
for i in 0..<n-2 {
guard let prime = numbers[i] where prime > 0 else { continue }
for multiple in stride(from: 2 * prime-2, to: n-2, by: prime) {
numbers[multiple] = 0
print("\"numbers[i]")
}
}
return numbers.filter { $0 > 0 }
}
When I type that into an Xcode playground, I get the following error:
Initializer for conditional binding must have Optional type, not 'Int.'
Why is that?
A: The "problem" here is the statement guard let prime = numbers[i]. The compiler complains about it because the guard let syntax expects numbers[i] to be an Optional which it can conditionally unwrap. But it is not an optional, you are always able to retrieve the i-th Int out of the array.
To fix it simply write
let prime = numbers[i]
guard prime > 0 else { continue }
The correct usage of the stride then looks like the following (after a long search in the comments):
for multiple in (2*prime-2).stride(to: n-2, by: 2*prime-2) {
Then final piece is then to change the print:
print("\(numbers[i])")
| |
doc_23536806
|
Here is some an illustration of what I'm doing.
public class readerThread implements Runnable {
private static BlockQueue<String> iqueue
private static BlockingQueue<Object> oqueue
private static ThreadLocal<java.util.ArrayList<File>> fileList = new ThreadLocal<java.util.ArrayList<File>>();
private static int FILE_BATCH_SIZE = 50;
public void run() {
fileList.set(new ArrayList<File>());
ThreadLocal<Integer> i = new ThreadLocal<Integer>();
i.set(1);
for (int y = i.get(); i<1000000; i.set(y++)) {
try {
File datafile = new File(iqueue.poll(86400, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (datafile == null || datafile == POISION) {
break;
}
fileList.get().add(datafile);
...
...
if (fileList.get().size() == FILE_BATCH_SIZE || (iqueue.peek() == null) || (iqueue.peek() == POISON) ) {
parseAndWrite();
fileList.get().clear();
}
}
}
public void parseAndWrite() {
for (File f : fileList.get()) {
Long fileTs = f.lastModified()
String fileName = String.valueOf(f);
Filelog filelog = new Filelog()
Asset asset = new Asset()
Parser parser = new Parser(f);
// Parser returns an Asset
asset = parser.parse()
String assetTag = asset.getAssetTag();
filelog.setTimeStamp(fileTs);
filelog.setFileName(fileName);
filelog.setAssetTag(assetTag);
filelog.setProcessed(false);
HibernateWrapper.commit(filelog);
oqueue.put(asset);
.....
.....
}
}
}
Please ignore any obvious errors in the example as it was hastily put together.
Effectively several readerThreads take files from an blockingqueue, extract data as an object and write the object to a database using Hibernate. Let's assume for a moment that the HibernateWrapper is 100% thread safe; since the data in the asset object is associated with files taken from the queue and since each thread is working on a different file, is it thread-safe?
Forgive me if my terminology is off. Basically I believe some of my prior code was racey as I observed some examples where rows of data written were associated with wrong objects (e.g file foo has bar's assettag).
A: Thread safety is an issue when there's shared state between threads. If your code is such that each thread has its own set of variables, then the code is thread-safe. That is more difficult than it sounds because of the possible shared state for other functions or third party libraries you call, because they may introduce shared state among threads.
Your use of fileList as a thread-local is correct, but it looks like it is unnecessary because you can pass it to the parseAndWrite method as an argument.
Your use of thread-local i is unnecessary, because it is a stack variable, and every thread will have its own copy.
| |
doc_23536807
|
1 18 * * * kill -SIGSTOP xxxx
1 2 * * * kill -SIGCONT xxxx
It never works.
Every day I have to pause it manually before I leave work at 19:00, and when I check it at the next morning, various things happens.
Sometimes I find the process had disappeared.
Sometimes the process is still in paused state, and I can successfully continue it with -SIGCONT.
Sometimes when I manually send -SIGCONT, the paused process disaapears.
| |
doc_23536808
|
Student* student11 = new Student("Vince", "Vaughn", "7-th Avenue", "New York", "783-945-90-28", 49);
Student* student12 = new Student("Vince", "Mcmahon", "Beverly Hills", "Los Angeles", "874-940-42-12", 47);
Student* student13 = new Student("Stone Cold", "Steve Austin", "Dallas", "Texas", "385-421-47-95", 34);
Then I created an object of class Teacher:
Teacher* teacher1 = new Teacher("Dave", "Bautista", "Washington", "Washington DC", "943-244-93-12", 31);
So the task is to put created objects of Student class in array that belongs to other class Course. And do the same thing with object of class Teacher.
A: Arrays are homogeneous: There is a single element type, and all elements of an array are of that same type. It is not possible to have elements of multiple types in an array.
If classes are related through inheritance, then it is possible to store pointers to base class sub objects, which may be the base of different derived types.
Another approach is to use a tagged union as the element type. std::variant is an implementation of tagged union provided by the standard library. Such type uses "type erasure" technique to store an object from a closed set of types.
| |
doc_23536809
|
create_list = []
counter = 0
for x in my_list:
create_list.append(f(x+counter))
counter += 1
I've tried:
create_list = [f(x+counter) for x in my_list] but obviously this doesn't increase the counter.
A: You could use enumerate():
new_list = [f(val+index) for (index, val) in enumerate(my_list)]
A: Okay, this is definitely not the best way to handle it (I hate having to import stuff!), but it's pretty cool and works:
counter = -1
def g(x): # function with side-effect! returns back the value.
global counter
counter = counter + 1
return counter
create_list = [f(x)+g(x)) for x in my_list] #btw you might want to type cast? I don't really know your data sets nor functionality of f, so I'm not sure
There are a lot of other ways too such as making a second list based off the len(my_list) and then using zip to sort of "parallel" compute, or using two list comprehensions, etc.
| |
doc_23536810
|
The time stamp held in $person['StartDateTime'] is 2019-10-09T14:00:00
The message always prints out the good morning message and I've tried the other posts on here but can't seem to get it to work. I've tried 'noon', 12, 12 PM, etc..
if ($person['StartDateTime'] < strtotime("noon"))
{
echo 'Meeting Time:' . $person['StartDateTime'] . '<br>';
echo "Good morning" . '<br>';
}
Edited:
If I try as suggested below I get nothing back.
if (strtotime($person['StartDateTime']) < strtotime("noon"))
If I try using after >
if (strtotime($person['StartDateTime']) > strtotime("noon"))
I get the message but also on my morning timestamp - 2019-10-09T10:00:00 which I shouldn't.
I'm wondering do I need to specify noon for the day of the timestamp?
A: I suggest using Datetime with proper format argument a which gives either am or pm depending on the time
if ((new Datetime($person['StartDateTime']))->format('a') == 'am') {
// am
} else {
// pm
}
A: Ok after trying a few things the solution in this case was simple.
Format the date using only "A", this will return AP or PM depending on the time.
$starttime = date("A",strtotime(date($person['StartDateTime'])));
if ($starttime == "AM"){
echo "Good Morning" . '<br>';
}
A: strtotime return timestamp. You compare int value with string. Read about strtotime function
| |
doc_23536811
|
I have a Java ulitities library. I want to make 2 jar files. One for Android and the another for Java.
For Android jar, I want to exclude JDBC package.
I want to upload both jar files & theirs javadoc, javasources into the Maven remote repository.
so I can use the library as below
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>mylib</artifactId>
<version>1.0</version>
</dependency>
OR Android classifier
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>mylib</artifactId>
<version>1.0</version>
<classifier>android</classifier>
</dependency>
Here is my POM.xml
<project>
<!-- .... -->
<groupId>com.mycompany</groupId>
<artifactId>mylib</artifactId>
<version>1.0</version>
<name>mylib</name>
<packaging>jar</packaging>
<!-- .... -->
<build>
<plugins>
<!-- compiler -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<!-- .... -->
</plugin>
<!-- jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<!-- .... -->
</plugin>
<!-- source -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<!-- .... -->
</plugin>
<!-- javadoc -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<!-- .... -->
</plugin>
<!-- nexus-staging-maven -->
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<!-- .... -->
</plugin>
<!-- maven-gpg -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<!-- .... -->
</plugin>
</plugins>
</build>
<profiles>
<!-- All files - Java -->
<profile>
<id>java</id>
<activation>
<property>
<name>!android</name>
</property>
</activation>
</profile>
<!-- Android - Excluding JDBC, JPA packages -->
<profile>
<id>android</id>
<activation>
<property>
<name>android</name>
</property>
</activation>
<build>
<plugins>
<!-- Exclude some packages -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/jdbc/**</exclude>
</excludes>
</configuration>
</plugin>
<!-- Exclude some packages -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<classifier>android</classifier>
<excludes>
<exclude>**/jdbc/**</exclude>
</excludes>
</configuration>
</plugin>
<!-- Exclude some packages -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/jdbc/**</exclude>
</excludes>
</configuration>
</plugin>
<!-- Exclude some packages -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<sourcepath>${project.basedir}/src/main/java</sourcepath>
<sourceFileExcludes>
<sourceFileExclude>**/jdbc/**</sourceFileExclude>
</sourceFileExcludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<!-- .... -->
</dependencies>
</project>
Maven CLI
*
*Run mvn clean deploy for deploy Java profile
Successfully. Maven deploy the following files into the remote repository:
*
*mylib-1.0.jar
*mylib-1.0.pom
*mylib-1.0-javadoc.jar
*mylib-1.0-sources.jar
*And all their sign files
*Run mvn clean deploy -Dandroid for deploy Android profile
The following files are generated:
*
*mylib-1.0-android.jar // append classifier
*mylib-1.0.pom
*mylib-1.0-javadoc.jar
*mylib-1.0-sources.jar
*And all their sign files
I got error
[ERROR] Repository "mycompany-1082" failures
[ERROR] Rule "sources-staging" failures
[ERROR] * Missing: no main jar artifact found in folder '/com/mycompany/mylib/1.0'
[ERROR] Rule "javadoc-staging" failures
[ERROR] * Missing: no main jar artifact found in folder '/com/mycompany/mylib/1.0'
Question: why is this error happening?
A: The same issue has already been reported and it's mainly due to the fact that the main artifact uses a classifier (the android one) while sources and javadoc artifact don't, creating a misalignment.
Indeed, the error message is exactly pointing at issues on sources and javadoc artifacts:
[ERROR] Rule "sources-staging" failures
[ERROR] * Missing: no main jar artifact found in folder '/com/mycompany/mylib/1.0'
[ERROR] Rule "javadoc-staging" failures
[ERROR] * Missing: no main jar artifact found in folder '/com/mycompany/mylib/1.0'
Saying that the sources and the javadoc artifact couldn't be found (according to the main artifact classifier): a mismatch.
Luckily, you can fix this issue configuring the maven-source-plugin via its classifier option (default to sources) and the maven-javadoc-plugin via its classifier option (default to javadoc).
The android profile could actually simply specify the following property entries:
<properties>
<maven.source.classifier>android-sources</maven.source.classifier>
<maven.javadoc.classifier>android-javadoc</maven.javadoc.classifier>
</properties>
Indeed using the user properties specified by the aforementioned plugin goals for these options.
To make it even more robust, better to apply the following approach:
<properties>
<android.classifier>android</android.classifier>
<maven.source.classifier>${android.classifier}-sources</maven.source.classifier>
<maven.javadoc.classifier>${android.classifier}-javadoc</maven.javadoc.classifier>
</properties>
Then use the ${android.classifier} property for the classifier value of the maven-jar-plugin also: that is, centralising its value you ensure an easier maintenance.
| |
doc_23536812
|
And i need help with the following:
1- is there an IDE to make it easy to make animation with HTML5
like flash IDE with time line ...
2- What is the best library to make animation with HTML5
i found "burst engine" library it is good but does not handle png images
Thanks
A: Companies are looking seriously at building an IDE for HTML5, including Adobe with their product, Edge, and Microsoft appear to be heading down this route with the recent announcement that they will be abandoning Silverlight as a broader web platform (instead choosing to focus on Windows Phone 7).
Given that HTML5 is still very much on the upward climb in terms of adoption and expectations, many of the higher-profile players in the market (i.e. Adobe, Microsoft, Coda or possibly Eclipse) are still feeling out what constitutes a stable HTML5 feature and what specs are still very fluid, I'd be surprised to see an IDE on the market before this time next year.
So that's my take on IDEs.
In terms of the best library to create HTML5-based animations, it really depends on what you're trying to do. There are a few JavaScript frameworks out there such as CakeJS, Doodle-js or - in particular - ProcessingJs.
You might find more relevant results for searches that are more specific to your particular needs. Good luck!
A: If you have Flash you could try using the following:
Adobe Wallaby
This is still on pre-release state, so many features are still unavailable. Here is the list of supported features: Release Notes
I also found this youtube video that gives a basic overview.
Hope it helps! and that soon an actual HTML5 IDE is released...
| |
doc_23536813
|
What I find awkward is that according to the input I have from tty and according to tput left key is mapped to Backspace code (ASCII code 8)
tput cub1 | od -tx1
0000000 08
0000001
while I would expect it to be \033[D because
$ tput cuf1 | od -tx1
0000000 1b 5b 43
0000003
which is \033[C code that is right key indeed according to various documents about terminal codes.
So the absence of symmetry here is quite confusing to me. Is there a specific reason behind it?
The second question: is there way to change it?
I have created example of raw terminal which demonstrates this behaviour: RawTerminal.
A: The cub1 capability is not left arrow, but instead a cursor movement capability. Referring to terminfo(5), you may find
cursor_left cub1 le move left one space
which is named similarly to the key marked "left-arrow":
key_left kcub1 kl left-arrow key
The cursor-movement capabilities do just that: move the cursor around on the screen. In some cases, the similarly-named cursor-movement and cursor-keys have the same string, just because (long ago) it was useful to have keys which one could setup to echo locally (rather than send to a host application).
In this particular case, the two are different because the main use of these terminal descriptions is for curses applications, which minimize the number of characters sent to the screen (as well as minimizing the time spent sending the characters). Making cub1 send an ASCII backspace is fewer characters than the escape sequence.
While there is no requirement, longstanding convention tells you that terminfo capabilities which begin with "k" are probably for the keyboard.
bash uses readline for reading keys and updating the line which you are
typing on. Checking its source-code, e.g., from bash-4.2 I am looking
at lib/readline/terminal.c, it has a table of the termcap strings that
it may use:
static const struct _tc_string tc_strings[] =
{
{ "@7", &_rl_term_at7 },
{ "DC", &_rl_term_DC },
{ "IC", &_rl_term_IC },
{ "ce", &_rl_term_clreol },
{ "cl", &_rl_term_clrpag },
{ "cr", &_rl_term_cr },
{ "dc", &_rl_term_dc },
{ "ei", &_rl_term_ei },
{ "ic", &_rl_term_ic },
{ "im", &_rl_term_im },
{ "kD", &_rl_term_kD }, /* delete */
{ "kH", &_rl_term_kH }, /* home down ?? */
{ "kI", &_rl_term_kI }, /* insert */
{ "kd", &_rl_term_kd },
{ "ke", &_rl_term_ke }, /* end keypad mode */
{ "kh", &_rl_term_kh }, /* home */
{ "kl", &_rl_term_kl },
{ "kr", &_rl_term_kr },
{ "ks", &_rl_term_ks }, /* start keypad mode */
{ "ku", &_rl_term_ku },
{ "le", &_rl_term_backspace },
{ "mm", &_rl_term_mm },
{ "mo", &_rl_term_mo },
{ "nd", &_rl_term_forward_char },
{ "pc", &_rl_term_pc },
{ "up", &_rl_term_up },
{ "vb", &_rl_visible_bell },
{ "vs", &_rl_term_vs },
{ "ve", &_rl_term_ve },
};
Using "infocmp -Cr xterm", I can see this:
xterm|xterm terminal emulator (X Window System):\
:am:bs:km:mi:msn:\
:co#80:it#8:li#24:\
:AL=\E[%dLC=\E[%dPL=\E[%dMO=\E[%dB:IC=\E[%d@:\
:K2=\EOE:LE=\E[%dD:RI=\E[%dC:SF=\E[%dS:SR=\E[%dT:\
:UP=\E[%dA:ae=\E(B:al=\E[L:as=\E(0:bl=^G:bt=\E[Z:cd=\E[J:\
:ce=\E[K:cl=\E[H\E[2J:cm=\E[%i%d;%dH:cr=^M:\
:cs=\E[%i%d;%dr:ct=\E[3gc=\E[Pl=\E[Mo=^J:ec=\E[%dX:\
:ei=\E[4l:ho=\E[H:im=\E[4h:is=\E[!p\E[?3;4l\E[4l\E>:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\E[15~:k6=\E[17~:\
:k7=\E[18~:k8=\E[19~:k9=\E[20~:kD=\E[3~:kI=\E[2~:kN=\E[6~:\
:kP=\E[5~:kb=\177:kd=\EOB:ke=\E[?1l\E>:kh=\EOH:kl=\EOD:\
:kr=\EOC:ks=\E[?1h\E=:ku=\EOA:le=^H:mb=\E[5m:md=\E[1m:\
:me=\E[0m:mh=\E[2m:mm=\E[?1034h:mo=\E[?1034l:mr=\E[7m:\
:nd=\E[C:rc=\E8:sc=\E7:se=\E[27m:sf=^J:so=\E[7m:sr=\EM:\
:st=\EH:ta=^I:te=\E[?1049l:ti=\E[?1049h:ue=\E[24m:up=\E[A:\
:us=\E[4m:vb=\E[?5h\E[?5l:ve=\E[?12l\E[?25h:vi=\E[?25l:\
:vs=\E[?12;25h:
or with "infocmp -Cr nsterm":
nsterm|Apple_Terminal|AppKit Terminal.app:\
:am:hs:mi:msno:\
:co#80:it#8:li#24:ws#50:\
:AL=\E[%dLC=\E[%dPL=\E[%dMO=\E[%dB:IC=\E[%d@:\
:K1=\EOq:K2=\EOr:K3=\EOs:K4=\EOp:K5=\EOn:LE=\E[%dD:\
:RI=\E[%dC:UP=\E[%dA:ae=^O:al=\E[L:as=^N:bl=^G:cd=\E[J:\
:ce=\E[K:cl=\E[H\E[J:cm=\E[%i%d;%dH:cr=^M:cs=\E[%i%d;%dr:\
:ct=\E[3gc=\E[Pl=\E[Mo=^Js=\E]2;\007:ei=\E[4l:\
:fs=^G:ho=\E[H:ic=\E[@:im=\E[4h:k1=\EOP:k2=\EOQ:k3=\EOR:\
:k4=\EOS:k5=\E[15~:k6=\E[17~:k7=\E[18~:k8=\E[19~:\
:k9=\E[20~:kD=\E[3~:kN=\E[6~:kP=\E[5~:kb=\177:kd=\EOB:\
:ke=\E[?1l\E>:kh=\EOH:kl=\EOD:kr=\EOC:ks=\E[?1h\E=:\
:ku=\EOA:le=^H:mb=\E[5m:md=\E[1m:me=\E[0m:mh=\E[2m:\
:mr=\E[7m:nd=\E[C:rc=\E8:\
:rs=\E>\E[?3l\E[?4l\E[?5l\E[?7h\E[?8h:sc=\E7:se=\E[m:\
:sf=^J:so=\E[7m:sr=\EM:st=\EH:ta=^I:te=\E[2J\E[?47l\E8:\
:ti=\E7\E[?47h:ts=\E]2;:ue=\E[m:up=\E[A:us=\E[4m:\
:vb=\E[?5h\E[?5l:ve=\E[?25h:vi=\E[?25l:
The ":le=^H:" part is what you are seeing.
From (ncurses) terminfo(5):
cursor_left cub1 le move left one space
if you made a termcap (for "xterm") setting that to \e[D, then bash should
echo back \e[D rather than ^H. But ncurses uses ^H to reduce the number of
characters from from 3 (\e[D) to 1 (^H)
Rather than modify the terminal description, you should modify your program,
e.g., to read the termcap strings and handle those.
| |
doc_23536814
|
This is a very complex code (not mine).
I want to halt the execution of the code in this function, and to resume it when the button in the other form is pressed.
Internet research has not been helpful. I have no idea how two different code parts could interact.
On Error GoTo NoConnnectionErrorHandler
Dim Request As New MSXML2.XMLHTTP60
Request.Open "GET", "http://www.bbc.com"
Request.send
'MsgBox Request.Status
NoConnnectionErrorHandler:
DoCmd.OpenForm "Frm_Global_NoConnectionDialog"
When there is no connection to the internet a form opens. How do I stop the code and let it resume when a button in another form is pressed?
It goes through the whole function (where the snippet is only a small part) periodically and checks.
When there is no connection it should halt the whole program, until the button is pressed, and then check the connection again and proceed if there is one.
EDIT: The answer tackles on the problem, but one thing that confuses me is how to trigger the "resume code execution" from a different form via a button press.
A: If I am understanding you correctly, you should use Exit Sub above your error handler (NoConnectinoErrorHandler).
Add some code to ensure your error has been resolved, then clear the error and resume your work.
See if this is what you are looking for:
Sub foo()
' Your unseen code ...
On Error GoTo NoConnnectionErrorHandler
Dim Request As New MSXML2.XMLHTTP60
Request.Open "GET", "http://www.bbc.com"
Request.send
'MsgBox Request.Status
Exit Sub 'Put this above your error handler
NoConnnectionErrorHandler:
DoCmd.OpenForm "Frm_Global_NoConnectionDialog"
'Some code to ensure error no longer exists....
Err.Clear
Resume
End Sub
| |
doc_23536815
|
Can someone please tell if I will still be able to use dictionary class, or if I need to use some other class?
EDIT : We have an existing application which uses oracle database to query or lookup object details. It is however too slow, since the same objects are getting repeatedly queried. I was feeling that it might be ideal to use a lookup map for this scenario, to improve the response time. However I am worried if size will make it a problem
A: Short Answer
Yes. If your machine has enough memory for the structure (and the overhead of the rest of the program and system including operating system).
Long Answer
Are you sure you want to? Without knowing more about your application, it's difficult to know what to suggest.
*
*Where is the data coming from? A file? Files? A database? Services?
*Is this a caching mechanism? If so, can you expire items out of the cache once they haven't been accessed for a while? This way, you don't have to hold everything in memory all the time.
*As others have suggested, if you're just trying to store lots of data, can you just use a database? That way you don't have to have all of the information in memory at once. With indexing, most databases are excellent at performing fast retrieves. You could combine this approach with a cache.
*Is the data that will be in memory read only, or will it have to be persisted back to some storage when something changes?
*Scalability - do you expect that the amount of data that will be stored in this dictionary will increase as time goes on? If so, you're going to run into a point where it's very expensive to buy machines that can handle this amount of data. You might want to look a distributed caching system if this is the case (AppFrabric comes to mind) so you can scale out horizontally (more machines) instead of vertically (one really big expensive point of failure).
UPDATE
In light of the poster's edit, it sounds like caching would go a long way here. There are many ways to do this:
*
*Simple dictionary caching - just cache stuff as its requested.
*Memcache
*Caching Application Block I'm not a huge fan of this implementation, but others have had success.
A: As long as you're on a 64GB machine, yes you should be able to use that large of a dictionary. However if you have THAT much data, a database may be more appropriate (cassandra is really nothing but a gigantic dictionary, and there's always MySQL).
A: When you say 1-2GB of data, I assume that you mean the items are complex objects that cumulatively contain 1-2GB.
Unless they're structs (and they shouldn't be), the dictionary doesn't care how big the items are.
As long as you have less than about 224 items (I pulled that number out of a hat), you can store as much as you can fit in memory.
However, as everyone else has suggested, you should probably use a database instead.
You may want to use an in-memory database such as SQL CE.
A: You can but For a Dictionary as large as that you are better off using a DataBase
A: Use a database.
Make sure you've a good DB model, put correct indexes, and off you go.
A: You can use subdictionaries.
Dictionary<KeyA, Dictionary<KeyB ....
Where KeyA is some common part of KeyB.
For example, if you have a String dictionary you can use the First letter as KeyA.
| |
doc_23536816
|
A: As of June 2020, The best method (WA), assuming you are using a form is to use a Tewr's FileReader. Let start with the API, the post controller would be :
public async Task<IActionResult> PostMedia(
[FromForm] IFormFile Picture,
[FromForm] string Focus,
[FromForm] string ID,
[FromForm] string Title,
[FromForm] string FormType,
[FromForm] string AnimalType,
[FromForm] string Mode,
[FromForm] string AnimalID
)
{
Debug.WriteLine($"-------------------------------------{Focus}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{ID}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{Title}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{FormType}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{AnimalType}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{Mode}-----------------------------------------------");
Debug.WriteLine($"-------------------------------------{AnimalID}-----------------------------------------------");
//check if file was fully uploaded
if (Picture.Length == 0 || Picture == null)
return BadRequest("Upload a new File");
else
return Ok ("do something with this data....")
}
Then the post method on the client side would be:
public async Task PostFile()
{
//create content headers
var content = new MultipartFormDataContent();
content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
//create content
content.Add(new StreamContent(Pic.Stream, (int)Pic.Stream.Length), "Picture", Pic.FileName);
content.Add(new StringContent(Pic.Title), "Title");
content.Add(new StringContent(Pic.Focus), "Focus");
content.Add(new StringContent(Pic.ID), "ID");
content.Add(new StringContent(Pic.FormType), "FormType");
content.Add(new StringContent(Pic.AnimalType), "AnimalType");
content.Add(new StringContent(Pic.Mode), "Mode");
content.Add(new StringContent(Pic.AnimalID), "AnimalID");
//call to the server
var upload = await Http.PostAsync("Media",content);
//get server response
Pic.Message = await upload.Content.ReadAsStringAsync();
}
Tewr File reader helps you read the file into a stream which in my case is passed to the Pic object. The reading function which is binded to the onchange of your input element in the form would be :
public async Task ReadFile()
{
var file = (await fileReaderService.CreateReference(Xelement).EnumerateFilesAsync()).FirstOrDefault();
if (file == null) return;
var fileInfo = await file.ReadFileInfoAsync();
Pic.FileName = fileInfo.Name;
// Read into RAM
using (var memoryStream = await file.CreateMemoryStreamAsync((int)fileInfo.Size))
{
// Copy store image into pic object
Pic.Stream = new MemoryStream(memoryStream.ToArray());
}
}
Note that Xelement is ElementReference, and it used as ref on the input element in the form.
A: I was dabbling with installing SteveSandersonMS' repo and then realised that, as of February 2021, there is actually a native InputFile component in ASP.NET Core 5.0.
It supports uploading of single and multiple files in Blazor and is easy to use (and you don't need to add your own JS files etc.).
I used it for single file uploads - all you need to do is add the InputFile component in the Razor page:
<InputFile OnChange="@SingleUpload" />
and then in my case I needed the file in a byte array:
@code {
private async Task SingleUpload(InputFileChangeEventArgs e)
{
MemoryStream ms = new MemoryStream();
await e.File.OpenReadStream().CopyToAsync(ms);
var bytes = ms.ToArray();
//do something with bytes
}
}
InputFileChangeEventArgs gives you an IReadOnlyList of IBrowserFile which you can use to get the Name, LastModified, Size and ContentType, as well as an OpenReadStream method for getting a Stream.
There is good documentation and code on how to get multiple files in the ASP.NET docs.
Your will also need to add the System.IO namespace:
@using System.IO
A: At the current state of affairs (as 2 April 2020), you will require JS, it is inevitable.
There are two main approaches you can take:
*
*get the file data in the onchange event of the input, and call C# methods by passing the byte[] to them - that's basically the file selector approach you linked where you get the file data in the Blazor app to do whatever you want with it.
*get the file data in the onchange event of the input, and use JS to call a remote endpoint that will receive the file and do something with it (like save it on your NAS or put it in your DB). This one is an actual file upload, as opposed to a file selector.
Both approaches are similar from coding perspective - you need JS. Perhaps in a future version of Blazor we will get an <InputFile> that will do the selection so you can to uploads with C# HTTP requests.
The File Selector approach is relatively easy to implement (literally a few lines), but it does not give you a file on the server, you have to work for it a little. The File Upload approach is harder to get right. I would personally use someone else's package for either. For file uploads things like Telerik UI for Blazor can be a commercial fit, and for the simpler selectors there is already another answer that links examples. By the way, Telerik's demos also have one such example as a component implemented for some of the demos.
A: I do this by using a component and some javascript (looks like a button). Once the component and js are incorporated, you never have to worry about it again...
Here's the Upload Component (Upload.Razor):
@inject IJSRuntime JSRuntime
@if (AllowMulitple)
{
<input id="Xinputfile00" type="file" accept="@Filter" @onchange="UploadFile" multiple hidden />
}
else
{
<input id="Xinputfile00" type="file" accept="@Filter" @onchange="UploadFile" hidden />
}
<button class="btn btn-default" @onclick="ClickUpload">@Title</button>
@code {
[Parameter]
public FileData[] Files { get; set; }
[Parameter]
public string Filter { get; set; }
[Parameter]
public string Title { get; set; }
[Parameter]
public bool AllowMulitple { get; set; }
[Parameter]
public Action Uploaded { get; set; }
async Task UploadFile()
{
string[] result = await JSRuntime.InvokeAsync<string[]>("blazorExtensions.GetFileData", "Xinputfile00");
List<FileData> results = new List<FileData>();
foreach (string file in result)
{
results.Add(new FileData(file));
}
this.Files = results.ToArray();
if (Uploaded != null)
{
Uploaded();
}
}
async Task ClickUpload()
{
await JSRuntime.InvokeVoidAsync("blazorExtensions.InvokeClick", "Xinputfile00");
}
public class FileData
{
public string Base64 { get; set; }
public string MIMEType { get; set; }
public byte[] Bytes
{
get
{
return Convert.FromBase64String(this.Base64);
}
}
public FileData(string data)
{
if (string.IsNullOrWhiteSpace(data) || !data.Contains(","))
{
return;
}
string[] alldata = data.Split(',');
this.MIMEType = alldata[0].Remove(0, 5).Replace(";base64", "");
this.Base64 = alldata[1];
}
}
Here's the javascript excerpt:
window.blazorExtensions = {
GetFileData: async function (id) {
var target = document.getElementById(id);
var filesArray = Array.prototype.slice.call(target.files);
return Promise.all(filesArray.map(window.blazorExtensions.fileToDataURL));
},
fileToDataURL: async function (file) {
var reader = new FileReader();
return new Promise(function (resolve, reject) {
reader.onerror = function () {
reader.abort();
reject(new DOMException('Error occurred reading file ' + file));
};
reader.onload = function (event) {
resolve(reader.result);
console.log('resolved');
};
reader.readAsDataURL(file);
console.log('returned');
})
},
InvokeClick: function (id) {
var elem = document.getElementById(id);
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
elem.click();
},
}
And here's a calling markup sample:
<Upload @ref="upload" Filter=".xlsx" Title="Upload" AllowMulitple="false" Uploaded="DoMyExcelThingOrSomething" />
and the method it calls after upload:
Upload upload;
void DoMyExcelThingOrSomething()
{
if (upload.Files.Length < 1 || string.IsNullOrWhiteSpace(upload.Files[0].Base64))
{
//...nothing good here...
return;
}
//play with upload.Files here...
}
A: For Blazor Server, the following would upload the file to the server. There's no need to have a separate API server, or to use JS code. And it converts the stream into a file.
@using System.IO
@inject IWebHostEnvironment env
@*for ibrowser*@
@using Microsoft.AspNetCore.Components.Forms;
<h1>Blazor Server File Upload</h1>
<h3>@Message</h3>
<form @onsubmit="OnSubmit">
<InputFile OnChange="OnInputFileChange" multiple />
<br /><br />
<button type="submit">Upload Selected File(s)</button>
</form>
@code {
string Message = "No file(s) selected";
IReadOnlyList<IBrowserFile> selectedFiles;
void OnInputFileChange(InputFileChangeEventArgs e)
{
selectedFiles = e.GetMultipleFiles();
Message = $"{selectedFiles.Count} file(s) selected";
this.StateHasChanged();
}
async void OnSubmit()
{
foreach (var file in selectedFiles)
{
Stream stream = file.OpenReadStream();
var path = $"{env.WebRootPath}\\{file.Name}";
FileStream fs = File.Create(path);
await stream.CopyToAsync(fs);
stream.Close();
fs.Close();
}
Message = $"{selectedFiles.Count} file(s) uploaded on server";
this.StateHasChanged();
}
}
(Minor edit of http://www.bipinjoshi.net/articles/06473cc7-a391-409e-948d-3752ba3b4a6c.aspx)
| |
doc_23536817
|
In scientific contexts, many software/libraries are not installed on the system but loaded from a module system.
Then, in order to use another gcc compiler, you would do:
module load .../gcc-X
or for hdf5
module load ../hdf5-Y
Sometimes also meta modules or programming environments
module load ProgrammingEnvironmentX
are available that set up a lot of libraries and links between them.
Then, I can perfectly configure and build a project with CMake and the loaded modules inside a terminal.
However, if I use VSCode and the CMakeTools Extension via the graphical user interface, it is unclear to me, how VSCode learns about these modules and the paths set.
I thought that the CMake extension would read a compile_commands.json in the corresponding root directory as it magically worked some hours ago but I cannot reproduce it.
I know that I can set the kit or compiler via F1 and "CMake: Edit User-Local CMake Kits". However, this only resolves for the compiler not for additional software such as hdf5 or gdb and its links.
Question
How can I configure, build and debug a software with VSCode and CMakeTools Extension if I do not use system software but variable modules? For the compiler, this is clear to me, see the kits. But often you need much more than just another compiler.
A potential solution
I am not sure if the solution presented in the following always works.
Load your software modules, e.g., with module load PrgEnv/gcc11-openmpi in a terminal and start code from that same terminal (If you use VSCode Remote you may need to load these modules in your bashrc and maybe kill the vscode-server everytime you disconnect and when you want to load other modules; not sure though)
There is the possibility to set specific compilers as a kit in cmake-tools-kits.json. Press F1 and go to CMake: Edit User-Local CMake Kits and, e.g., add
{
"name": "GCC 11 openmpi",
"compilers": {
"C": "/modulesystem/...LONGPATH.../bin/gcc",
"CXX": "/modulesystem/...LONGPATH.../bin/g++"
}
}
or similar if you have, e.g., loaded a clang/clang++ compiler set.
Then add to your settings.json (also in .vscode of your project directory)
"cmake.cmakePath" : "...LONGPATH.../bin/cmake",
"cmake.debugConfig": {
"MIMode": "gdb",
"miDebuggerPath": "...LONGPATH.../bin/gdb"
}
If you don't do so, CMakeTools or VSCode will try to use the system CMake in the first case or search for gdb in the compiler path set above in the kit.
**Some other promising approaches without solution **
Approach A: CMake Tools Kits with environmentSetupScript
If we do not want to load one particular module environment but change without restarting VSCode, we could load the environment before the call of cmake tools with the script
#!/bin/bash
module load PrgEnv/gcc11-openmpi
and execute this with
"environmentSetupScript": "/home/USER/.load_gcc11.sh",
which is placed below "name": "GCC 11 openmpi", above. However, in my case I get a lot of
[kit] Error parsing environment variable: }
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: *)
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: }
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: *)
[kit] Error parsing environment variable: ;;
[kit] Error parsing environment variable: }
I actually do not know what then was set correctly and what not. This however could be solved as reported in https://github.com/microsoft/vscode-cmake-tools/issues/2686
Approach B: Using tasks.json
I also tried to set up a tasks.json and to call a task like
{
"type": "shell",
"label": "Build with modules",
"options": {
"cwd": "${workspaceRoot}/cpp/"
},
"command": "module load PrgEnv/gcc11-openmpi; cd build; cmake -DCMAKE_BUILD_TYPE=Debug ..; cmake --build . -- -j32; gdb build/bin/ode_secir_save_result",
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceFolder}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
This also perfectly builds all software parts but CMake Tools extensions does not get to know about these. I could not resolve that with a particular launch.json or whatsoever on top of that.
| |
doc_23536818
|
What I want to do is add a cell, like in this video at about 0:12 http://www.youtube.com/watch?v=SAebrhW3SHg
In this example, a new cell just pops right out when the add button is pushed. How can I do this?
A: Call -insertRowsAtIndexPaths:withRowAnimation: when you get a button press, and use UITableViewRowAnimationNone to place the cell without any animation. You won't need to reload your table.
| |
doc_23536819
|
Google provides some samples for this in other environments but not .NET.
A: I got it working by using Microsoft.Identity.Client and MailKit.Net.Smtp.SmtpClient like this using Office 365 / Exchange Online. App registration requires API permissions SMTP.Send.
var options = new PublicClientApplicationOptions
{
ClientId = "00000000-0000-0000-0000-000000000000",
TenantId = " 00000000-0000-0000-0000-000000000000",
RedirectUri = "http://localhost"
};
var publicClientApplication = PublicClientApplicationBuilder
.CreateWithApplicationOptions(options)
.Build();
var scopes = new string[] {
"email",
"offline_access",
"https://outlook.office.com/SMTP.Send" // Only needed for SMTP
};
var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
//Test refresh token
var newAuthToken = await publicClientApplication.AcquireTokenSilent(scopes, authToken.Account).ExecuteAsync(cancellationToken);
var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);
await client.AuthenticateAsync(oauth2);
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(authToken.Account.Username));
message.To.Add(MailboxAddress.Parse("toEmail"));
message.Subject = "Test";
message.Body = new TextPart("plain") { Text = @"Oscar Testar" };
await client.SendAsync(message, cancellationToken);
await client.DisconnectAsync(true);
}
Based on this example:
https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md
A: System.Net.Mail does not support OAuth or OAuth2. However, you can use MailKit's (note: only supports OAuth2) SmtpClient to send messages as long as you have the user's OAuth access token (MailKit does not have code that will fetch the OAuth token, but it can use it if you have it).
The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.
Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:
var certificate = new X509Certificate2 (@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id@developer.gserviceaccount.com") {
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = "username@gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
Now that you have an access token (credential.Token.AccessToken), you can use it with MailKit as if it were the password:
using (var client = new SmtpClient ()) {
client.Connect ("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// use the access token
var oauth2 = new SaslMechanismOAuth2 ("username@gmail.com", credential.Token.AccessToken);
client.Authenticate (oauth2);
client.Send (message);
client.Disconnect (true);
}
A: Just adding to the above answer. I also spend lot of time to find out things for sending email using gmail oAuth2 with mailkit in .net. As I am using this to send email to my App users. Thanks to mailkit developers.
Now we need:
*
*Authorization code
*Client ID
*Client Secret
*Refresh Token
*Access Token
You can directly get the Client Id and Client Secret from google console by creating your project.
Next you can enable gmail app from the Google Developers OAuth Playground by using your own OAuth credentials in left top setting button.
After that Select and Authorize the API https://mail.google.com/.
Now you can directly refresh token by this http POST request https://developers.google.com/oauthplayground/refreshAccessToken. you will find the parameter in there.
Now you can directly use this code in your C# code using MailKit:
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
var oauth2 = new SaslMechanismOAuth2(GMailAccount, token.AccessToken);
client.Authenticate(oauth2);
await client.SendAsync(mailMessage);
client.Disconnect(true);
}
Now you will be able to send email through your gmail account from server side.
A: Using MailKit as referenced in the other answers, I was hitting an authentication issue requiring more scopes to be requested from Gmail. For anyone experiencing "Authentication Failed error" with either of the other answers, this answer uses the Gmail API instead in order to avoid requesting more scopes.
Using some pieces from this answer: https://stackoverflow.com/a/35795756/7242722
Here's a complete example which worked for me:
var fromAddress = new MailboxAddress(fromName, fromEmail);
var toAddress = new MailboxAddress(toName, toEmail);
List<MailboxAddress> ccMailAddresses = new List<MailboxAddress>();
if (ccEmails != null)
foreach (string ccEmail in ccEmails)
ccMailAddresses.Add(new MailboxAddress(string.Empty, ccEmail));
var message = new MimeMessage();
message.To.Add(toAddress);
message.From.Add(fromAddress);
message.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = body;
bodyBuilder.TextBody = HtmlUtilities.ConvertToPlainText(body);
message.Body = bodyBuilder.ToMessageBody();
foreach (MailboxAddress ccMailAddress in ccMailAddresses)
message.Cc.Add(ccMailAddress);
GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets()
{
ClientId = <ClientId>,
ClientSecret = <ClientSecret>
},
});
TokenResponse tokenResponse = await authorizationCodeFlow.RefreshTokenAsync("id", <RefreshToken>, CancellationToken.None);
UserCredential credential = new UserCredential(authorizationCodeFlow, "id", tokenResponse);
var gmailService = new GmailService(new BaseClientService.Initializer()
{
ApplicationName = <AppName>,
HttpClientInitializer = credential,
});
Google.Apis.Gmail.v1.Data.Message gmailMessage = new Google.Apis.Gmail.v1.Data.Message();
gmailMessage.Raw = Utilities.Base64UrlEncode(message.ToString());
var result = gmailService.Users.Messages.Send(gmailMessage, "me").Execute();
| |
doc_23536820
|
AWS_KEY: 'myKey'
AWS_SECRET: 'mySecret'
Then
s3 = Aws::S3::Client.new
successfully returns a client, but when I am trying to fetch an object
resp = s3.get_object(bucket:'my-bucket', key:'myFile.txt')
I am getting the following error.
Aws::Errors::MissingCredentialsError:
| |
doc_23536821
|
select col1,
(select min(date_)from t where i.col1=col1) as first_date,
datediff(date_, (select min(date_)from t where i.col1=col1)
) as days_since_first_date,
count(*) cnt
from t i
where anothercol in ('long','list','of','values')
group by col1,days_since_first_date;
Is there a way to use (select @foo:=min(date_)from t where i.col1=col1) safely instead of repeating the subquery? If so, could I do it in the datediff function or the first time the subquery appears (or either one)?
Of course, I could do
select col1,
(select min(date_)from t where i.col1=col1) as first_date,
date_,
count(*) cnt
from t i
where anothercol in ('long','list','of','values')
group by col1,date_;
and then do some simple postprocessing to get the datediff. Or I can write two separate queries. But those don't answer my question, which is whether one can safely define and use the same variable in a query and a subquery.
A: First, your query doesn't really make sense, because date_ has no aggregation functions. You are going to get an arbitrary value.
That said, you could repeat the subquery, but I don't see why that would be necessary. Just use a subquery:
select t.col1, t.first_date,
datediff(date_, first_date),
count(*)
from (select t.*, (select min(date_) from t where i.col1 = t.col1) as first_date
from t
where anothercol in ('long','list', 'of', 'values')
) t
group by col1, days_since_first_date;
As I mentioned, though, the value of the third column is problematic.
Note: this does occur additional overhead for materializing the subquery. However, there is a group by anyway, so the data is being read and written multiple times.
| |
doc_23536822
|
where userid not in (select userid from ship where status in ('1','0'))
and field='web';
This simple statement seems to be running a terribly long time, how do I change the sql so that it can run faster? Thanks.
A: It's best to avoid IN/NOT IN when dealing with large amounts of data. Assuming your userid columns are indexed, something like this may be faster:
SELECT COUNT(DISTINCT u.userid)
FROM user u
LEFT JOIN ship s ON u.userid=s.userid AND s.status IN ('1', '0')
WHERE s.userid IS NULL AND field='web'
| |
doc_23536823
|
int **allocateMatrix(int rows, int columns) {
int i = 0;
int **p = NULL;
p = (int**) calloc(rows, sizeof(int*));
for(; i < rows; i++) {
p[i] = (int*) calloc(columns, sizeof(int));
}
return p;
}
The code works but actually it's allocating double the memory it needs.
For example, if i pass the arguments rows = 2 and columns = 3 i get an array that's 2 rows by 8 columns.
Am i doing something wrong?
Thank you.
Edit:
The content of the matrix (which is loaded from a file) is:
-1 5 0
4 0 2
And this is what the memory looks like after the allocation and the assignment of the values:
A: It is allocating the correct amount of memory, but it allocating more memory than a simple 2D array would use because what you've created is not a simple 2D array.
Assuming a 32-bit system (so sizeof(int) == sizeof(int *), and sizeof(int) == 4), then:
*
*a simple 2D array needs 2 x 3 integers = 6 x 4 = 24 bytes
*a dynamic 2D array needs 2 pointers plus 2 x 3 integers = 8 x 4 = 32 bytes
That's before there's any accounting for overhead in the memory allocations. So not twice, but more.
The advantages of what you're doing is you can write p[i][j] and get the right result. If you simulated a simple 2D array, you'd have to do the subscript calculation yourself: p[i*3+j] or use (*p)[i][j], depending on exactly how you defined the pointer p.
A: AFAICT, your screenshot of the array having 20 elements is because.. you told Netbeans (with that @20) to display 20 elements starting at a memory location (**(matrix)). What happens when you change it to be '@3'?
However, based on this comment:
Actually it's more than the double. I know because when i try to assign values they're not contiguous in memory but they are shifted (i can see it from the watches in the debug window in netbeans).
When you allocate memory, you're calling a library that figures out how to request from the operating system what space it may use and then of what space it's been given by the operating system what it hasn't used yet.
You're making assumptions about how the allocator works that may or may not be correct. It's possible for it to allocate space efficiently in a way you don't expect, especially due to virtual paging mechanisms. In short, contiguous calls to the allocator are not guarenteed to allocate contiguous memory, and rarely will.
If you want to use an array-of-pointers for a double array style structure and absolutely must have contiguous addresses in a more "expected" way, you can try this:
int **allocateMatrix(int rows, int columns) {
int i = 0;
int **p = NULL;
int *d = NULL;
p = (int**) calloc(rows, sizeof(int*));
d = (int*) calloc(rows * columns, sizeof(int));
for(; i < rows; i++) {
p[i] = d + i * columns;
}
return p;
}
(code not tested)
A: that's not because it haves a bidimensional array size (rows*columns*sizeof(int*)) to store the pointers and a bidimensional array space to store the real values (rows*columns*sizeof(int))?
A: You can use the following approach (no extra memory needed for storing data, actually 1D continuous array in memory):
#include <stdlib.h>
#include <stdio.h>
int (*allocateMatrix(int rows, int columns))[]{
int (*p)[columns] = calloc(rows, columns * sizeof(int)),
i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
p[i][j] = rows*i + j;
}
}
return p;
}
int main(int argc, char *argv[]) {
int rows = 4, cols = 5,
(*array)[cols] = allocateMatrix(rows,cols);
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("array[%d][%d] = %2d\n", i, j, array[i][j]);
}
}
free(array);
return 0;
}
Output:
array[0][0] = 0
array[0][1] = 1
array[0][2] = 2
array[0][3] = 3
array[0][4] = 4
array[1][0] = 4
array[1][1] = 5
array[1][2] = 6
array[1][3] = 7
array[1][4] = 8
array[2][0] = 8
array[2][1] = 9
array[2][2] = 10
array[2][3] = 11
array[2][4] = 12
array[3][0] = 12
array[3][1] = 13
array[3][2] = 14
array[3][3] = 15
array[3][4] = 16
| |
doc_23536824
|
It seems that copy constructor of merged_data is not invoked. Instead the default constructor is invoked then only the coordinate related properties are being set when I construct a linestring model from my user defined point. So long before I can run RDP algorithm on my set of points, all other properties are lost.
Following is an example code (cpp.sh/7otfd) that reproduces the issue.
#include <boost/format.hpp>
#include <boost/geometry.hpp>
#include <boost/date_time.hpp>
#include <boost/geometry/geometries/register/point.hpp>
struct gps_coordinate{
double lat;
double lng;
};
struct merged_data{
gps_coordinate location;
std::string label;
};
namespace boost { namespace geometry { namespace traits {
template<> struct tag<merged_data> {typedef point_tag type;};
template<> struct dimension<merged_data> : boost::mpl::int_<2> {};
template<> struct coordinate_type<merged_data> {typedef double type;};
template<> struct coordinate_system<merged_data> {typedef boost::geometry::cs::spherical_equatorial<boost::geometry::degree> type;};
template<> struct access<merged_data, 0>{
static inline double get(merged_data const& p) {return p.location.lng;}
static inline void set(merged_data& p, double const& value) {p.location.lng = value;}
};
template<> struct access<merged_data, 1>{
static inline double get(merged_data const& p) {return p.location.lat;}
static inline void set(merged_data& p, double const& value) {p.location.lat = value;}
};
}}}
int main(){
std::vector<merged_data> complicated{merged_data{gps_coordinate{1, 2}, "Hallo"}, merged_data{gps_coordinate{3, 4}, "World"}};
boost::geometry::model::linestring<merged_data> complicated_polyline;
for(auto m: complicated){
std::cout << boost::format("(%1%, %2%) @%3%") % m.location.lat % m.location.lng % m.label << std::endl;
boost::geometry::append(complicated_polyline, m);
}
std::cout << std::endl << std::endl;
for(auto p: complicated_polyline){
std::cout << boost::format("(%1%, %2%) @%3%") % p.location.lat % p.location.lng % p.label << std::endl;
}
return 0;
}
In this example label attribute is lost. In my actual problem I have many other attributes that I want to retain.
(1, 2) @Hallo (3, 4) @World
(1, 2) @ (3, 4) @
WORKAROUND
A simple trick worked. After creating the linestring I need to set the additinal attributes. Rest of the work will go fine.
for(int i = 0; i != complicated_polyline.size(); ++i){
complicated_polyline[i] = complicated[i];
}
In my actual problem I am using this linestring and applying RDP algorithm on it which filters out a subset of points in simplified_polyline
boost::geometry::model::linestring<stmr::merged_data> complicated_polyline, simplified_polyline;
for(auto m: complicated){
boost::geometry::append(complicated_polyline, m);
}
for(int i = 0; i != complicated_polyline.size(); ++i){
complicated_polyline[i] = complicated[i];
}
boost::geometry::simplify(complicated_polyline, simplified_polyline, th/earthRadiusKm);
std::vector<stmr::merged_data> simplified;
for(auto p: simplified_polyline){
simplified.push_back(p);
}
| |
doc_23536825
|
List<Sale> l1 = new List<Sale>();
l1 = (List<Sale>)HttpContext.Current.Cache.Get("list");
doSomething();
List<Sale> l2 = new List<Sale>();
l2 = (List<Sale>)HttpContext.Current.Cache.Get("list");
doSomething();
List<Sale> l3 = new List<Sale>();
l3 = (List<Sale>)HttpContext.Current.Cache.Get("list");
doSomething();
As I step through the code, the lists l1, l2 and l3 keeps changing their content for unknown reasons. Is there any way to monitor the cached list during debug to see exactly when it changes?
| |
doc_23536826
|
I have the following code snippet:
int main()
{
char avp_val[50];
uint32_t date_value=1477069401;
sprintf(avp_val,"%s",ctime((time_t*)(&date_value)));
return;
}
A: It works for me, but the code is still odd.
I'm not sure why you're using uint32_t to store the time. It should be time_t (or int if you must). Time is not unsigned, it can be negative (I hear there was time before 1970). It also shouldn't be 32 bit; if you do that you'll run out of time in 2038. Most machines use 64 bit time_t these days.
You shouldn't use ctime because it reuses the same pointer. I suspect that's why you're doing the sprintf, to copy the string. Even better, use ctime_r which has you pass in the allocated string.
Here is a much more straightforward way of doing this.
#include <stdio.h>
#include <time.h>
int main() {
time_t date_value = 1477069401;
char date_str[26];
ctime_r(&date_value, date_str);
puts(date_str);
return 0;
}
| |
doc_23536827
|
On the one hand I have an image that changes every X time, It is generated by a php file:
../bg.php
So I've done that I change the background-image with $("header").css().
Running the script like this:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);
But does not change by itself.
A: This is just a guess, but there's a good chance that the browser is just caching the file. You could add cache control headers on the server, or else add a nonce parameter each time you change the background:
var counter = 1, refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?_=" + counter++ + ")");
}, 9000);
It's probably a good idea to go ahead and set the cache headers properly anyway, just to avoid having client browsers needlessly cache the same image over and over again.
A: Maybe because your browser cache it. place a random number at the end of url:
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
}, 9000);
A: window.setInterval(function(){
/// call your function here
}, 5000);
You probably need to call location.reload(); as well.
A: Try to add query to bg.php
var d = new Date();
var n = d.getTime();
$container.css("background-image", "url(bg.php?" + n + ")");
the browser will not load the file with same name again
A: You're going to need to set the background-image to a different URL if you don't want to reload the entire page. However, you can attach a fragment (ex. http://example.com/index.php#fragment), or alternatively a query string (ex. http://example.com/index.php?querystring) to that URL .php file each time. If you are going to reset it every 5 seconds, a good method would be to append a new Date().getTime(); to the end of the image source URL, like this:
var currentDate = new Date();
$container.css("background-image", "url(bg.php#" + currentDate.getTime() + ")");
or even more succinctly/efficiently
$container.css("background-image", "url(bg.php#" + new Date().getTime() + ")");
You should end up with a background-image property of something like url(bg.php#1413320228120). This is good because the fragment won't affect where the browser looks for the image (still bg.php), but it'll consider it a different URL each time and load it again.
Your solution should look something like:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);
| |
doc_23536828
|
Here the whole Code:
the problem is, it jumps to the next sheet even if there is no searched value.
Dim ws As Worksheet
Dim Loc As Range
Dim StrVal As String
Dim StrRep As String
Dim i As Integer
Private Sub CommandButton1_Click()
i = 1
Call Replacing
End Sub
Private Sub CommandButton2_Click()
i = 2
Call Replacing
End Sub
Public Sub Replacing()
StrVal = Userform1.Textbox1.Text
StrRep = Me.Textbox1.Text
if Trim(StrVal) = "" Then Exit Sub
Dim fstAddress As String
Dim nxtAddress As String
For Each ws In ThisWorkbook.Worksheets
With ws
Set Loc = .Cells.Find(what:=StrVal)
fstAddress = Loc.Address
If Not Loc Is Nothing Then
If Not StrRep = "" And i = 1 Then
Loc.Value = StrRep
Set Loc = .Cells.FindNext(Loc)
ElseIf i = 2 Then Set Loc = Range(ActiveCell.Address)
Set Loc = .Cells.FindNext(Loc)
nxtAddress = Loc.Address
If Loc.Address = fstAddress Then
ActiveSheet.Next.Activate '****Here it should jump only if found something on the next sheet****
GoTo repeat
nxtAddress = Loc.Address
End If
If Not Loc Is Nothing Then Application.Goto ws.Range(nxtAddress), False
End If
i = 0
End If
End With
Set Loc = Nothing
repeat:
Next ws
End Sub
the variable "i" which switches between the values 0, 1 and 2 is bound to two buttons. these buttons are "Replace" and "Skip (to next found value)".
A: This code asks on each occurrence of StrVal whether you want to replace the value or skip it.
I found a problem checking if Found_Address = First_Found_Address:
*
*If you've replaced the value in in First_Found_Address it won't find that address again and miss the starting point in the loop.
Also the original source of the code stops at the last value using Loop While Not c Is Nothing And c.Address <> firstAddress. The problem here is that if the value in c is being changed eventually c will be Nothing but it will still try and check the address of c - causing an error (Range Find Method).
My solution to this is to build up a string of visited addresses on the sheet and checking if the current address has already been visited using INSTR.
I've included the code for calling from a button click or from within another procedure.
Private Sub CommandButton1_Click()
FindReplace Userform1.Textbox1.Text, 1
End Sub
Private Sub CommandButton2_Click()
FindReplace Userform1.Textbox1.Text, 1, Me.Textbox1.Text
End Sub
Sub Test()
FindReplace "cd", 1, "ab"
End Sub
Sub FindReplace(StrVal As String, i As Long, Optional StrRep As String = "")
Dim ws As Worksheet
Dim Loc As Range
Dim fstAddress As String
Dim bDecision As Variant
For Each ws In ThisWorkbook.Worksheets
'Reset the visited address list on each sheet.
fstAddress = ""
With ws
Set Loc = .Cells.Find(what:=StrVal, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext)
If Not Loc Is Nothing Then
Do
fstAddress = fstAddress & "|" & Loc.Address
Loc.Parent.Activate 'Activate the correct sheet.
Loc.Activate 'and then the cell on the sheet.
bDecision = MsgBox("Replace value?", vbYesNo + vbQuestion, "Replace or Select value?")
If bDecision = vbYes Then
Loc = StrRep 'Raise the blade, make the change.
'Re-arrange it 'til it's sane.
End If
Set Loc = .Cells.FindNext(Loc)
If Loc Is Nothing Then Exit Do
Loop While InStr(fstAddress, Loc.Address) = 0
End If
End With
Next ws
End Sub
| |
doc_23536829
|
|-- .gitignore
|-- .hgignore
`-- var
|-- .dummy
|-- asdf
`-- log
|-- .dummy
`-- asdf
My .hgignore file uses regular expressions. Part of my .hgignore file is as follows:
^var/(?!\log|.dummy)
^var/log/(?!\.dummy)
I want to track the .dummy files but not the asdf files. hg status returns:
? var/.dummy
? var/log/.dummy
How can I get the same effect in .gitignore? I have tried the following:
/var/**/*
!/var/.dummy
!/var/log/.dummy
But this will not ignore var/asdf as desired. How can I track var/.dummy and var/log/.dummy and ignore var/asdf and var/log/asdf?
A: You don't need to exclude .dummy with regex. Just ignore everything and manually add then all your .dummy.
Ignore affects only on the status command result.
A: If you are only using the .dummy files as placeholders to make sure that you always get those particular (nearly empty) directories when you make a clean checkout, then you should probably just exclude /var and use git add -f var/.dummy var/log/.dummy to start explicitly tracking the placeholder files. The effective result is that you will ignore everything except the .dummy files that you explicitly tracked.
On the other hand, if you plan on expanding the hierarchy of nearly empty directories beyond just var/log, then you might be able to make use of a bit of explanation.
The rules are described in gitignore(5), but sometimes it is difficult to make sense of all the rules and how they interact. The important part is that the last rule wins, and that later rules can only be effective if the directories they act on are not already wholly ignored. This means that you if you have ignored directories, you have to unignore them before you can unignore a bit of their contents (while re-ignoring the rest of their contents).
If you want to automatically ignore everything except .dummy files under var, then the simplest way of doing this involves putting a .gitignore file in your var directory instead of doing it at the top level. I described this solution in another SO answer.
# var/.gitignore
*
!/.gitignore
!.dummy
!*/
*
*Ignore everything in this directory (var).
*But, do not ignore this one .gitignore file (you can leave this out if you are willing to do git add -f to start tracking this .gitignore file).
*Also, do not ignore .dummy files at any depth in the hierarchy rooted at this directory (var).
*Also, do not ignore any directories at any depth under this directory (var).
Without this rule, the first rule will ignore the subdirectories and Git would never even open them to look for .dummy files.
The last two patterns are “recursive” because they do not have a non-trailing slash (meaning that * will match slashes in addition to other characters). A trailing slash makes the pattern match only directories. Leading and embedded slashes effectively anchor the pattern to the location of the .gitignore file (or the root of the repository for patterns from other exclude files). The idea is that a plain *.o should match anywhere, but dir/*.o should only match items directly under dir (and we can use /*.o for this latter effect in dir/.gitignore).
If you can not tolerate a var/.gitinore file, then you can still do what you asked, but you can not automatically “unignore” new .dummy files anywhere under var without editing the exclude patterns.
# .gitignore at root of repository
/var/*
!/var/.dummy
!/var/log/
/var/log/*
!/var/log/.dummy
*
*Ignore everything under the var directory that is a sibling of this .gitignore file.
*But, do not ignore the var/.dummy.
*Also, do not ignore the directory var/log.
*But, ignore everything directly in var/log.
*But, do not ignore var/log/.dummy.
The pattern is: unignore an interesting directory (skip this the first time, since everything is “unignored” by default), ignore what is in the directory, unignore the .dummy file in it. Repeat the pattern for each deeper part of the hierarchy.
You can replace log with * to make it work for any directory directly under var, but it will not automatically work for directories that are deeper (e.g. it would work for var/cache/.dummy, but not for var/log/ssh/.dummy). This is because we are using non-trailing slashes and anchor the patterns. To manually make it work, you have to repeat the pattern to generate more exclusion rules for the deeper parts (unignore interesting dir, ignore contents of dir, unignore file).
| |
doc_23536830
|
I'm working on a website where a map displays different units with real time status changes, and the markers colors should reflect this as part of the functionality.
Can it be done in some way, or is the only way to set the color at "runtime"?
Currently, the map displays all of my markers just fine, in a blue color.
<script src="~/Scripts/GoogleAPI/markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="~/Scripts/GoogleAPI/oms.min.js"></script>
<script>
var markerArray = [];
var usualColor = '0000FF';
var spiderfiedColor = 'ffee22';
var iconWithColor = function(color) {
return 'http://chart.googleapis.com/chart?chst=d_map_xpin_letter&chld=pin|+|' +
color + '|000000|ffff00';
};
var shadow = new google.maps.MarkerImage(
'https://www.google.com/intl/en_ALL/mapfiles/shadow50.png',
new google.maps.Size(37, 34), // size - for sprite clipping
new google.maps.Point(0, 0), // origin - ditto
new google.maps.Point(10, 34) // anchor - where to meet map location
);
function initialize() {
var bounds = new google.maps.LatLngBounds();
var iw = new google.maps.InfoWindow();
var mapOptions = {
zoom: 12,
panControl: false,
zoomControl: false,
scaleControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
streetViewControl: false,
overviewMapControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var oms = new OverlappingMarkerSpiderfier(map);
var mcOptions = {
maxZoom: 12
};
var markerCluster = new MarkerClusterer(map, [], mcOptions);
//Overlapping marker spiderfier
oms.addListener('click', function(marker) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
iw.close();
});
oms.addListener('unspiderfy', function(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setIcon(iconWithColor(usualColor));
markers[i].setShadow(shadow);
}
});
//Populate data section
var addMarker = function(lat, lon, name, locationName, unitHref, wellName, runNo, taskDesc, lastDepth, activityMessage, modeMessage) {
var myLatlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
bounds.extend(myLatlng);
// COMMENTED OUT CUSTOM MARKER DESCRIPTION TO SAVE SPACE
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: iconWithColor(usualColor),
shadow: shadow,
maxWidth: 200
});
marker.desc = content;
oms.addMarker(marker);
markerArray.push(marker);
};
var populateUnits = function() {
@foreach (var location in Model.Location)
{
if (location.Value != null && location.Key != null)
{
@:addMarker('@location.Value.Latitude', '@location.Value.Longitude', '@location.Key.UnitName', '@location.Value.Name', '#', '@location.Key.ViewUnitContract.CurrentRun.Operation.WellContract.Name', '@location.Key.ViewUnitContract.CurrentRun.Id', '@location.Key.ViewUnitContract.CurrentRun.RunTask', '@location.Key.Depth', '@location.Key.ActivityMessage', '@location.Key.ModeMessage');
}
}
};
//Populate the units
populateUnits();
//Add cluster
markerCluster.addMarkers(markerArray, true);
//Fit map
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's how I loop through the array.
function changeMarkers(myArray) {
for (var i = 0; i < myArray.length; i++) {
myArray[i].setIcon(iconWithColor('a51720'));
};
}
Now, at this point I've just called the changeMarkers function upon execution of the script, which works. I've moved the markerArray out of the initialize function, but that's not working either.
Let me clarify what I'd like to do. Say that the page loads, my connection to SignalR spins up and there's no live data available. There might be 10 seconds or 10 hours before I would like to update the color of a marker.
For example, say that two hours have passed, this is what I'd like to do;
function someFunc() {
// Get a reference to the map object
// Loop through its array of markers
// if match between marker-id and SignalR data-id
// update color of marker
}
If I just loop through the markerArray at any given time after the script has executed the first time it will just return an empty set every time.
I'm kind of lost here :)
A: You can set the marker color by calling setIcon(). In your case, when you get an update from SignalR, do something like this...
var markerToChange = findMarker(markerArray, dataFromSignalR); // implement findMarker()
markerToChange.setIcon(iconWithColor(dataFromSignalR.color));
More details in documentation... https://developers.google.com/maps/documentation/javascript/reference#Marker
| |
doc_23536831
|
public partial class frmRegistr : Form
{
public frmRegistr()
{
InitializeComponent();
}
int counter = 0;
int a = 0;
string b;
private void frmRegistr_Load(object sender, EventArgs e)
{
b = label1.Text;
a = b.Length;
label1.Text = "";
timer1.Start();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
if (counter < a)
{
counter++;
label1.Text = b.Substring(0, counter);
}
else
{
timer1.Stop();
}
}
private void label4_Click(object sender, EventArgs e)
{
timer3.Start();
}
private void label4_MouseHover(object sender, EventArgs e)
{
//if this.MouseLeave
label4.BackColor = Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(181)))), ((int)(((byte)(101)))));
}
private void timer2_Tick(object sender, EventArgs e)
{
if (Opacity == 1)
{
timer2.Stop();
}
Opacity += .2;
}
private void timer3_Tick(object sender, EventArgs e)
{
if (Opacity <= 0)
{
this.Close();
}
Opacity -= .2;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox2.UseSystemPasswordChar = true;
}
}
}
A: If you want to define your own password character, use property TextBox.PasswordChar. If you want this in a certain font, use Control.Font
As you only have to do this once, do this in the constructor:
public MyForm : Form
{
InitializeComponents(),
this.textBox1.PasswordChar = '_';
this.textBox11.Font = new Font(...)
};
You can also decide to do this using the visual studio designer.
A: You can setup this in VisualStudio designer, but this is code:
textBox1.PasswordChar = '*';
//* = password character
| |
doc_23536832
|
*
*Create a List using the ListModel
*Add 5 items to the list using the ItemModel I call it store. Items are stored in the store.items which is a list
Each item is created with the ItemModel Object the object name is item
Then each item is added to the items list in the store with store.add(id, name) i.e. store.add(1, 'Candy')
*When I go to save the records in the store object(ListModel).
I loop through the list of items and run a error_check function in the ItemModel.
This issue is when I find a name that is None. It finds it and there is a false positive for every record aftewards.
Why is this happening?
Also I noted below on how I can fix it.
Output
Store Items
ID: 1, Candy
ID: 2, Pop
ID: 3, None
ID: 4, Milk
ID: 5, Meat
Save Items
ID: 1, Candy - No errors
[]
ID: 2, Pop - No errors
[]
ID: 3, None - No errors
['Name "None" is empty']
ID: 4, Milk - No errors
['Name "None" is empty'] <<<< Why is this showing the error from item 3?
ID: 5, Meat - No errors
['Name "None" is empty'] <<<< Why is this showing the error from item 3?
Code
class ListModel:
items = []
def add(self, id=None, name=None):
item = ItemModel(id, name)
# Add the item to the list of items
self.items.append(item)
def save(self):
for i in self.items:
# Check the Item for errors using the error_check function on the ItemModel
i.error_check()
if i.errors is not None:
print(f'ID: {i.id}, {i.name} - No errors')
print(i.errors)
else:
print(f'ID: {i.id}, {i.name} - Has errors')
print(i.errors)
class ItemModel:
id = None
name = None
errors = []
def __init__(self, id, name):
self.id = id
self.name = name
# The following line will fix the error.
# Why is the errors = [] from above not used?
# self.errors = []
def error_check(self):
if self.name is None:
self.errors.append(f'Name "{self.name}" is empty')
if __name__ == '__main__':
store = ListModel()
store.add(1, 'Candy')
store.add(2, 'Pop')
store.add(3, None)
store.add(4, 'Milk')
store.add(5, 'Meat')
print(f'Store Items')
for i in store.items:
print(f'ID: {i.id}, {i.name}')
print(f'\n')
print(f'Save Items')
store.save()
| |
doc_23536833
|
..
<form action="TestMartController" method="post">
<input type="hidden" value="math">
<input type="image" src="<%=request.getContextPath()%>/css/categories/math.jpg">
</form>
..
In my servlet I have
...
private static final String MATH = "WEB-INF/jsp/math.jsp";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = null;
String action=request.getParameter("action");
if(action.equals("math")){
forward = MATH;
flag = 1;
}
RequestDispatcher rd = request.getRequestDispatcher(forward);
rd.forward(request, response);
}
...
When I clicked the image I got null pointer exception. I want to know why it does not pass the value where it should. Since hidden will always get the values to pass.
A: your input type="hidden" field is missing a name="action" attribute. Thus, the action parameter is null.
| |
doc_23536834
|
A: You should be able to refresh the token without getting an authorization code. When the access token is sent back, a refresh token is also issued to you.
{
"access_token": "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl",
"expires_in": 3600,
"restricted_to": [],
"token_type": "bearer",
"refresh_token": "J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR"
}
You should store this refresh token somewhere secure (keychain, encrypted datastore, something similar) and use it to refresh the session when it expires.
You can tell the session is expired when you receive a 401 Unauthorized response from Box for any API request AND you see a WWW-Authenticate header with the value Bearer realm=.
The flow should look something like:
1) Log into Box and get an authorization code
2) Exchange the authorization code for an ACCESS TOKEN and REFRESH TOKEN pair (this only needs to be done once!)
3) Store the refresh token
4) Begin making requests with the API
5) When a 401 Unauthorized is received with a WWW-Authenticate header in an API response, issue a www-form-urlencoded POST request to Box like this:
curl https://www.box.com/api/oauth2/token \ -d 'grant_type=refresh_token&refresh_token={valid refresh token}&client_id={your_client_id}&client_secret={your_client_secret}' \ -X POST
If successful, you'll be issued a NEW access token AND refresh token pair. Store the new refresh token, swap out the old access token for the new one, and resume your API calls from your previous failed call.
Hope that helps!
A: Found a nice package which answers my question. :) https://github.com/sookasa/box.py
A: According to Sikppy Ta
You can save your first token in the file and using the refresh mechanism via such file.
Here is example
static String tokenUrl = "https://app.box.com/api/oauth2/token";
public String getTokenFromFile() throws Exception {
String path = this.tokenFilePath;
File file = new File(path);
String line = "", token = "";
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
token = line;
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String newRefleshToken = refleshToken(token);
String accessToken = newRefleshToken.substring(17, 49);
return accessToken;
}
For refreshToken, you need the HTTPClient
private String refleshToken(String tokencode) throws Exception {
String accessToken = tokencode.substring(17, 49);
String refleshToken = tokencode.substring(105, 169);
tokencode = HttpURLConnectionExample.refreshToken(refleshToken);
writeTokenToTextFile(tokencode);
return tokencode;
}
public static String refreshToken(String newToken) throws Exception {
String urlParameters = "grant_type=refresh_token&refresh_token=" + newToken + "&client_id=" + client_id + "&client_secret=" + client_secret;
String result = sendPost(tokenUrl, urlParameters);
return result;
}
Let me show the sendPost method
String sendPost(String url, String urlParameters) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
| |
doc_23536835
|
The part of the system log for the login on the sd card looks like this:
Aug 25 09:15:46 localhost audit[951]: USER_AUTH pid=951 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:authentication grantors=pam_unix acct="root" exe="/usr/bin/login" hostn
Aug 25 09:15:46 localhost audit[951]: USER_ACCT pid=951 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:accounting grantors=pam_unix acct="root" exe="/usr/bin/login" hostname=
Aug 25 09:15:46 localhost audit[951]: CRED_ACQ pid=951 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:setcred grantors=pam_unix acct="root" exe="/usr/bin/login" hostname=loca
Aug 25 09:15:46 localhost audit[951]: USER_ROLE_CHANGE pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='pam: default-context=unconfined_u:unconfined_r:unconfined_t:s0 selected-context=unconfin
Aug 25 09:15:46 localhost systemd[1]: Created slice User Slice of root.
Aug 25 09:15:46 localhost systemd[1]: Starting User Manager for UID 0...
Aug 25 09:15:46 localhost systemd-logind[640]: New session 11 of user root.
Aug 25 09:15:46 localhost systemd[1]: Started Session 11 of user root.
Aug 25 09:15:46 localhost systemd[1]: Started Getty on tty6.
Aug 25 09:15:46 localhost audit[953]: USER_ACCT pid=953 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:accounting grantors=pam_unix acct="root" exe="/usr/lib/systemd/systemd"
Aug 25 09:15:46 localhost audit[953]: USER_ROLE_CHANGE pid=953 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='pam: default-context=unconfined_u:unconfined_r:unconfined_t:s0 selected
Aug 25 09:15:46 localhost systemd[953]: pam_unix(systemd-user:session): session opened for user root by (uid=0)
Aug 25 09:15:46 localhost audit[953]: USER_START pid=953 uid=0 auid=0 ses=12 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:session_open grantors=pam_selinux,pam_selinux,pam_loginuid,pam_keyinit,pam_limits,pam_s
Aug 25 09:15:46 localhost audit[953]: AVC avc: denied { transition } for pid=953 comm="(systemd)" path="/usr/lib/systemd/systemd" dev="mmcblk0p4" ino=16969648 scontext=system_u:system_r:kernel_t:s0 tcontext=u
Aug 25 09:15:46 localhost systemd[953]: user@0.service: Failed to execute command: Permission denied
Aug 25 09:15:46 localhost systemd[953]: user@0.service: Failed at step EXEC spawning /usr/lib/systemd/systemd: Permission denied
Aug 25 09:15:46 localhost systemd[1]: user@0.service: Failed with result 'protocol'.
Aug 25 09:15:46 localhost systemd[1]: Failed to start User Manager for UID 0.
Aug 25 09:15:46 localhost audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='unit=user@0 comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? te
Aug 25 09:15:46 localhost login[951]: pam_systemd(login:session): Failed to create session: Start job for unit user@0.service failed with 'failed'
Aug 25 09:15:46 localhost login[951]: pam_unix(login:session): session opened for user root by LOGIN(uid=0)
Aug 25 09:15:46 localhost audit[951]: USER_START pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:session_open grantors=pam_selinux,pam_loginuid,pam_console,pam_selinux,pam_namespace,pa
Aug 25 09:15:46 localhost audit[951]: CRED_REFR pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:setcred grantors=pam_unix acct="root" exe="/usr/bin/login" hostname=localhost addr=? ter
Aug 25 09:15:46 localhost audit[951]: USER_LOGIN pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='op=login id=0 exe="/usr/bin/login" hostname=localhost addr=? terminal=tty6 res=success'
Aug 25 09:15:46 localhost login[951]: ROOT LOGIN ON tty6
Aug 25 09:15:46 localhost audit[955]: AVC avc: denied { transition } for pid=955 comm="login" path="/usr/bin/bash" dev="mmcblk0p4" ino=33781637 scontext=system_u:system_r:kernel_t:s0 tcontext=unconfined_u:unc
Aug 25 09:15:46 localhost audit[951]: CRED_DISP pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:setcred grantors=pam_unix acct="root" exe="/usr/bin/login" hostname=localhost addr=? ter
Aug 25 09:15:46 localhost login[951]: pam_unix(login:session): session closed for user root
Aug 25 09:15:46 localhost audit[951]: USER_END pid=951 uid=0 auid=0 ses=11 subj=system_u:system_r:kernel_t:s0 msg='op=PAM:session_close grantors=pam_selinux,pam_loginuid,pam_console,pam_selinux,pam_namespace,pam
Aug 25 09:15:46 localhost audit[1]: SERVICE_STOP pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:kernel_t:s0 msg='unit=getty@tty6 comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=?
Aug 25 09:15:46 localhost systemd[1]: getty@tty6.service: Service has no hold-off time, scheduling restart.
Aug 25 09:15:46 localhost systemd[1]: getty@tty6.service: Scheduled restart job, restart counter is at 2.
Aug 25 09:15:46 localhost systemd[1]: Stopped Getty on tty6.
When I try to ssh to the Pi I get a broken pipe.
packet_write_wait: Connection to 192.168.20.150 port 22: Broken pipe
At this time i have checked on permissions on the file /usr/lib/systemd/systemd, but they are set right:
4 drwxr-xr-x. 14 root root 4096 25. Apr 08:17 systemd
Does anyone has a solution for this?
| |
doc_23536836
|
I have declared a static string which will be assigned in a for loop, later the string get's printed out in the console but it doesn't contain the full context.
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class dothework {
static String info;
public void scrapeinfo() throws IOException {
Document doc = Jsoup.connect("html").get();
Elements el_name = doc.select(".champ-name");
Elements el_speed = doc.select(".speed");
Elements el_altitude = doc.select(".altitude");
el_name.size();
el_speed.size();
el_altitude.size();
for(int i = 0; i < 5; i++) {
String name = el_name.get(i).text();
String speed = el_speed.get(i).text();
String altitude = el_altitude.get(i).text();
String tempinfo = (name+": "+speed+" ("+altitude+")");
System.out.println(tempinfo);
info = tempinfo;
}
}
public void printinfo() {
System.out.println(info);
}
}
While System.out.println(tempinfo); prints out the full information of 5 rows each containing name, speed and altitude the other System.out.println(info); prints out just one row with name, speed and altitude. So the problem is that the strings differ even though I equalized them here:info = tempinfo;. I guess that has something to do with the for-loop and/or with the modifier but I can't figure it out. Please help me.
A: You should be using a StringBuilder to accumulate the lines.
public class Dothework {
StringBuilder info = new StringBuilder();
// for...
info.append(tempinfo).append("\n");
Currently, each iteration of the loop overwrites the previous value stored in the string. You also don't need a static variable here.
| |
doc_23536837
|
Error: find_call_occs : Prod
I'm posting the whole source code at the bottom, but my function is
Function kripke_sat (M : kripke) (s : U) (p : formula) {measure size p}: Prop :=
match p with
| Proposition p' => L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p'' => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p'' => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p'' => ~kripke_sat M s p' \/ kripke_sat M s p''
| Knows a p' => forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' => forall i, kripke_sat M s (Knows i p' )
end.
I know the problem is due to the foralls: if I replace them with True, it works. I
also know I get the same error if my right-hand-side uses implications (->).
Fixpoint works with foralls, but doesn't allow me to define a measure.
Any advice?
As promised, my complete code is:
Module Belief.
Require Import Arith.EqNat.
Require Import Arith.Gt.
Require Import Arith.Plus.
Require Import Arith.Le.
Require Import Arith.Lt.
Require Import Logic.
Require Import Logic.Classical_Prop.
Require Import Init.Datatypes.
Require Import funind.Recdef.
(* Formalization of a variant of a logic of knowledge, as given in Halpern 1995 *)
Section Kripke.
Variable n : nat.
(* Universe of "worlds" *)
Definition U := nat.
(* Universe of Principals *)
Definition P := nat.
(* Universe of Atomic propositions *)
Definition A := nat.
Inductive prop : Type :=
| Atomic : A -> prop.
Definition beq_prop (p1 p2 :prop) : bool :=
match (p1,p2) with
| (Atomic p1', Atomic p2') => beq_nat p1' p2'
end.
Inductive actor : Type :=
| Id : P -> actor.
Definition beq_actor (a1 a2: actor) : bool :=
match (a1,a2) with
| (Id a1', Id a2') => beq_nat a1' a2'
end.
Inductive formula : Type :=
| Proposition : prop -> formula
| Not : formula -> formula
| And : formula -> formula -> formula
| Or : formula -> formula -> formula
| Implies : formula -> formula ->formula
| Knows : actor -> formula -> formula
| EvKnows : formula -> formula (*me*)
.
Inductive con : Type :=
| empty : con
| ext : con -> prop -> con.
Notation " C # P " := (ext C P) (at level 30).
Require Import Relations.
Record kripke : Type := mkKripke {
K : actor -> relation U;
K_equiv: forall y, equivalence _ (K y);
L : U -> (prop -> Prop)
}.
Fixpoint max (a b: nat) : nat :=
match a, b with
| 0, _ => a
| _, 0 => b
| S(a'), S(b') => 1 + max a' b'
end.
Fixpoint length (p: formula) : nat :=
match p with
| Proposition p' => 1
| Not p' => 1 + length(p')
| And p' p'' => 1 + max (length p') (length p'')
| Or p' p'' => 1 + max (length p') (length p'')
| Implies p' p'' => 1 + max (length p') (length p'')
| Knows a p' => 1 + length(p')
| EvKnows p' => 1 + length(p')
end.
Fixpoint numKnows (p: formula): nat :=
match p with
| Proposition p' => 0
| Not p' => 0 + numKnows(p')
| And p' p'' => 0 + max (numKnows p') (numKnows p'')
| Or p' p'' => 0 + max (numKnows p') (numKnows p'')
| Implies p' p'' => 0 + max (numKnows p') (numKnows p'')
| Knows a p' => 0 + numKnows(p')
| EvKnows p' => 1 + numKnows(p')
end.
Definition size (p: formula): nat :=
(numKnows p) + (length p).
Definition twice (n: nat) : nat :=
n + n.
Theorem duh: forall a: nat, 1 + a > a.
Proof. induction a. apply gt_Sn_O.
apply gt_n_S in IHa. unfold plus in *. apply IHa. Qed.
Theorem eq_lt_lt: forall (a b c d: nat), a = b -> c<d -> a+ c< b+d.
Proof. intros. apply plus_le_lt_compat.
apply eq_nat_elim with (n:=a) (m := b). apply le_refl.
apply eq_nat_is_eq. apply H. apply H0. Qed.
Function kripke_sat (M : kripke) (s : U) (p : formula) {measure size p}: Prop :=
match p with
| Proposition p' => L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p'' => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p'' => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p'' => ~kripke_sat M s p' \/ kripke_sat M s p''
| Knows a p' => forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' => forall i, kripke_sat M s (Knows i p' )
end.
A: The "Function" plugin is still very experimental.
In the documentation you can find
term0 must be build as a pure pattern-matching tree (match...with) with λ-abstractions and applications only at the end of each branch.
But I have to agree that this error message is far from being explicit
(normally such error messages should either end with "Please report" or be more user
friendly, I consider this as a bug). It means foralls are not allowed in the body of a Function (I don't know whether or not there are theoretical reasons for this behavior).
So you need to do your definition "by hand" without the help of
Function. Here is a small example you can adapt for your development.
Good luck !
Inductive form : Set :=
| T : form
| K : nat -> form -> form
| eK : form -> form.
Fixpoint size (f : form) : nat := match f with
| T => 1
| K _ f => S (size f)
| eK f => S (S (size f))
end.
Require Import Wf.
Require Import Wf_nat.
Definition R x y := size x < size y.
Lemma R_wf : well_founded R.
apply well_founded_ltof.
Qed.
Lemma lem1 :
forall x n, R x (K n x).
unfold R; intuition.
Qed.
Lemma lem2 :
forall x n, R (K n x) (eK x).
unfold R; intuition.
Qed.
Definition interpret : form -> Prop.
(* we use the well_founded_induction instead of Function *)
refine (well_founded_induction_type R_wf (fun _ => Prop) (fun x f => _)).
destruct x.
exact True. (* ⟦T⟧ ≡ True *)
exact (n = 2 /\ f x (lem1 x n)). (* ⟦K n F⟧ ≡ (n = 2) ∧ ⟦F⟧ *)
exact (forall n:nat, f (K n x) (lem2 x n)). (* ⟦eK F⟧ ≡ ∀n:nat,⟦K n F⟧ *)
Defined.
PS: I am going to fill a bug report with the following simpler version of your code.
Require Import Recdef.
Inductive I : Set :=
| C : I.
Definition m (_ : I) := 0.
Function f (x : I) {measure m x} : Type := match x with
| C => nat -> nat end.
A: The error message has changed in Coq 8.4 but the problem is still there. The new error message is: "Error: Found a product. Can not treat such a term"
This change in error message also lead to Marc's bug being closed:
http://www.lix.polytechnique.fr/coq/bugs/show_bug.cgi?id=2457
| |
doc_23536838
|
Is there a api available in webdriver to check if the browser still exists?
A: After calling driver.close() the value of driver is set to
FirefoxDriver: firefox on WINDOWS(4b4ffb1e-7c02-4d9c-b37b-310c771492ac)
But if you call driver.quit() then it sets the value of driver to
FirefoxDriver: firefox on WINDOWS (null)
So if you're checking the browser window after calling driver.quit() then you will be able to know by below implementation.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.quit();
if(driver.toString().contains("null"))
{
System.out.print("All Browser windows are closed ");
}
else
{
//open a new Browser
}
A: There is no api for it. The best one, you can do is call toString method, which returns a string like this:
SafariDriver . . . null
Then you can call contains method, which does check in the string null is there.
Note that this will work only if the quit is been called.
A: I actively use this for Chrome. At the same time, since I run the browsers with cmd title, I can close the command line to get rid of excessive loads.
from selenium.common.exceptions import WebDriverException
while True:
try:
#do somethings
except selenium.common.exceptions.WebDriverException as e:
if 'chrome not reachable' in str(e):
os.system('taskkill /FI "WindowTitle eq YourTitleIfExistsOrDeleteThisLine*" /T /F')
A: public void isBrowserWindowOpen(WebDriver dr){
RemoteWebDriver driver = (RemoteWebDriver) dr;
try {
driver.getWindowHandles();
} catch (NullPointerException | NoSuchSessionException e) {
//open a new Browser
}
}
A: I've tried Arthur Kuklenko's concept for selenium in python:
try:
driver.window_handles
print("Driver has active window.")
except:
print("Driver doesn't have active window.")
That worked great, but it put this warning message:
WARNING:urllib3.connectionpool:Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7358c3bfa0>: Failed to establish a new connection: [Errno 111] Connection refused')': /session/b622db660ff0b436d0269368dd30bc7e
WARNING:urllib3.connectionpool:Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7358c27d60>: Failed to establish a new connection: [Errno 111] Connection refused')': /session/b622db660ff0b436d0269368dd30bc7e
WARNING:urllib3.connectionpool:Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7358c3b370>: Failed to establish a new connection: [Errno 111] Connection refused')': /session/b622db660ff0b436d0269368dd30bc7e
To ignore this message I've added logging:
import logging
import requests
logging.getLogger(requests.packages.urllib3.__package__).setLevel(logging.ERROR)
Finally the full code stands:
import logging
import requests
from selenium import webdriver
logging.getLogger(requests.packages.urllib3.__package__).setLevel(logging.ERROR)
driver = webdriver.Chrome()
try:
driver.window_handles
print("Driver has active window.")
except:
print("Driver doesn't have active window.")
driver.quit()
try:
driver.window_handles
print("Driver has active window.")
except:
print("Driver doesn't have active window.")
| |
doc_23536839
|
Picture of specific cell formula is in:
Ps: Cell B6 in reference contains a date, so it will only show the value if it's past the current date
Thanks!
UPDATE: I managed to find a computer with excel 2013, in the 'show calculation steps' window I can see that the error results in the evaluation of 'Jog Log'!$M$500 <= DATEVALUE("9/30/2016")
A: In excel 2013 DATEVALUE apparently doesn't allow dates to be entered in the form "9/1/2016" Once all dates were entered in an alternate format "1 September 2016" all #VALUE! errors went away.
| |
doc_23536840
|
if(isset($_POST["submit"]))
{
$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password);
$pre = 'PREFIX';
$suf = '%20ThankYou';
$sms = $pre.$password.$suf;
session_start();
$ch = curl_init("http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
curl_close($ch);
header("Location:password.php?msg=new");
}
else
{
header("Location:register.php?msg=invalid");
}
}
}
?>
this code is working perfect on my local host .. but when i put it on server ... it takes lots of time but the code in curl command is not working it only refers to next page ... i checked that curl is enabled .. if i use only sms api without curl command it sends sms immidiately.... but i want to run both header and also want to hide my sms api.... is there any alternate of this ???
A: Check if simple wget or curl from server to SMS API working fine or not ?
bash~/$wget "http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms"
bash~/$curl "http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms"
If wget or curl is fine then something wrong with your code.
If wget or curl not working from server then might be port 80 is blocked by your ISP for outgoing traffic. Check with ISP for same.
Also you can try
telnet www.perfectbulksms.in 80
and see if its getting connected or not.
| |
doc_23536841
|
Can this be done with Java? If not, is there any 'simple' way to do this with JavaScript (I'm just a noobie at it)?
Thanks.
A: There is! Try this:
Properties properties = new Properties();
properties.put("mail.store.protocol", "imaps");
properties.put("mail.imaps.host", "imap.gmail.com");
properties.put("mail.imaps.port", "993");
properties.put("mail.imaps.timeout", "10000");
Session session = Session.getInstance(properties);
IMAPStore store = null;
Folder inbox = null;
try {
store = (IMAPStore) session.getStore("imaps");
store.connect(username, password);
...
This connects to gmail using IMAP.
If you want to know more, this question is great: Right way to display mail from Gmail
| |
doc_23536842
|
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
return sum() / Int(count)
}
}
sum() works fine but average() has an error.
Binary operator '/' cannot be applied to operands of type
'Self.Element' and 'Int'
I'm not sure why this is. Self.Element is a FloatingPoint. I would expect to be able to divide this.
(I'm also aware that there's a divide-by-zero issue, but I'll fix that later.)
A: You average didnt work because you were trying to divide some FloatingPoint type with integer. Use Element(count) to create new element of same type to divide.
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(count)
}
}
And this works because FloatingPoint protocol declares following initializer,
public init(_ value: Int)
This works with Swift 4.1, since count is Int. For earlier versions of Swift use,
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(Int(count))
}
}
| |
doc_23536843
|
My question is, how do you add or call the Camera in the application? What are the steps in taking a photo, capturing a photo, saving it in a folder, and how to stop a photo from saving (like cancel the saving).
A: There are lots of docs on the Android Camera API. You can use Google to find them. Here is a link to a really helpful article on the Camera API.
http://www.vogella.com/articles/AndroidCamera/article.html
A: I would suggest you to follow the example provided by android
http://developer.android.com/guide/topics/media/camera.html
the easiest and simple instruction.
| |
doc_23536844
|
var queryOptions = new List<QueryOption>()
{
new QueryOption("startDateTime", startDateTime),
new QueryOption("endDateTime", endDateTime)
};
var calendarView = await graphClient.Users[{user_id}].CalendarView
.Request(queryOptions)
.GetAsync();
Is there any way to fetch events from the room calendar using graph client.
Any help is appreciated.
A: You can try this:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var schedules = new List<String>()
{
"roommailboxone@domain.onmicrosoft.com"
};
var startTime = new DateTimeTimeZone
{
DateTime = "2020-09-11T09:00:00",
TimeZone = "Pacific Standard Time"
};
var endTime = new DateTimeTimeZone
{
DateTime = "2020-09-11T18:00:00",
TimeZone = "Pacific Standard Time"
};
var availabilityViewInterval = 60;
await graphClient.Me.Calendar
.Getschedule(schedules,endTime,startTime,availabilityViewInterval)
.Request()
.PostAsync();
It works for me. Here's the output:
| |
doc_23536845
|
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
private EditText etIp, etPort;
int port=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1); //reference to the send button
text = (TextView) findViewById(R.id.textView1); //reference to the text view
etIp = (EditText) findViewById(R.id.editText1);
etPort = (EditText) findViewById(R.id.editText2);
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create file instance
port=Integer.parseInt(etPort.getText().toString());
File file = new File("/mnt/sdcard/bluetooth/AnyFile.txt");
try
{
client = new Socket(etIp.getText().toString(), port);
byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
outputStream = client.getOutputStream();
outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream byte by byte
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
A: I know it is a bit old question. Android 4.4 provides you this functionality.
Please check these instructions
A: Jpg, png, and doc would need to be parsed into a file format the printer recognizes such as pdf or PS. Then the file could be streamed to the printer.
| |
doc_23536846
|
_image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(@"pack://application:,,,/images/tagimages/placeholder.png", UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
_image.Source = src;
_image.Stretch = Stretch.None;
In my project I have a folder called images and a sub folder of that folder called tagimages that contains the placeholder.png. When I run this code I get the following error
"Cannot locate resource 'images/tagimages/placeholder.png'"
What am I doing wrong?
A: It turns out that I should have used
Uri(@"pack://application:,,,/<MyProject>;component/images/tagimages/placeholder.png", UriKind.Absolute);
A: From procedural code you use: @"pack://application:,,,/putyourfilenamehere" for an embedded resource.
Or in other words
BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/Images/myimage.png"));
| |
doc_23536847
|
How do I import from excel to SQL using VB6? Can I make a variable for the excel filename or does the string value of the filename have to be hard coded? If I can make a variable can/should I add set and get to it in order to specify the filename? Thanks
A: With a 32 bit Machine (O/S):
Dim cn As ADODB.Connection
Dim strSQL As String
Dim lngRecsAff As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\test\myfile.xls;" & _
"Extended Properties=Excel 8.0"
'Import by using Jet Provider.
strSQL = "SELECT * INTO [odbc;Driver={SQL Server};" & _
"Server=<server>;Database=<database>;" & _
"UID=<user>;PWD=<password>].MyTable " & _
"FROM [MySheet$]"
Debug.Print strSQL
cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
Debug.Print "Records affected: " & lngRecsAff
cn.Close
Set cn = Nothing
Microsoft KB : 321686 has more ideas.
| |
doc_23536848
|
LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
ActiveWorkbook.Worksheets("RO input sheet").Range("A" & LastRow).Select
Next step should be to merge column A to M in this row, but I can't seem to figure out how this is achieveable. I'm aware of the .Merge method of the Range class, but can't get it to work.
Any hints would be greatly appreciated.
A: There are few attempts available and one could be as follows:
ActiveWorkbook.Worksheets("RO input sheet").Range("A" & lastrow, "M" & lastrow).Merge
| |
doc_23536849
|
So I make the input as required,
@Html.TextBoxFor(modelitem => Model.startdate, new { @class = "datepicker form-control" ,@placeholder = "Select From Date" , @id="from" , @required = "required" })
@Html.TextBoxFor(modelitem => Model.finishdate, new { @class = "datepicker form-control", @placeholder = "Select To Date" , @id = "to" , @required = "required" })
and in javascript, I remove it if the length of the textbox == 0 like in this code below
$(document).ready(function () {
if ($('#to').val().length == 0 && $('#from').val().length == 0) {
$('#from').removeAttr('required');
$('#to').removeAttr('required');
}
})
With this, i can submit the request without fill in the filter date. However, after I select the date in "from" textbox, and leave the "to" textbox as empty, it still can be submitted at first. then I tried to execute again, in "to" textbox says that "this field is required".
So basically, I dont understand why on the first load, it still can be submitted eventhough I leave the "to" textbox as empty. Anyone know what happened? so it seems at the first load, the textbox "from" still detect it as empty, and the javascript still valid.
| |
doc_23536850
|
Line:68
Char: 2
Error: Object required: 'document.all.item(...)'
Code: 800a01a8
Source: VBScript runtime error
It takes a website for requesting songs and spams in requests. I have permission to do this. The error wasn't happening, but now it is. Visual Studio is completely up to date. I'm on windows 10. It did work, but now it throws that error.
I already tried updating windows, and visual studio. Also running it in command prompt did not yield any information.
Option Explicit
Dim browser,x,loginpass,datem,dated,datey,nameArr,numberOfRequests,artistName,songName
set x = CreateObject("wscript.shell")
'Random init shit'
loginpass = "space"
datem = 5
dated = 4
datey = 2019
'Fill this array with names, and it will loop through all of them when you run it.'
nameArr = Array("Becka","Kelly","Jake","Joseph")
'This will control how many times the selected song is voted for'
numberOfRequests = 5
'What is your song pick?'
artistName = "PinkFong"
songName = "Baby Shark"
Dim ree
ree=msgbox("You selected " & songName & " by " & artistName & ". If that is not correct, click no.", 4096+64+4, "Reeee, make sure you don't request the wrong shitty song!")
If ree = vbNo Then
WScript.Quit
End If
Dim name
For Each name in nameArr 'name loop'
'initialize the browser in the most basic form'
set browser = createobject("internetexplorer.application")
browser.statusbar = false
browser.menubar = false
browser.toolbar = false
browser.Width = 1360
browser.Height = 768
browser.top = 100
browser.Left = 100
browser.Resizable = 0
browser.visible = true
'navigate to the login website with the specified djidnumber'
x.AppActivate "Internet Explorer"
browser.navigate([sitenameredacted])
do while browser.busy
wscript.sleep(100)
loop
'input the date and password into the fields provided'
browser.document.all.item("password").value = loginpass
browser.document.all.item("month").value = datem
browser.document.all.item("day").value = dated
browser.document.all.item("year").value = datey
wscript.sleep(500) 'This is line 61'
x.SendKeys "{ENTER}"
do while browser.busy
wscript.sleep(100)
loop
'Deal with the guestname dialogue befor looping song pick 10 times.'
browser.document.all.item("guest_name").Click() 'this is the line 68 in question'
wscript.sleep(500)
Set x = CreateObject("wscript.shell")
x.SendKeys name
wscript.sleep(100)
x.SendKeys "{ENTER}"
wscript.sleep(100)
'Select the button for add your own.'
browser.Document.getElementByID("addyourown_a").click
wscript.sleep(100)
'Loop the song request the number of times given'
Dim loops
For loops = 1 to numberOfRequests
browser.Document.getElementByID("add_your_own_artist_name_id").value = artistName
browser.Document.getElementByID("add_your_own_song_title_id").value = songName
For Each btn In browser.Document.getElementsByTagName("input")
If btn.value = "Save" Then btn.Click()
Next
wscript.sleep(100)
Next
'Submit requests and then close browser for the next name to start.'
For Each btn In browser.Document.getElementsByClassName("djep-guestsubmit")
If btn.href = "javascript:document.ep_form.submit();" Then btn.Click()
Next
wscript.sleep(5000)
browser.Quit
Next 'name loop'
I expect it to set the login info on the site, and then login. Afterwards it inputs the first name on the list and confirms a dialogue. Then, it suggest the same song 5 times. That works flawlessly when I separate it.
When I add a 5 second wait time to line 61 instead of a .5 second wait time nothing changes so I assume the error is above line 61.
A: I actually fixed this. The problem is the line x.SendKeys {ENTER}
Enter doesn't actually advance the dialogue, so it was looking for an element that didn't exist yet, guest_name
| |
doc_23536851
|
$a0 = pointer to destination array
$a1 = source string
$a2 = number of characters to copy
strncpy:
add $t1 $zero $zero #counter
beq $a2 $0 done # if num chars to copy is 0, return.
j cpyLoop
cpyLoop:
beq $t1 $a2 done # if counter == num to copy, end
lb $t2 0($a1) # load the character
beq $t2 $0 done #if we reach the null char, end
sb $a0 0($a1)
addi $a0 $a0 1 #increment the pointer in dest array
addi $a1 $a1 1 #increment the pointer in source array
addi $t1 $t1 1 #increment the counter
j cpyLoop
done:
lb $a0 0(0)
move $v0 $a0
jr $ra
A: to make this post complete i will take part of coat from the dublicate poast mentioned above and complete it:
addi $a3 $a0 0
strncpy:
beqz $a2, out
lb $t0, 0($a1) #load byte
beqz $t0 out
subiu $a2, $a2, 1
sb $t0, 0($a0)
addiu $a0, $a0, 1
addiu $a1, $a1, 1
j strncpy
out:
move $a0 $a3
move $v0 $a0
jr $ra
A: Null-terminating a string is a matter of writing a 0 byte to the terminating offset in the string.
Your attempt, lb $a0 0(0) loads a byte, but because null termination entails writing, you probably meant sb. Using 0(0) as the address doesn't make much sense, nor does $a0 as the source register since it contains an address.
The correct version is sb $zero ($a0). This writes a 0 byte to the offset at $a0 which conveniently points to the tail of the string, either due to encountering the null terminator in the source string or the count expiring, whichever is first.
Here's a minimal, complete example:
.data
dst: .space 12
src: .asciiz "hello world"
.text
main:
la $a0 dst # destination string
la $a1 src # source string
li $a2 5 # number of chars to copy
jal strncpy
# print the destination string
la $a0 dst
li $v0 4
syscall
# print '\n'
li $a0 10
li $v0 11
syscall
li $v0 10
syscall
strncpy:
li $t0 0 # index
strncpy_loop:
# while counter < chars to copy || src[i] != '\0'
beq $t0 $a2 strncpy_done
lb $t1 ($a1) # load src[i]
beqz $t1 strncpy_done
sb $t1 ($a0) # dst[i] = src[i]
addi $t0 $t0 1 # i++
addi $a0 $a0 1 # dst++
addi $a1 $a1 1 # src++
b strncpy_loop
strncpy_done:
sb $zero ($a0) # dst[i] = '\0' null terminate dst
move $v0 $a0
jr $ra
Additional remarks regarding your code:
*
*sb $a0 0($a1) is incorrect; it's attempting to store an address as a byte (use $t2 instead) and $a1 is the source address, not the destination address.
*The precondition beq $a2 $0 done # if num chars to copy is 0, return. doesn't appear necessary. The loop termination conditional already checks this.
*beq $t2 $0 done can be simplified to beqz $t2 done.
*The first j cpyLoop isn't necessary since the loop is the next instruction with fallthrough anyway.
| |
doc_23536852
|
create database test;
it shows
ERROR 3680 (HY000): Failed to create schema directory 'test' (errno: 2 - No such file or directory)
what is problem and what i can do ?
| |
doc_23536853
|
A: No, that is not possible. The table is not interactive.
You can do that manually by adding the assets to your watchlist.
| |
doc_23536854
|
Let's say I have the following list:
((1 2 3) (4 (5 6)))
I want to add them all, so the result should be 21
I started easy, trying to add elements from a nice list ( like (1 2 3) ), and I pretty much did it:
(defun sum (list)
(if list
(+ (car list) (sum (cdr list)))
0)
)
There might be better way of coding that and nicer ways of arranging it, but for now this (almost C-like) indentation style helps me to keep track of my parentheses. And it works.
Unfortunately, it is not good enough for the list in my example. So I tried again:
(defun sum (list)
(cond
( (atom (car list)) (+ (car list) (sum (cdr list))) )
( (list (car list)) (+ (sum (car list) ) (sum (cdr list))))
)
)
This doesn't just looks like overkill, it is overkill as I get a stack overflow error even for simple examples.
Edit:
I managed to write a working (and not so complex) function:
(defun sum (l)
(cond
((null l) 0)
((atom (car l)) (+ (car l) (sum (cdr l))))
((+ (sum (car l)) (sum (cdr l))))
)
)
A: You said:
There might be better way of coding that and nicer ways of arranging it, but for now this (almost C-like) indentation style helps me to keep track of my parentheses. And it works.
Any modern editor will help you with that. The editor indents and counts parentheses. It's very important that indentation is correctly.
The best way to format your Lisp code is like this:
(defun sum (list)
(if list
(+ (car list)
(sum (cdr list)))
0))
The better way to write your function is like this:
(defun sum (list)
(cond ((null list) 0) ; termination test first
((atom (first list)) (+ (first list) ; FIRST not CAR
(sum (rest list)))) ; REST not CDR
(t (+ (sum (first list))
(sum (rest list))))))
A slightly different version:
(defun sum (list)
(if (null list) ; termination test first
0 ; termination value
(destructuring-bind (head . tail) ; bind variables
list ; matching with LIST
(+ (if (atom head) ; all list elements are numbers
head
(sum head))
(sum tail)))))
A: You are very close. Tweak your first variant:
(defun sum (list)
(if list
(+ (sum (car list)) (sum (cdr list)))
0)
)
because (car list) might itself be a list, not necessarily a number.
So now we have to make this work, in case it is a number - and not only car, but a cdr also:
(defun sum (list)
(if (not (listp list))
; an obvious result here...
...
; or else it's a list
(+ (sum (car list)) (sum (cdr list)))
0)
)
But wait, there really are three cases here - a non-empty list, an empty list, and not a list. Amend the code accordingly.
| |
doc_23536855
|
edit: the problem is not that I cannot fill in this whitespace (I can if I just increase the plotBand end to beyond the yAxis.max. The problem is that this area exists at all--I also want the last point to go up to the edge of the chart, so the inner plot bands are not shrunken to scale.
In this example, there's also whitespace in the middle of the circle--that's ok.
http://jsfiddle.net/XEte8/
html:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<div id="container" style="height: 400px"></div>
javascript:
$(function () {
$('#container').highcharts({
chart: {
polar:true
},
yAxis: {
plotBands: [{ // mark the weekend
color: '#FCFFC5',
from: 0,
to: 250,
}],
max:250,
endOnTick:true,
maxPadding:0,
minPadding:0,
startOnTick:true,
tickmarkPlacement:"on"
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
pointStart: Date.UTC(2010, 0, 1),
pointInterval: 24 * 3600 * 1000
}]
});
});
A: What you need is configure tickInterval
javascript:
$(function () {
$('#container').highcharts({
chart: {
polar:true,
marginTop: 10
},
yAxis: {
plotBands: [{ // mark the weekend
color: '#FCFFC5',
from: 100,
to: 250,
}],
max:250,
tickInterval: 50,
startOnTick:true,
tickmarkPlacement:"on"
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
pointStart: Date.UTC(2010, 0, 1),
pointInterval: 24 * 3600 * 1000
}]
});
});
jsfiddle: http://jsfiddle.net/Ng3s5/
A: If the endOnTick option is true, max will sometimes be rounded up. I updated your fiddle with endOnTick:false:
http://jsfiddle.net/XEte8/1/
| |
doc_23536856
|
In the "Profile" is a variable called restrole. In the code below, restrole is being used to control the NEXT screen the user sees (as well as as the data on it):
def user_login(request):
if request.method == 'POST':
# First get the username and password supplied
username = request.POST.get('username')
password = request.POST.get('password')
# Django's built-in authentication function:
user = authenticate(username=username, password=password)
if user:
# Check it the account is active
if user.is_active:
# Log the user in.
login(request, user)
myprofile = user.userprofileinfo
restrole = myprofile.restrole
if restrole == 1:
return HttpResponseRedirect(reverse('authinduction:induct-owner'))
elif restrole == 2:
return HttpResponseRedirect(reverse('authinduction:induct-office'))
elif restrole == 3:
return HttpResponseRedirect(reverse('authinduction:induct-customer'))
elif restrole == 4:
return HttpResponseRedirect(reverse('authinduction:induct-field-work'))
else:
return HttpResponse("Unrecognized Role")
This Part works fine
I can get data from the "request" variable
# First get the username and password supplied
username = request.POST.get('username') <<< data is returned
password = request.POST.get('password') <<< data is returned
The problem
When I execute one of the branches:
if restrole == 1:
return HttpResponseRedirect(reverse('authinduction:induct-owner'))
It goes to the correct function, but "request" does not appear to have any data associated with it. Getting the "username" results in getting a value of "None"
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from authinduction.models import Mstrauthownerrdx
from django.contrib.auth.models import User
def inductowner(request):
username = request.POST.get('username') <<< does NOT work, returns "None"
user = User.objects.get(username=username) <<< causes a DoNotExist error here
What is the best way to come around this problem?
TIA
Update
@Alasdair - Thanks for the response. That did the trick! I noticed that the form itself accesses the user login info as follows:
<input type="text" name="username" placeholder="Enter Your Logon Info">
As metioned above, to get the username (when doing the POST as you have noted), one does
username = request.POST.get('username')
In all of this, I keep seeing "username", but - to solve the problem, one users "request.user". Why is this the case? I ask because I would have never thought to use "request.user" to get the information. If anything, I would have used "request.username"
A: When you return a redirect response, Django does a GET request to that URL, so the POST data is not sent to the new URL.
Since you have already logged-in the user in user_login, I would fetch the user from the request in the next view.
from django.contrib.auth.decorators import login_required
@login_required
def inductowner(request):
user = request.user
...
The login_required ensures that only logged-in users can access the view, so stops anonymous users going straight to the inductowner view.
| |
doc_23536857
|
Thanks in Advance
A: just modify the file(build/core/Makefile) setting PRODUCT_DEFAULT_LANGUAGE and PRODUCT_DEFAULT_REGION to what you want to set... to English in this case
| |
doc_23536858
|
By the way, I wouldn't want to solve this with a command that requires typing the exact name of the embedded repositories because I have many such manifest repositories and I am looking for a generic solution.
EDIT: Here is how to reproduce it yourself: by creating any git repo and within it create another git repo. Go to the parent repo and do git add . and you will see that git gives you the following message:
+++++++++++++++++++
The background:
I have a repository that contains several other embedded repositories.
I manage all the embedded repos using a manifest file (a text file listing each repository and its associated commit and brach) and when I want to sync them I simply checkout the relevant branches and commits based on the manifest file using a bash script I wrote. I am building an app that implements a multi-repo management solution that combines features from submodules and google's repo with the addition of a graphical user interface. That is why I am purposely not using submodules here.
A:
I manage all the embedded repos using a manifest file (a text file listing each repository and its associated commit nd brach) and when I want to sync them I simply checkout the relevant branches and commits based on the manifest file using bash script I have.
You do understand that your bash script implements submodules, right? .gitmodules is a text file listing tracked histories, the origin repositories used to fetch them and the various options you like to use when working with them, and git adding a nested repository lists it in the Git manifest aka index.
If you're wedded to the way you're doing things, I'd suggest a pre-commit hook that scrapes any added gitlinks out of the index and updates-and-re-adds your manifest file, then maybe pops a note if it made any changes. This would be like a five-liner (just like a large majority of git submodule commands can be implemented as five-liners).
git ls-files -cs | grep ^16
will list all your tracked histories. Assuming to keep things simple that you keep your manifest file keyed in that format the update is a straight sort -t$'\t' -usk2,2 | join pipe.
| |
doc_23536859
|
I am going to use one element of each list as a data frame here to better illustrate what I am trying to do.
list1_element1 <- data.frame("0" = c(20, 150, 120),
"10" = c(20, 800, 120))
list2_element2 <- data.frame("0" = c(8, 10, 6),
"10" = c(10, 9, 8))
here is the conditions for k
if 0 < X <= 20 in list 1, k=0.02514
if 100 < X <= 200 in list 1 = 100, k=0.03095
if 700 < X <= 800 in list 1 = 800, k=0.07037
Applying the function x*0.6/k in list 2, this is the result I am looking for
list3_element1<- data.frame("0" = c(190.93, 193.86, 116.31 ),
"10" = c(238.66, 76.73, 155.08))
To clarify, I want to apply the function in list2_element2 using the conditions of k based on list1_element1. The same I want to do for element2 (apply the function in list2_element2 with k based on list1_element1) and so on.
I hope I was clear about what I am trying to do. So any help is very much appreciated because I am not sure from where to start. Thank you.
A: You can create a data frame with the mapped coefficients. I used a nested ifelse statement since you only have 3 conditions. cut() can be used for efficiency and multiple conditions.
d1 <- data.frame(ifelse(list1_element1 <= 20, 0.02514,
ifelse(list1_element1 > 100 & list1_element1 <= 200, 0.03095,
ifelse(list1_element1 > 700 & list1_element1 <= 800, 0.07037, NA))))
mapply(function(x, y)x * 0.6 / y, list2_element2, d1)
X0 X10
[1,] 190.9308 238.66348
[2,] 193.8611 76.73725
[3,] 116.3166 155.08885
| |
doc_23536860
|
The error message I get from ERR_print_errors_fp is:
1998677064:error:0200407C:lib(2):func(4):reason(124):NA:0:port='5354'
1998677064:error:20069076:lib(32):func(105):reason(118):NA:0:
Could anybody explain why is my program unable to bind? I have tested it on Ubuntu - this is why I haven't posted any code - (the problem I have is with a cross-compiled version), OpenSSL version OpenSSL 1.0.1f 6 Jan 2014 and, on Dragino, OpenSSL version is: OpenSSL 1.0.1h 5 Jun 2014.
Also, Dragino version (from the banner) is Dragino-v2 common-2.0.5
I tried using s_server and the result is following:
root@dragino-70decb:~/certificates# openssl s_server -key server.key.pem -cert server.cert.pem -accept 8081
Enter pass phrase for server.key.pem:
Using default temp DH parameters
ACCEPT
which, when s_client is used, produced some communication, thus the socket bind was ok.
So, what is the problem and how do I make this work properly?
I tried Googling the error message but to no avail.
Also, I altered iptables to have ACCEPT default policy on INPUT, FORWARD and OUTPUT chains.
EDIT: Adding the code.
common.h:
#define PORT "5354"
#define SERVER "localhost"
#define CLIENT "localhost"
#define CIPHER_LIST "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
#define SSL_METHOD_ SSLv23_method()
#define SEED_PRNG_() seed_prng(30)
#define SSL_CTX_FLAGS_ SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION
#define DEFAULT_DEPTH_ 4
#define DATA_SIZE_ 256
void init_OpenSSL(void) ;
int seed_prng(int bytes) ;
int verify_callback(int ok, X509_STORE_CTX *store) ;
int write_to_SSL(SSL *ssl, const char* msg, int length) ;
int read_from_SSL(SSL *ssl, char* msg, int length) ;
common.c:
#include "common.h"
void init_OpenSSL(void)
{
if (!SSL_library_init())
{
fprintf(stderr, "** OpenSSL initialization failed!\n");
exit(-1);
}
//Loads error strings for various SSL functions
SSL_load_error_strings();
}
//Not sure if this is good idea
int seed_prng(int bytes)
{
//Seeds PRNG (pseudo random number generator) with the contents of the /dev/urandom file
if (!RAND_load_file("/dev/urandom", bytes))
{
return 0;
}
return 1;
}
int verify_callback(int ok, X509_STORE_CTX *store)
{
char data[DATA_SIZE_];
if (!ok)
{
X509 *cert = X509_STORE_CTX_get_current_cert(store);
int depth = X509_STORE_CTX_get_error_depth(store);
int err = X509_STORE_CTX_get_error(store);
fprintf(stderr, "-Error with certificate at depth: %i\n", depth);
X509_NAME_oneline(X509_get_issuer_name(cert), data, DATA_SIZE_);
fprintf(stderr, " issuer = %s\n", data);
X509_NAME_oneline(X509_get_subject_name(cert), data, DATA_SIZE_);
fprintf(stderr, " subject = %s\n", data);
fprintf(stderr, " err %i:%s\n", err,
X509_verify_cert_error_string(err));
}
return ok;
}
int write_to_SSL(SSL *ssl, const char* msg, int length)
{
int writtenbytes = 0;
int err = 0;
while(err >= 0 && writtenbytes < length)
{
err = SSL_write(ssl, msg + writtenbytes, length - writtenbytes);
if(err < 0)
{
return err;
}
else
{
writtenbytes += err;
}
}
return writtenbytes ;
}
int read_from_SSL(SSL *ssl, char* msg, int length)
{
int err = 0, readbytes = 0;
while(err > 0 && readbytes < length)
{
err = SSL_read(ssl, msg + readbytes, length - readbytes);
if(err < 0)
{
return err;
}
else
{
readbytes += err ;
}
}
return readbytes;
}
server.h:
#include "common.h"
//If the key and the certificate are in the same file, these two can be the same
#define CERTFILE "/root/certificates/server.cert.pem"
#define KEYFILE "/root/certificates/server.key.pem"
//One of the two values below can be NULL but not both
#define CAFILE "/root/certificates/ca-chain.cert.pem"
#define CADIR NULL
SSL_CTX *ctx = NULL;
BIO *acc = NULL;
void cleanup_(void) ;
//Does the setup of the server (loading SSL libraries, loading certificates, etc)
SSL_CTX *setup_server_ctx_(void) ;
//Exchange of data with the clien
int exchange_data_(SSL *ssl) ;
//Does the whole communication once the connection is established
void communicate_(SSL *ssl) ;
//Waits for clients, establishes the connection and then proceeds to
//call communicate_()
void run_server_(void) ;
server.c:
#include "server.h"
#include "logger.h"
#include <sys/time.h>
SSL_CTX *setup_server_ctx_(void)
{
SSL_CTX *ctx;
init_OpenSSL();
//This is my function, gotta investigate it and see what should be there (maybe I got it right?)
SEED_PRNG_();
// This specifies that either SSL or TLS can be used
// Later, we will "filter" out SSLv2
ctx = SSL_CTX_new(SSL_METHOD_);
// NULL return value indicates a failure in creation of SSL_CTX object
if(ctx == NULL)
{
int_error("Setup error: The creation of a new SSL_CTX object failed.");
}
SSL_CTX_set_options(ctx, SSL_CTX_FLAGS_);
// These two functions are used to load trusted CAs
if (SSL_CTX_load_verify_locations(ctx, CAFILE, CADIR) != 1)
{
int_error("Setup error: Error loading CA file and/or directory");
}
if (SSL_CTX_set_default_verify_paths(ctx) != 1)
{
int_error("Setup error: Error loading default CA file and/or directory");
}
// This loads a certificate from a file
if (SSL_CTX_use_certificate_chain_file(ctx, CERTFILE) != 1)
{
int_error("Setup error: Error loading certificate from file");
}
// This loads a private key (can be the same file as certificate)
if (SSL_CTX_use_PrivateKey_file(ctx, KEYFILE, SSL_FILETYPE_PEM) != 1)
{
int_error("Setup error: Error loading private key from file");
}
if (SSL_CTX_set_cipher_list(ctx, CIPHER_LIST) != 1)
{
int_error("Error setting cipher list (no valid ciphers)");
}
// Setting the verify options for ctx context
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback);
// Setting the maximum allowed depth for CA verification
SSL_CTX_set_verify_depth(ctx, DEFAULT_DEPTH_);
return ctx;
}
int exchange_data_(SSL *ssl)
{
int err;
err = write_to_SSL(ssl, "Hello, client!", strlen("Hello, client!"));
if (err <= 0)
{
printf("An unsuccessful write!");
}
else
{
printf("Sent %d bytes.\n", err);
}
// SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN != 0 indicate that the shutdown notification
// was sent from the peer (in this case, the client)
//close(uart_fd);
return (SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) ? 1 : 0;
}
void communicate_(SSL *ssl)
{
long err;
struct timeval tval_before, tval_after, tval_result;
//accepting connection from ssl object (structure)
if (SSL_accept(ssl) <= 0)
{
int_error("Error accepting SSL connection");
}
fprintf(stderr, "SSL Connection opened\n");
if (exchange_data_(ssl))
{
SSL_shutdown(ssl);
}
else
{
SSL_clear(ssl);
}
fprintf(stderr, "SSL Connection closed\n");
SSL_free(ssl);
}
void run_server_(void)
{
BIO *client;
SSL *ssl;
//This call does the setup of the server context (see the function for more info)
ctx = setup_server_ctx_();
// Creates BIO and sets the accept port
acc = BIO_new_accept(PORT);
BIO_set_bind_mode(acc, BIO_BIND_REUSEADDR_IF_UNUSED);
if (!acc)
{
int_error("Error creating server socket");
}
//The first call to BIO_do_accept() binds to the given port
if (BIO_do_accept(acc) <= 0)
{
int_error("Error binding server socket");
}
for (;;)
{
//The second BIO_do_accept() call listens on the acc BIO
if (BIO_do_accept(acc) <= 0)
{
int_error("Error accepting connection from client");
}
client = BIO_pop(acc);
if (!(ssl = SSL_new(ctx)))
{
int_error("Error creating SSL context");
}
SSL_set_bio(ssl, client, client);
communicate_(ssl);
}
}
int main(int argc, char *argv[])
{
run_server_();
return 1;
}
Note: The code is mostly taken from O'Reilly book "Network Security with OpenSSL".
Also, this is not the whole code I have but it is the whole code related to OpenSSL so I didn't deem the other code relevant.
There could be some mistakes in the code due to the copy/paste.
A: After contacting the OpenSSL team, they concluded that the problem with the OpenSSL call BIO_do_accept() was in a call to socket(). The peculiar thing was that the socket() call seemed to be working fine when I wrote a simple server application of my own. So, they proposed a workaround: instead of using BIO calls, I am now using system calls. This reduced the portability of the code but, for my purposes, it doesn't matter.
The run_server_() function now looks like this:
void run_server_(void)
{
BIO *client;
SSL *ssl;
int listenfd, connfd;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
ctx = setup_server_ctx_();
listenfd = socket (AF_INET, SOCK_STREAM, PROTOCOL);
if(listenfd < 0)
{
printf("serv_socket unsuccessful\n");
exit(EXIT_FAILURE);
}
printf("Created socket!\n");
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl (INADDR_ANY);
servaddr.sin_port = htons (atoi(PORT));
if(bind(listenfd, (const struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
printf("bind() error\n");
exit(EXIT_FAILURE);
}
printf("Binded port/socket!\n");
if(listen(listenfd, LISTENQ) < 0)
{
printf("listen() error\n");
exit(EXIT_FAILURE);
}
printf("Listening!\n");
for(;;)
{
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
if(connfd < 0)
{
printf("accept() error\n");
}
printf("Accepted!\n");
client = BIO_new(BIO_s_socket());
if (client == NULL)
{
printf("error creating BIO\n");
}
BIO_set_fd(client, connfd, BIO_NOCLOSE);
if (!(ssl = SSL_new(ctx)))
{
server_error_("Error creating SSL context");
}
SSL_set_bio(ssl, client, client);
communicate_(ssl);
close(connfd);
}
}
| |
doc_23536861
|
setContentView(R.layout.inbox);
when i hover over the error mark i get
Multiple markers at this line
- Inbox cannot be resolved or is not a field
- R cannot be resolved to a variable.
Im getting this on all of my Activity
UPDATE:
some errors from my XML that is causing the R.java to not be rebuilt durring the cleaning proces
Description Resource Path Location Type
error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/friendrowbg'). friendslistselector.xml /atmebeta/res/layout line 8 Android AAPT Problem
error: Error: No resource found that matches the given name (at 'background' with value '@drawable/friendslistselector'). friend_row.xml /atmebeta/res/layout line 1 Android AAPT Problem
error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/friendrowbg'). friendslistselector.xml /atmebeta/res/layout line 2 Android AAPT Problem
error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/friendrowbg'). friendslistselector.xml /atmebeta/res/layout line 6 Android AAPT Problem
error: Error: No resource found that matches the given name (at 'listSelector' with value '@drawable/friendslistselector'). friends.xml /atmebeta/res/layout line 29 Android AAPT Problem
A: You should not import android.R. There is up to a couple minutes (~2) for R.java to be recreated at times.
If R.java is not created then there is a problem within your res folder. What helped the OP (found in the comments as well) was the @drawable reference is referencing items that are located within res/drawable/, not within res/layout. The layout folder is only for layout xml files, while the drawable is for your apps images.
A: You may want to check a similar question posted before:
"R cannot be resolved to a variable"?
Basically, it seems that it could be an error on an XML or your code that prevents R to be generated again, hence, it's missing. In worst scenario some configuration on your project may be missing or a library project may be causing the issue.
Check that question or provide more information about your set up.
A: Your project itself will have an R file for your local resources (everything in the /res/ directory).
If your project is com.example.app... add this line
import com.example.app.R;
A: The R file is built automatically when the project is built. Do you have "Build Automatically" checked (it's under the Project menu)? If not, doing a Clean will remove the R file, but a Build will not be executed. You'll need to either select Build, or check the Build Automatically.
You can also go to Window > Show View > Progress and see if a build is in progress. Doing a Clean should trigger a build if Build Automatically is checked.
| |
doc_23536862
|
I have an object "pet", which could be one of, "cat", "dog" etc. So I have created an "pet" class with a "petType" enum to store this.
Now this is where it gets tricky. If an "pet" is a "cat", then its "food" could be one of "fish", "milk" etc. If it is a "dog" then its "food" could be "meat", "biscuits" or something.
Now should I create a big enum for "fish", "milk", "meat" and "biscuits" and somehow code it so that a "cat" cannot be assigned "food.meat"?
It wouldnt really make sense for my "pet" class to have a "catfood" and "dogfood" enum, because thats not extensible and it will end up storing loads of enums that are null.
Is there an elegant solution to this that I'm not seeing?
A: Try #2. Seems to be correct
interface IPet { }
class Cat : IPet
{
public void eat(CommonFood food) { }
public void eat(CatFood food) { }
}
class Dog : IPet
{
public void eat(CommonFood food) { }
public void eat(DogFood food) { }
}
interface IFood { }
abstract class CommonFood : IFood { }
abstract class CatFood : IFood { }
abstract class DogFood : IFood { }
class Milk : CommonFood { }
class Fish : CatFood { }
class Meat : DogFood { }
class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog();
myDog.eat(new Milk()); // ok, milk is common
myDog.eat(new Fish()); // error
}
}
A: First, cat and dog should probably be subclassed from pet, assuming there are some common properties of all pets.
Next, I'm not clear what you are planning to do with food. As an object model does a pet hold a type of food or will there be methods such as eat that will take food as an argument?
A: i don't know about your cat, but my cats eat meat and very little else!
and eating table scraps like biscuits is bad for dogs (and cats)
but that aside, why are you screwing around with enums? and why does your 'pet' object have a 'petType' property? A simple/direct representation would be a Pet class with Cat and Dog subclasses, but a more practical representation would be a Pet interface that could be applied to any Animal object.
A: I agree with Tautologistics on having Cat and Dog subclass Pet (or implement a Pet interface!), rather than having an explicit PetType enumeration and field. Explicit "type flags" are out of step with true OO design.
As for the food relationship, you might consider implementing two concepts:
*
*A "business rule" on Pet, implemented via an acceptsFood(FoodEnum food) method. This method would be responsible for checking the legality of a food assignment.
*A "favorite food" property of any Pet (subclass) instance that allows the individual pet to have a favorite food identified (out of the set of foods that are actually accepted by its species).
A: It sounds like you need to consider cat/dog food as sort of strategies, and compose appropriate food with appropriate pet using a simple factory.
Here is one variation in Ruby.
class CatFood
attr_reader :items
def initialize
@items = ['fish', 'milk']
end
end
class DogFood
attr_reader :items
def initialize
@items = ['meat', 'biscuits']
end
end
class NoFood
attr_reader :items
def initialize
@items = []
end
end
class Pet
attr_reader :food
def initialize(food)
@food = food
end
end
class PetFactory
def create_dog
Pet.new(DogFood.new)
end
def create_cat
Pet.new(CatFood.new)
end
def create_unknown_pet
Pet.new(NoFood.new)
end
end
| |
doc_23536863
|
I have applied Canny edge detection to three different images and I got three images of edges of circles of three different sizes. I want to show these three edges of circles of different radius in same figure but with different colors to compare them. How it can be done?
I have tried to use imfused command but did not get desired result. Please help me
A: Here is a quick solution but it might not be the best method:
% edge detection
I = imread('circuit.tif');
bw1 = edge(I,'canny');
bw2 = edge(I,'sobel');
% black result image (it could be anything else)
imrgb = repmat(zeros(size(bw1)), [1 1 3]);
% color matrices, red and green
rm = repmat(cat(3,1,0,0),size(bw1,1),size(bw1,2));
gm = repmat(cat(3,0,1,0),size(bw1,1),size(bw1,2));
% logical matrices with same dimension as the result image
lm1 = repmat(bw1,[1 1 3]);
lm2 = repmat(bw2,[1 1 3]);
% overwrite pixel positions from the color matrices according to the logical matrices
% logical matrices were derived from the edge detected ones
imrgb(lm1) = rm(lm1);
imrgb(lm2) = gm(lm2);
imshow(imrgb)
| |
doc_23536864
|
What does that mean? I've created a folder, then inside this folder, I've created a Program, then inside this program I've created this email. I can't create a email without a Program - as far as I know anyway - so I'm a bit lost.
Thanks
EDIT: Adding my request:
I'm building my request with php:
<?php
$email = new CreateEmail();
$email->name = "MyEmailName";
$email->folder = new stdClass();
$email->folder->id = 3211;
$email->folder->type = "Folder";
$email->template = 0003;
$email->subject = "This email was created with an api call";
print_r($email->postData());
class CreateEmail{
private $host = "mydetails";
private $clientId = "mydetails";
private $clientSecret = "mydetails";
public $name;//name of new email, required - NOCEmai
public $folder;//json object with two members, id and type(Folder or Program), required
public $template;//id of parent template
public $description;//optional description of new
public $subject;//subject line of new email
public $fromName;//from name of new email
public $fromEmail;//from email of new email
public $replyEmail;//reply to address of new email
public $operational;//boolean operational status of email
public function postData(){
$url = $this->host . "/rest/asset/v1/emails.json?access_token=" . $this->getToken();
$ch = curl_init($url);
$requestBody = $this->bodyBuilder();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_getinfo($ch);
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
private function bodyBuilder(){
$requestBody = "&name=" . $this->name . "&folder=" . json_encode($this->folder) . "&template=" . $this->template;
if (isset($this->description)){
$requestBody .= "&description=" . $this->description;
}
if (isset($this->subject)){
$requestBody .= "&subject=" . $this->subject;
}
if (isset($this->fromName)){
$requestBody .= "&fromName=" . $this->fromName;
}
if (isset($this->fromEmail)){
$requestBody .= "&fromEmail=" . $this->fromEmail;
}
if (isset($this->replyEmail)){
$requestBody .= "&replyEmail" . $this->replyEmail;
}
if (isset($this->operational)){
$requestBody .= "&operational=" . $this->operational;
}
return $requestBody;
}
}
| |
doc_23536865
|
My installed matplotlib version is 3.3.1
backtrader 1.9.76.123
python 3.8.5
the entire code posted below:
from matplotlib.dates
import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,MONTHS_PER_YEAR,
DAYS_PER_WEEK,SEC_PER_HOUR, SEC_PER_DAY,num2date, rrulewrapper,
YearLocator,MicrosecondLocator)
import alpaca_backtrader_api
import backtrader as bt
from datetime import datetime
#import matplotlib
ALPACA_API_KEY = "XXXXX"
ALPACA_SECRET_KEY = "XXXX"
ALPACA_PAPER = True
class SmaCross(bt.SignalStrategy):
def init(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.CrossOver(sma1, sma2)
self.signal_add(bt.SIGNAL_LONG, crossover)
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)
store = alpaca_backtrader_api.AlpacaStore( key_id=ALPACA_API_KEY,secret_key=ALPACA_SECRET_KEY,paper=ALPACA_PAPER)
if not ALPACA_PAPER:
broker = store.getbroker() # or just alpaca_backtrader_api.AlpacaBroker()
cerebro.setbroker(broker)
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData
data0 = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(2015, 1, 1), timeframe=bt.TimeFrame.Days)
cerebro.adddata(data0)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.plot()
A: Downgrade to matplotlib 3.2.2 until the bug in backtrader is fixed.
Here is the fix pull request: https://github.com/mementum/backtrader/pull/418.
pip uninstall matplotlib # or conda
pip install matplotlib==3.2.2
A: Mac Big Sur
for me it only worked if:
Downgrade python3.9 to python 3.8
then I downgraded matplotlib==3.2.2
A: For both python 3.8.x and 3.9.x, I solved the problem by using specific version of matplotlib==3.2.2
pip install matplotlib==3.2.2
By default, I used matplotlib==3.4.x version and the problem occured.
A: I suffered the same problem like you did, your link provided has the perfect solution. just get rid of warnings from locator.py
https://community.backtrader.com/topic/981/importerror-cannot-import-name-min_per_hour-when-trying-to-plot/8
A: All of the above answers are fine. The problem is not with Matplotlib though. The Backtrader library hasn't kept up with the Matplotlib updates. You can do the off-label Backtrader update suggested by Joel Brigate above...or you can make a simple mod to locator.py file (backtrader.plot):
Just change:
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR,
SEC_PER_MIN, MONTHS_PER_YEAR, DAYS_PER_WEEK, SEC_PER_HOUR,
SEC_PER_DAY, num2date, rrulewrapper, YearLocator,
MicrosecondLocator, warnings)
to:
from matplotlib import warnings
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
MONTHS_PER_YEAR, DAYS_PER_WEEK, SEC_PER_HOUR,
SEC_PER_DAY, num2date, rrulewrapper,
YearLocator, MicrosecondLocator)
You'll note that the warnings import now comes directly out of matplotlib rather than matplotlib.dates. This is the offending issue within locator.py.
A: Here is my solution:
python -m pip uninstall matplotlib
python -m pip uninstall backtrader
python -m pip install backtrader
python -m pip install matplotlib==3.2.2
Enjoy!
A: I couldn't install matplotlib==3.2.2 nor the patch without uninstalling backtrader first.
So, this worked for me in the end:
*
*Uninstall backtrader:
pip uninstall backtrader
*Install the patch provided in the above solution:
pip install git+https://github.com/mementum/backtrader.git@0fa63ef4a35dc53cc7320813f8b15480c8f85517#egg=backtrader
*If necessary, install matplotlib again:
pip install matplotlib
A: As pointed out above, the issue is addressed in this pull request and the patch is the latest commit to master, but there hasn't been a release since 2019-05.
You can install the patched version like so:
pip install git+https://github.com/mementum/backtrader.git@0fa63ef4a35dc53cc7320813f8b15480c8f85517#egg=backtrader
You could alternatively specify the required commit in requirements.txt like so:
-e git+https://github.com/mementum/backtrader.git@0fa63ef4a35dc53cc7320813f8b15480c8f85517#egg=backtrader
…then pip install -r requirements.txt
After installing with either method, you can confirm the versions installed with pip freeze:
...
backtrader==1.9.76.123
...
How to install from git
A: I could not install matplotlib==3.2.2 with python 3.9 .
Here is how did I fix this issue:
$ pip uninstall backtrader
$ pip install git+https://github.com/mementum/backtrader.git@0fa63ef4a35dc53cc7320813f8b15480c8f85517#egg=backtrader
Reference:
Github: Fix ImportError from matplotlib.dates
#418
A: @laffuste solution of downgrading to version 3.2.2 of matplotlib solved the issue for me. PR to fix the issue is still open, you can also follow this forum for more info on the problem:
A: Mac Big Sur. I did the same: python 3.8.5, uninstall matplotlib, install matplotlib==3.2.2
I'm new at this so I first tried the easy way, through anaconda.org, but could not find version 3.2.2. Then tried it from the Jupyter notebook with conda install... didn't work. I finally did it straight through terminal, which worked fine.
| |
doc_23536866
|
I'm try use React.NET , but it's cannot use Material-UI conponent .
even use webpack to compiler it or Material-UI just only for NodeJS ?
Thank you
A: Can you show the error?
Material-UI and any other javascript library is totally not (ASP.NET/Django/Spring/Node.js) related, these are just a bunch of assets files.
| |
doc_23536867
|
Visit this page: http://sta.manageorsell.com/breakpoint.php with both Chrome and either firefox or IE.
You will see my point. I've totally simplified the source code. I've even added a setInterval to insure it had nothing to do with elements not being loaded yet.
I'm stupified...
In todays responsive world a browser compatible method for testing the viewport / window width has to be among the most common needs for developers
What sayeth the group ?
Jay
CompuMatter
A: I think your are fooled be the good old IE quirks mode trap :-)
http://en.wikipedia.org/wiki/Quirks_mode
You have not defined at DOCTYPE for your page, which will sent IE into quirks mode, which will simulate IE6, which uses another box-model then the others.
IE6 uses border-box as box-model and the others uses content-box as box-model.
See this post about the box-model: http://css-tricks.com/the-css-box-model/
Try adding a DOCTYPE to your page, I would suggest the HTML 5 doctype:
As an extra service info, I just tried out your sample in Chrome 29, Firefox 23 and IE 11, which all return the same widths.
| |
doc_23536868
|
I want to insert the information for "init_cells" in a generic way so that I don't have to care how many objects (I hope this term is right) are in the array.
In reference to the demo there is this example code:
$('#slider123').TimeSlider({
start_timestamp: current_time - 3600 * 12 * 1000,
init_cells: [
{
'_id': 'c1',
'start': (current_time - (3600 * 5.4 * 1000) + 1234),
'stop': current_time - 3600 * 3.2 * 1000,
'style': {
'background-color': '#76C4FF'
}
},
{
'_id': 'c2',
'start': (current_time - (3600 * 2.1 * 1000))
}
]
});
This looks for me like a JSON array of two objects?!
I tried this in the meantime, to store every object in an centralized array.
var str1 = [{
'_id':'c1','start':tV1Start,'stop':tV1End,'style':{'background-color':'#76C4FF'}}];
var str2 = [{
'_id':'c2','start':tV1Start2,'stop':tV1End2,'style':{'background-color':'#76C4FF'}}];
var arr = [];
arr.push(str1);
arr.push(str2);
But how can I extract all the stored inforamtion in the array "arr" inside of the jQuery function for init_cells?
This snipped is not working
init_cells:arr
But this works:
init_cells:arr[0]
But how can I create the full timeline by passing the variable arr into the jQuery function without taking care how many elements are inside of the array arr?
A: That is because in your "centralised array" you are actually storing an array of array of objects—and you actually need an array of objects, without the additional nesting. arr is an array, and instead of concatenating str1 and str2, you are pushing them into arr instead.
Therefore, your code will produce an incorrect structure that is not recognised:
*
*Array (this is your arr)
*
*Array (this is your str1)
*
*Object
*Array (this is your str2)
*
*Object
To fix the issue, use .concat() instead of .push():
var arr = [].concat(str1).concat(str2);
This will then generate the following structure, which is what you need:
*
*Array (this is your arr)
*
*Object
*Object
A: You have an extra wrapping array for each of your individual objects
Remove the outer [] from each like:
var str1 = {'_id':'c1','start':tV1Start,'stop':tV1End,'style':{'background-color':'#76C4FF'}};
If you had this all stored in database and returned full array from database all you would have to do is something like:
$.getJSON('/path/to/data', function(responseData){
$('#slider123').TimeSlider({
start_timestamp: current_time - 3600 * 12 * 1000,
init_cells: responseData // pass response data array directly as property value
});
});
| |
doc_23536869
|
In simple terms, the project will be pulling information from a Web Service and shall display data in a Grid-Like fashion. The information will simply be boxes with text inside.
There will be other pages such as Information (static) and Tweets which is self explanatory.
I would like to use the Panorama Template as it's quite pretty and fluid. The application does not require any such user validation, i.e. there will be no text-boxes for the user to input any data. It simply displays data.
The most important key is functionality but native look and feel is equally as important.
I just want to get a feel of what other people think and which app template is best suited for the type of project.
Thank you for your input.
A: Depends what design you want really. I like apps that have a panorama as the first screen and it quite common. I would also avoid using a Pivot unless you are actually doing something like the email app where you swipe between different filters on a list, as that's its intended purpose.
All the templates are essentially just picking a pre made layout. If you change your mind later you won't have any issue changing it. There's no fundamental difference in the app.
| |
doc_23536870
|
sqlite3 * db1;
sqlite3 * db2;
sqlite3_open("file:db1?mode=memory?cache=shared", &db1);
sqlite3_open("file:db2?mode=memory?cache=shared", &db2);
sqlite3_exec(db1, "create table t1 (a int)", NULL, NULL, NULL);
sqlite3_exec(db2, "create table t2 (a int)", NULL, NULL, NULL);
Is it possible to assign a name to db1, e.g. "db1", and to db2, e.g. "db2" so that I can do
sqlite3_exec(db1, "select * from db1.t1 inner join db2.t2 on db1.t1.a = db2.t2.a", NULL, NULL, NULL);
Thanks in advance.
A: You have to attach the database see
| |
doc_23536871
|
I can narrow it down to literally the multiplication of a float onto the time object:
import numpy, time
# base check works
ts = numpy.arange(10, dtype=numpy.int64)
print(type(ts[0]), " and should be numpy.int64 : ", end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")
# time object works
ts = numpy.arange(10, dtype=numpy.int64) + int(round(time.time()))
print(type(ts[0]), " and should be numpy.int64 : ", end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")
# float itself works
ts = numpy.arange(10, dtype=numpy.int64) + numpy.int64(round(1e9))
print(type(ts[0]), " and should be numpy.int64 : ", end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")
# for some reason the multiplication of both does not work
ts = numpy.arange(10, dtype=numpy.int64) + int(round(time.time()*1e9))
print(type(ts[0]), " and should be numpy.int64 : ", end = "")
if isinstance(ts[0], numpy.int64) : print("Check OK!")
else : print("Check FAILED!")
My output is :
<class 'numpy.int64'> and should be numpy.int64 : Check OK!
<class 'numpy.int64'> and should be numpy.int64 : Check OK!
<class 'numpy.int64'> and should be numpy.int64 : Check OK!
<class 'numpy.int64'> and should be numpy.int64 : Check FAILED!
The first checks above work, as they should, since to my understanding the dtype of ts should remain int64 (and it does obviously).
The last check however fails, EVEN THOUGH the dtype is indicated as int64. I do not understand why.
I ran the code on a python3.6.8 with numpy1.16.4. The machine is 64bit, so the natural int should be 64bit as well, but either way this should not matter, since I specifically state int64 in the numpy array (AFAIK).
I actually have 3 different machines, with different python versions (python 3.5.3 & numpy 1.16.2) and (3.6.8 and 1.16.2) yield the same failed check. One of them wasn't even set up by myself, but is a managed system. I believe this is not related to my local installation.
| |
doc_23536872
|
data1 = pd.read_csv('001.txt', sep='\n')
stop = set(stopwords.words('english'))
def clean(doc):
stop_free = " ".join([i for i in doc.lower().split() if i not in stop])
return stop_free
data1_clean = [clean(doc).split() for doc in data1]
| |
doc_23536873
|
With using debugger I go through code. When I reach row with Load frmTest (there is a specific form) it takes about 1.5 - 2 seconds to continue in Form_Load handler.
I tried to search for some documentation, but failed... well at least finding any information about what Load Sub does before Form Load event triggers.
So, how does the VB.Global.Load work?
A: There're so many things that can go wrong.
That's how I would analyze this case.
*
*Check if you have Form_Initialize method, if not - create it and check if delay's before or after this method's call.
*Check if you have any private fields on a form level. If there're heavy objects there they may be initialized before the form Load and it may take the time. Especially actual for the COM objects.
*If this happens for a single form only I would try to understand what's so special about this exact form and if needed remove everything to the ground to detect the problem.
A: Assuming this is VB6 (never heard of 'VB.Global.Load' in that context), see Life Cycle of Visual Basic Forms
A: Thanks @Alex K. for the answer:
The biggest job it does it to initialize all the controls/activex
components sited on the form (or anything in the global scope declared
As New) so if you have any third party ones then that's something to
investigate.
| |
doc_23536874
|
The part that does NOT work: `
-(IBAction)followTwitter:(id)sender {
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"twitter_on_file" ] == nil) {
UIAlertView *allert = [[UIAlertView alloc] initWithTitle:@"Uh oh!" message:@"You have not linked your twitter account quite yet! Head to My Account settins to do so." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[allert show];
} else {
ACAccountStore *store1 = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [store1 accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
if ([twitterAccountType accessGranted]) {
[store1 requestAccessToAccountsWithType:twitterAccountType options:nil completion:^(BOOL granted, NSError *error) {
arrayOfUsernames = [[NSMutableArray alloc] init];
iosAccounts = [store1 accountsWithAccountType:twitterAccountType];
for (ACAccount *accou in iosAccounts) {
[arrayOfUsernames addObject:accou.username];
}
NSString *usernameOnFile = [[NSUserDefaults standardUserDefaults] objectForKey:@"twitter_on_file" ];
int tracker = 0;
for (NSString *username in arrayOfUsernames) {
if ([username isEqualToString:usernameOnFile]) {
NSLog(@"Using twitter account: %@", username);
STTwitterAPI *twitterAPI = [STTwitterAPI twitterAPIOSWithAccount:iosAccounts[tracker]];
[twitterAPI verifyCredentialsWithSuccessBlock:^(NSString *username) {
NSLog(@"Successfully authenticated the user");
} errorBlock:^(NSError *error) {
NSLog(@"Erorr: %@", error);
}];
NSLog(@"Twitter API: %@", twitterAPI);
[twitterAPI postFriendshipsCreateForScreenName:@"kickscaterer" orUserID:nil successBlock:^(NSDictionary *befriendedUser) {
NSLog(@"Befriend %@", befriendedUser);
} errorBlock:^(NSError *error) {
NSLog(@"Error: %@", error);
}];
} else {
tracker++;
}
}
}];
}
}
}
`
The part that DOES work:
STTwitterAPI *twitter= [STTwitterAPI twitterAPIOSWithAccount:iosAccounts[indexForAlert.row]];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *username) {
// ...
NSLog(@"Username: %@", username);
// [self.tableView reloadData];
[[NSUserDefaults standardUserDefaults] setObject:twitter.userName forKey:@"twitter_on_file"];
} errorBlock:^(NSError *error) {
NSLog(@"Error: %@", error);
// ...
}];
[twitter postFriendshipsCreateForScreenName:@"didi4" orUserID:nil successBlock:^(NSDictionary *befriendedUser) {
NSLog(@"Befriend %@", befriendedUser);
} errorBlock:^(NSError *error) {
NSLog(@"Error: %@", error);
}];
Thanks!
A: The postFriendshipsCreateForScreenName: method should be called inside the success block, at the same level than the log "Successfully authenticated the user".
| |
doc_23536875
|
General Solution:
int max = 0;
for( i = 0; i< n-d; i++){
int min = MX;
for( j = i; j < i + d; j++)
if(min > A[j])
min = A[j];
if(max < min)
max = min;
}
printf("%d\n", max);
But it will take O(n x d) not O(n)
Better Solution: using Range_minimum_query
int max = 0;
for( i = 0; i< n-d; i++){
int min = RMQ( i , i + d);
if(max < min)
max = min;
}
printf("%d\n", max);
It will take O(log(d) * n) as RMQ's average time is log(d)
I thought this problem in my head about 15 days, but not renovation yet.
Could anyone solve this problem efficiently?
i/o data: 1<n<10^7 1<d<n
input : n = 10, d = 3, A[i] > 0
1, 3, 2, 4, 5, 6, 7, 8, 9, 10
result : 8 //= max(1, 2, 2, 4, 5, 6, 7, 8)
A: Following the Range minimum query philosophy (which is good for random access), I would use a Double-ended queue (which is good for sequential access), which offers a average complexity of O(1) for all operations*.
*except insertion/deletion)
| |
doc_23536876
|
resources { 'host':
purge => true,
}
host { 'localhost.localdomain':
ip => '127.0.0.1',
target => '/chroot/etc/hosts',
}
When I am using target /etc/hosts and I remove the host resource or rename it the output is:
Info: Applying configuration version '1560267493'
Notice: /Stage[main]/Profile:abc:Hosts/Host[localhost.localdomain]/ensure: removed
Info: Computing checksum on file /etc/hosts
Notice: /Stage[main]/Profile::abc:Hosts/Host[localhost.localdomain]/ensure: created
When I am using non standard target e.g. /chroot/etc/hosts nothing happens. (If I rename the entry then just another host entry is created)
Another strange behaviour is that when there is no /etc/hosts file on the agent node an error is thrown: (even if I am using a different target.)
Error: Could not find a suitable provider for host
Versions: Puppetserver: 5.3.8, puppet agent: 4.10.8
A:
I am using resource host. During my experiments the resource type "resources" has no impacts if a host resource is using a non-standard target.
That is not surprising. The resources resource type can purge only resource instances that the specified resource type "prefetches". For the Host resource type, this is hosts recorded in the default hosts file. This is the reason for the documented limitation that a Resources cannot purge type ssh_authorized_key. For that, as for hosts in other target files, Puppet has no way to identify the resources you want to purge.
Another strange behaviour is that when there is no /etc/hosts file on
the agent node an error is thrown: (even if I am using a different
target.) Error: Could not find a suitable provider for host
I would account that a bug. You could consider filing a ticket.
| |
doc_23536877
|
Firstly I want to find out what values are stored in each column and then replace each instance of this value with a number. I can use either table() or summary() to get a frequency table for each data value but then I am unable to access these values - I can only get the frequencies which I don't care about. I have also looked at unique() and duplicated() to no avail.
For example for the first column I have 10,000 rows containing either "dummy1", "dummy2", "dummy3", "dummy4" or "dummy5". I want to replace these values with 1, 2, 3, 4 or 5 respectively.
table(data) gives me a summary of the frequency for each qualitative value but I'm unable to isolate the values "dummy1" etc in a variable (which I will later match to replace). Because I have 30 columns of data I don't want to hard code these dummy values. Unique() only gives the unique value but I want a list of each possible value.
Any help would be much appreicated.
A: Try using which() to find the indices of each expression you want to convert. The following example should be enough to get you started. You can expand this idea to the whole data set with a loop or functional statement:
a <- c("dummy1", "dummy1", "dummy2", "dummy1", "dummy3")
df <- data.frame(a=a, b=a, stringsAsFactors = FALSE)
print(df)
index <- which(df[1]=="dummy1")
df[index, 1] = 3
print(df)
> print(df)
a b
1 dummy1 dummy1
2 dummy1 dummy1
3 dummy2 dummy2
4 dummy1 dummy1
5 dummy3 dummy3
> index <- which(df[1]=="dummy1")
> df[index, 1] = 3
> print(df)
a b
1 3 dummy1
2 3 dummy1
3 dummy2 dummy2
4 3 dummy1
5 dummy3 dummy3
A: My problem was that I didn't want to hard code "dummy1". I don't know what the categories are in each column and I have 30 columns. I have stumbled across what I was looking for in another question... levels(as.factor(dataCol)). This gives me a list of the categories in the column "dataCol".
However, your code is what I'll need for the next step so thanks very much!
| |
doc_23536878
|
A: You can do this:
{@html `<style>${post.css}</style>`}
Bear in mind that the styles in post.css will apply to the entire page, not just to the post's HTML.
Demo
| |
doc_23536879
|
So after running
DBCC CHECKIDENT ('{tableName}', RESEED, 0)
on tables, it set identity_columns.last_value to null in all new tables, due which when I'm inserting new record, identity column start from 0 instead of 1.
I can insert one record and delete it to fix the issue, how can I fix for all tables at once.
This is the query that returns all the tables where identity_columns.last_value is null
SELECT
tables.name As TableName,
identity_columns.last_value
FROM
sys.tables tables
JOIN
sys.identity_columns identity_columns ON tables.object_id = identity_columns.object_id
WHERE
identity_columns.last_value IS NULL
A: I cannot test it, but something like this must work...
SQL
declare tableName varchar(100)
declare cur cursor for
SELECT
tables.name As TableName
FROM sys.tables tables
JOIN sys.identity_columns identity_columns
ON tables.object_id=identity_columns.object_id
WHERE identity_columns.last_value IS NULL
open cur
fetch next from cur into @tableName
while @@fetch_status = 0
begin
DBCC CHECKIDENT (@tableName, RESEED, 1)
fetch next from cur into @tableName
end
close cur
deallocate cur
| |
doc_23536880
|
[[CCDirector sharedDirector] pushScene:[CCTransitionSlideInR transitionWithDuration:.3 scene:prefScene]];
The preferences scene has a back button to take the user back to the menu.
[[CCDirector sharedDirector] popScene];
This works fine unless the user exits the preferences scene and then tries to go back into it. The second time the preferences scene is opened all of the buttons animate when they are touched but are otherwise unresponsive.
Thanks for the help!
A: I have had something similar, there were two solutions I found:
*
*Quick and Dirty is to create the preferences scene instance as you need it (lazy loading), this will reduce memory of keeping it around unless you need it, but you will have to initialize it each time, however it should be new clean copy each time, and if the user doesn't click preferences every time probably faster to load the whole game.
*Make sure the preferences scene cleans itself up before it disappears, this especially means stop all Scheduled selectors or interval timers and remove delegates and touch events.
| |
doc_23536881
|
Query Error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) from (select * from t1 union select * from t2 union select * from t3 ) a' at line 1
create table t1(s int);
create table t2(s int);
create table t3(s int);
insert into t1 values(1);
insert into t2 values(2);
insert into t3 values(3);
select count(*) from
(select * from t1 union
select * from t2 union
select * from t3
) as ta;
DB fiddle
A: COUNT has a special treatment for * that counts the rows regardless of any null values. SUM must take a (numeric) expression as its argument.
In this example, you could use sum(s):
select sum(s) from
(select * from t1 union
select * from t2 union
select * from t3
) as ta;
FBFiddle
| |
doc_23536882
|
public class Employee {
private int empId;
private String name;
private double basicPay;
private double perksPay;
public Employee()
{
}
public Employee(int empId, String name, double basicPay, double perksPay) {
super();
this.empId = empId;
this.name = name;
this.basicPay = basicPay;
this.perksPay = perksPay;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBasicPay() {
return basicPay;
}
public void setBasicPay(double basicPay) {
this.basicPay = basicPay;
}
public double getPerksPay() {
return perksPay;
}
public void setPerksPay(double perksPay) {
this.perksPay = perksPay;
}
public class Organization extends Employee
{
ArrayList<Employee> emp=new ArrayList<Employee>();
public int addEmployee(Employee e)
{
.......
}
}
A: The old java way:
public int addEmployee(Employee e) {
for (Employee employee : emp) {
if (e.getId() == employee.getId()) {
return -1;
}
}
emp.add(e);
return emp.size();
}
EDIT:
The Java8 way:
public int addEmployee(Employee e) {
List<Employee> alreadyInList = emp.stream().filter(em -> em.getId() == e.getId()).collect(Collectors.toList());
return alreadyInList.isEmpty() ? -1 : alreadyInList.size();
}
| |
doc_23536883
|
The problem comes when I want to replace the original <img> by a <div> and add some content. The text can overflow, so I added the jQuery.dotdotdot plugin to crop this text in a nice way. Thus I added my custom JavaScript code:
$(document).ready(function() {
$('#MixItUp').find('> li.mix > div.grid-square').each(function() {
$(this).dotdotdot({
watch: $(this)
});
});
});
Which is quite straight forward, I guess. When I trigger the menu, all boxes are properly aligned and neat, but when it's folded, those texts which have been trimmed by jQuery.dotdotdot are messing up all the grid. How to get rid of those?
I have created a snippet below with some sample data :-)
window.onload = function() {
$(document).ready(function() {
$('#MixItUp').find('> li.mix > div.grid-square').each(function() {
$(this).dotdotdot({
watch: $(this)
});
});
});
}
/* solution to the blank gaps problem */
.grid-square {
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Responsive farm</title>
<link rel="stylesheet" type="text/css" href="http://codyhouse.co/demo/content-filter/css/reset.css">
<link rel="stylesheet" type="text/css" href="http://codyhouse.co/demo/content-filter/css/style.css">
<script type='text/javascript' src="http://codyhouse.co/demo/content-filter/js/modernizr.js"></script>
</head>
<body>
<header class="cd-header">
<h1>Farm data</h1>
</header>
<main class="cd-main-content">
<div class="cd-tab-filter-wrapper">
<div class="cd-tab-filter">
<ul class="cd-filters">
<li class="filter"><a href="/session/logout/">LOGOUT</a>
</li>
</ul>
<!-- cd-filters -->
</div>
<!-- cd-tab-filter -->
</div>
<!-- cd-tab-filter-wrapper -->
<section class="cd-gallery">
<ul id="MixItUp">
<li style="display: inline-block" class="mix topic-C work_phase-B type-D NORA10_fino3.csv">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: NORA10_fino3.csv</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/NORA10_fino3.csv">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Time series over 2000-10 of wind and surface-wave parameters at the location of the FINO3 met mast. Values comprise three-hourly sampled wind speed and direction at 10, 100 and 150 m; significant wave height; and dominant wave period and
direction. Supplied by Metno from their NORA10 reanalysis - horizontal resolution 10 km.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-L work_phase-B type-D NRWF_bline_clin_layout.png">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: NRWF_bline_clin_layout.png</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Layouts, wakes & loads</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/NRWF_bline_clin_layout.png">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Plot of the location of installations in the curvilinear layout.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-L work_phase-B type-D NRWF_bline_clin_layout.txt">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: NRWF_bline_clin_layout.txt</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Layouts, wakes & loads</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/NRWF_bline_clin_layout.txt">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Location of installations in the curvilinear layout.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-L work_phase-B type-D NRWF_bline_rlin_layout.png">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: NRWF_bline_rlin_layout.png</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Layouts, wakes & loads</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/NRWF_bline_rlin_layout.png">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Plot of the location of installations in the rectilinear layout.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-L work_phase-B type-D NRWF_bline_rlin_layout.txt">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: NRWF_bline_rlin_layout.txt</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Layouts, wakes & loads</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/NRWF_bline_rlin_layout.txt">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Location of installations in the rectilinear layout.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-L work_phase-B type-P Pres_May15_RWF.pdf">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: Pres_May15_RWF.pdf</p>
<p>
<label class="att-name">Information type</label>: Reports, presentations & working papers</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Layouts, wakes & loads</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/Pres_May15_RWF.pdf">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Presentation on Uni Research's work on baseline specification of the RWF.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-C work_phase-B type-D vol_flux_10_deg_bin_wind_rose_fino3.jpg">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: vol_flux_10_deg_bin_wind_rose_fino3.jpg</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/vol_flux_10_deg_bin_wind_rose_fino3.jpg">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Wind-rose plot of data in vol_flux_10_deg_bin_wind_rose_fino3.txt.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-C work_phase-B type-D vol_flux_10_deg_bin_wind_rose_fino3.txt">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: vol_flux_10_deg_bin_wind_rose_fino3.txt</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/vol_flux_10_deg_bin_wind_rose_fino3.txt">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Joint histogram of magnitude and direction of volume flux of air through an isolated ideal WT, dimensions those of the DTU 10 MW reference WT, at the location of the FINO3 met mast. Sample counts at 10 s resolution over 2000-10 broken down
by flux magnitude, bin size 1 m s-1, and flux direction, bin size 10 degs. Derived using results from a downscaling of the ERA-Interim reanalysis of ECMWF with WRF, at 3 km horizontal resolution.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-C work_phase-B type-D vol_flux_15_deg_bin_wind_rose_fino3.png">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: vol_flux_15_deg_bin_wind_rose_fino3.png</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/vol_flux_15_deg_bin_wind_rose_fino3.png">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Wind-rose plot of data in vol_flux_15_deg_bin_wind_rose_fino3.txt.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-C work_phase-B type-D vol_flux_15_deg_bin_wind_rose_fino3.txt">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: vol_flux_15_deg_bin_wind_rose_fino3.txt</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/vol_flux_15_deg_bin_wind_rose_fino3.txt">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Joint histogram of magnitude and direction of volume flux of air through an isolated ideal WT, dimensions those of the DTU 10 MW reference WT, at the location of the FINO3 met mast. Sample counts at 10 s resolution over 2000-10 broken down
by flux magnitude, bin size 1 m s-1, and flux direction, bin size 15 degs. Derived using results from a downscaling of the ERA-Interim reanalysis of ECMWF with WRF, at 3 km horizontal resolution.</p>
</div>
</li>
<li style="display: inline-block" class="mix topic-C work_phase-B type-D vol_flux_tseries_fino3.csv">
<div class="grid-square" style="background-color: beige">
<p>
<label class="att-name">File name</label>: vol_flux_tseries_fino3.csv</p>
<p>
<label class="att-name">Information type</label>: Data files</p>
<p>
<label class="att-name">Work phase</label>: Baseline</p>
<p>
<label class="att-name">Wind farm topic</label>: Site characterisation</p>
<p>
<label class="att-name">Uploaded by</label>: angus
</p>
<p><a href="/media/tree/2015/06/30/vol_flux_tseries_fino3.csv">Download</a>
</p>
<p>
<label class="att-name">Description</label>:
<br>
<br/>Time series over 2000-10 of the estimated wind forcing of an isolated ideal WT, dimensions those of the DTU 10 MW reference WT, at the location of the FINO3 met mast. Values comprise hourly-sampled magnitude and direction of the volume flux
through the rotor. Derived using results from a downscaling of the ERA-Interim reanalysis of ECMWF with WRF, at 3 km horizontal resolution.</p>
</div>
</li>
<li class="gap"></li>
<li class="gap"></li>
<li class="gap"></li>
</ul>
<div class="cd-fail-message">No results found</div>
</section>
<!-- cd-gallery -->
<div class="cd-filter">
<form>
<div class="cd-filter-block">
<h4 class="is-open">Search</h4>
<div class="cd-filter-content">
<input placeholder="Try file name..." type="search">
</div>
<!-- cd-filter-content -->
</div>
<!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Information type</h4>
<ul class="cd-filter-content cd-filters list">
<li>
<input class="filter" data-filter="" name="typeRadioButton" id="type-ALL" checked="" type="radio">
<label class="radio-label" for="type-ALL">All</label>
</li>
<li>
<input class="filter" data-filter=".type-D" name="typeRadioButton" id="type-D" type="radio">
<label class="radio-label" for="type-D">Data files</label>
</li>
<li>
<input class="filter" data-filter=".type-P" name="typeRadioButton" id="type-P" type="radio">
<label class="radio-label" for="type-P">Reports, presentations & working papers</label>
</li>
<li>
<input class="filter" data-filter=".type-S" name="typeRadioButton" id="type-S" type="radio">
<label class="radio-label" for="type-S">Software</label>
</li>
</ul>
<!-- cd-filter-content -->
</div>
<!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Work phase</h4>
<ul class="cd-filter-content cd-filters list">
<li>
<input class="filter" data-filter="" name="phaseRadioButton" id="work_phase-ALL" checked="" type="radio">
<label class="radio-label" for="work_phase-ALL">All</label>
</li>
<li>
<input class="filter" data-filter=".work_phase-B" name="phaseRadioButton" id="work_phase-B" type="radio">
<label class="radio-label" for="work_phase-B">Baseline</label>
</li>
<li>
<input class="filter" data-filter=".work_phase-P" name="phaseRadioButton" id="work_phase-P" type="radio">
<label class="radio-label" for="work_phase-P">Post baseline</label>
</li>
</ul>
<!-- cd-filter-content -->
</div>
<!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Wind-farm topic</h4>
<ul class="cd-filter-content cd-filters list">
<li>
<input class="filter" data-filter="" name="topicRadioButton" id="topic-ALL" checked="" type="radio">
<label class="radio-label" for="topic-ALL">All</label>
</li>
<li>
<input class="filter" data-filter=".topic-C" name="topicRadioButton" id="topic-C" type="radio">
<label class="radio-label" for="topic-C">Site characterisation</label>
</li>
<li>
<input class="filter" data-filter=".topic-L" name="topicRadioButton" id="topic-L" type="radio">
<label class="radio-label" for="topic-L">Layouts, wakes & loads</label>
</li>
<li>
<input class="filter" data-filter=".topic-M" name="topicRadioButton" id="topic-M" type="radio">
<label class="radio-label" for="topic-M">Management, operations & costs</label>
</li>
</ul>
<!-- cd-filter-content -->
</div>
<!-- cd-filter-block -->
</form>
<a href="#0" class="cd-close">Close</a>
</div>
<!-- cd-filter -->
<a href="#0" class="cd-filter-trigger">Menu</a>
</main>
<script type='text/javascript' src="http://codyhouse.co/demo/content-filter/js/jquery-2.1.1.js"></script>
<script type='text/javascript' src="http://codyhouse.co/demo/content-filter/js/jquery.mixitup.min.js"></script>
<script type='text/javascript' src="http://codyhouse.co/demo/content-filter/js/main.js"></script>
</body>
</html>
A: There was an easy answer to my problem, just adding
overflow: hidden;
to the .grid-square CSS class. I have edited the question above to reflect this solution.
| |
doc_23536884
|
In my component.ts I have lot of static functions and need to put them in another ts file for better readability purposes. How can I do that ?
Like we can put interfaces in another file and export them is there something similar for static functions too ?
Desired Result is I am able to call Component.foo() in component.ts file, but private static foo() exists in logic.ts file . Is it possible to do so ?
A: You can't do what you're asking.
You can easily create an external class for static files like:
export class Logic {
public static foo() {
console.log('foo');
}
}
And then in component.ts you can call Logic.foo() just fine. However, you can't make foo private because then it's not available in Component. Also, while you rename Logic inside component or wherever else, i.e.
const LogicalFunctions = Logic;
LogicalFunctions.foo();
you can't reference them as a part of Component, a la Component.foo().
A: It depends on what exactly you want to achieve.
You can have a file logic.ts:
export function foo(){ }
And then in your Component-class import this into a private static property if you don't mind an extra step in calling your functions.
import * as Logic from './Logic'
class Component
{
private static Logic = Logic;
public DoStuff() {
Component.Logic.foo();
}
}
Component.Logic.foo(); // Not allowed
Of course anyone could reuse Logic.ts, but if your aim with "private" just is to limit the API of Component, it might be an idea.
And of course your foo won't have access to other private statics of Component, but if you need that I don't see the point in trying to separate your class into multiple files.
| |
doc_23536885
|
https://developer.edamam.com/edamam-docs-nutrition-api
Reading the API understand that we need to use a POST request to get a response specifically for mealType data. However I am very confused on how the syntax would be written for this.
for example the user puts in lasagna and the api gives me the meal type which should be Italian.
A: Step 1, write a service that sends a post request when you run your script. I'm assuming here you're using node, so we'd have something like, let say APIGetter. In the api getter, you want to send out an http request.
I suggest using the request module. Now when you call this function, it'll return a json string inside a promise, containing a bunch of information. You can then deserialize it (turn it into a javascript object) using JSON.parse.
However, I don't think the API does what you think it does, it gives nutrition information given a list of ingredients. It will not categorize the food for you.
| |
doc_23536886
|
AggregateIterable<Document> propertiesDoc = collection.aggregate(Arrays.asList(
Aggregates.match(queryNew),
Aggregates.group("$similarGroup", Accumulators.sum("count", 1),Accumulators.first("data", "$$ROOT")),
Aggregates.skip(skipCount),
Aggregates.limit(searchRequest.getItemsPerPage()),
Aggregates.sort(descending("salePrice")))
);
A: I found solution. there was multiple issues.
*
*there was some records missing the field "similarGroup".
*Sort was not working properly, and below code worked.
AggregateIterable propertiesDoc =
collection.aggregate(Arrays.asList(Aggregates.match(queryNew),
Aggregates.group("$similarGroup", Accumulators.sum("count", 1),
Accumulators.first("data", "$$ROOT")),
Aggregates.sort(Sorts.descending("data.salePrice")),
Aggregates.skip(skipCount),
Aggregates.limit(searchRequest.getItemsPerPage())));
| |
doc_23536887
|
pid with number 2.
I want to grep the whole line. Also, it is very important to filter only and exactly "2". Because at the moment It filters all the number which have 2 in it.
A: If you want to get the listing for just one particular PID, the -p option is the best way.
ps -f -p 2
for example
If you want grep to match a string only if it is the whole word, not part of another word, look at the -w flag, which matches words like
$ echo '52' | grep 2
52
$ echo '52' | grep -w 2
$
if you want to match against only a particular field, awk might be a better answer than grep. For example, if we want to check if the second column is exactly 2 we could do
ps -af | awk '$2 == 2 {print}'
A: You could go for something like this. If you need the details of a process and you know the pid go for this.
ps afux | awk '{if($2==<pid>) print}'
| |
doc_23536888
|
I have no idea how to convert the string into a txt file, I have also tried to look for an answer on the internet but I have found nothing. And also just is there any particular data sanitizing functions I should add if I save user input text in my directory?
Thanks
A: $filename='fish'.uniqid(); //unique filename per Fred's comments
file_put_contents ($filename , $_POST['YOUR_FORM_FIELD_NAME'] );
| |
doc_23536889
|
int argc = 9;
char* argv[argc];
argv[0] = "c:/prog.exe";
but I get notice, that it is deprecated. What is better way?
A: You have to either make it const:
const char *argv[] = { "Arg1", "Arg2", "..." };
... or not use the constant string literals:
int argc = 9;
char* argv[argc];
char prog_name[] = "c:/prog.exe";
argv[0] = prog_name;
A: Besides the problem of using something other than a constant expression for your array size...
The thing that has been deprecated is the silent casting of string literals to char*. This used to be OK:
char * hello = "hello";
Now it has to be:
char const* hello = "hello";
This deprecation is actually in an Appendix in C++03.
A: Try using const to indicate that the strings won't be modified.
const char* argv[] = { "c:/prog.exe" };
const int argc = sizeof(argv) / sizeof(argv[0]);
int main()
{
for(int i = 0; i < argc; ++i)
{
::printf("%s\n", argv[i]);
}
}
Here, argc will also be calculated at compile time automatically so there's a lesser chance of error (thanks to Goz for the suggestion).
A: Let analyze what you are doing here:
// Create an int with value 9.
int argc = 9;
// Create an array of char* pointers of size 9
char* argv[argc];
// Assign the the first pointer to the global data string "C:\prog.exe"
argv[0] = "c:/prog.exe";
My guess is that you are not trying to do what I've described above. Try something like this:
// create an array of characters
char argv[] = "C:/prog.exe";
// argc in now the length of the string
int argc = sizeof argv;
-or -
// create an array of strings
char* argv[] = {"C:/prog.exe"};
// argc is now the number of strings in the array
int argc = 1;
A: +1 for Vlad.
Some more explanation from me on what happens here:
You get the "deprecated" warning, because such code:
"asdf"
now has type const char*, not char*. And string literals can be converted to char*, to retain some compatibility with the older conventions when const wasn't that strict. But conversion of a string literal to char* from const char* is deprecated and you should not rely on it.
Why? String literal is a pointer to constant memory, that's why it needs to be const char*.
A: Other than what everyone else has pointed out about const string literals being assigned to non-const char pointers and the weirdness of declaring argv and argc outside of main()'s parameter list, there is an additional problem with this line here:
char* argv[argc];
You can only use integer constant expressions for array sizes in C++; an integer constant expression being a literal integer in the source of your program (like "5" or "10"), an enumerations value (like "red" from "enum colors {red, green, blue};"), a sizeof expression, or an int variable declared with const:
// can hold 30 ints
int myarray1[30];
// can hold as many ints as myarray1 is wide in bytes
int myarray2[sizeof(myarray1)];
// C++ does not support variable-length arrays like C99 does, so if an int
// variable is used to specify array size, it must be marked const:
const int myarray3_size = 42;
int myarray3[myarray3];
Many C++ compilers implement C99-style variable-length arrays, so you may not get any complaint when you use them, but they are still best avoided if you want to write portable code.
| |
doc_23536890
|
ajax javascript
<script>
$(document).ready(function() {
$('#catid').on('click', function() {
var catid = $("#catid").val();
$.ajax({
url: "<?php echo base_url(); ?>get-form-detail",
type: "post",
data: "catid=" + catid,
success: function(response) {
var res = JSON.parse(response);
for(i=0;i<res.length;i++)
{
//alert(res[i]['cat_title']);
options += '<option value="' + res[i]['id'] + '">' + res[i]['cat_title'] + '</option>';
$('#tbl').html(options);
}
}
});
});
});
</script>
view page
<div class="row">
<label class="col-sm-4 col-form-label text-right">Form Category : </label>
<div class="col-sm-8">
<div class="form-group">
<select class="form-control" name="formID" id="formID">
<div id="tbl"></div>
</select>
</div>
</div>
</div>
A: change callback function to
success: function(response) {
let res = JSON.parse(response);
let options = res.reduce((a,v)=>(`${a}<option value = "${v['id']}">${v['cat_title']}</option>`), '');
$('#formID').html(options);
}
And use this html code
<select class="form-control" name="formID" id="formID"></select>
A: idk how u to add more item using variable option but i have another solution
Replace your code :
var x = document.getElementById("yourSelectElementId");
for(i=0;i<res.length;i++){
var option = document.createElement("option");
option.text = res[i]['id'];
option.value= res[i]['id'];
x.add(option);
}
| |
doc_23536891
|
The divider should always be in the center of any two columns and should not be displayed on the outer edges of the grid. Note that the number of columns will change according to screen size. Any ideas how to do this?
Here is my code:
https://play.tailwindcss.com/ATXYuNgHg9
A: You can try using a pseudo-element for the first red blocks, we make height with very long with vh unit and hide it using the overflow property on the parent element.
<script src="https://cdn.tailwindcss.com"></script>
<div class="absolute inset-0 justify-center p-32">
<div class="grid gap-x-8 gap-y-3 overflow-hidden xs:grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<div class="relative w-30 h-10 bg-red-600 sm:after:content-[''] sm:after:absolute sm:after:w-[3px] sm:after:min-h-[500vh] sm:after:bg-black sm:after:right-[-1rem]"></div>
<div class="relative w-30 h-10 bg-red-600 lg:after:content-[''] lg:after:absolute lg:after:w-[3px] lg:after:min-h-[500vh] lg:after:bg-black lg:after:right-[-1rem]"></div>
<div class="relative w-30 h-10 bg-red-600 xl:after:content-[''] xl:after:absolute xl:after:w-[3px] xl:after:min-h-[500vh] xl:after:bg-black xl:after:right-[-1rem]"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
<div class="w-30 h-10 bg-red-600"></div>
</div>
</div>
| |
doc_23536892
|
Any suggestions?
forms.py
class WardForm(forms.Form):
ward_no = forms.ChoiceField(choices=[(x, x) for x in ['All', '1', '2', '3','4','5','6','7','8','9','10','11','12','13','14','15']])
Views.py
def post(request, template_name='report.html'):
if request.method == 'POST':
form=WardForm(request.POST)
return render(request, template_name, {'form': form})
reports.html
{{ form.as_p}}
| |
doc_23536893
|
<div class="row justify-content-center align-self-center">
<div class="col-sm-1 mt-auto" id="sec_1"></div>
<div class="col-sm-1 mt-auto" id="sec_2"></div>
<div class="col-sm-1 mt-auto" id="sec_3"></div>
<div class="col-sm-1 mt-auto" id="sec_4"></div>
<div class="col-sm-1 mt-auto" id="sec_5"></div>
<div class="col-sm-1 mt-auto" id="sec_6"></div>
<div class="col-sm-1 mt-auto" id="sec_7"></div>
<div class="col-sm-1 mt-auto" id="sec_8"></div>
</div>
JS switches exactly one of the elements to be bigger which means I replace it with either a col-sm-3 (now the borders collide right side of the green img):
or a col-sm-4 - which means it is not center-aligned any more:
The green image has the following CSS attributes:
background-size: cover;
width: 200px;
height: 150px;
border: 2px solid yellow;
outline: 2px solid white;
Small image has the same class, but width = 64px; height = 48px.
I know the outline is not "pushing" the other image (which also has a outline right now) to the right - but how would I achieve that? I want let's say 4px between every <div> (or image inside the <div>).
A: try this
<style>
.sel {
background-size: cover;
width: 200px;
height: 150px;
border: 2px solid red;
outline: 2px solid white;
}
</style>
<div class="col-6">
<div class="row justify-content-center align-self-center">
<div class="col-sm-1 mt-auto" id="sec_1"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-4 mt-auto sel" id="sec_2"><img class="mx-auto d-block" src="https://dummyimage.com/200x150/000/cacaca" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_3"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_4"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_5"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_6"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_7"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
<div class="col-sm-1 mt-auto" id="sec_8"><img src="https://dummyimage.com/64x48/000/fff" alt=""></div>
</div>
</div>
Explanation
Important: I have simulated the case of the class added by JS through the SEL class.
I have added the "mx-auto d-block" class to image on this cell, that centers the image inside the div inside of all the space available.
You can see the example in the following link.
good luck!
| |
doc_23536894
|
ggplot(DataSB,aes(x=Year,y=Kilos))+
geom_point(shape=21, size=3, color="black", fill="#E29578") +
geom_smooth(method = "glm", method.args=list(family=Gamma(link = "log")),
se=T, size=2, color="#E29578") +
labs(x= "", y = "Catch per average trip (Kg)", title = "(a) Small benthics")+
stat_poly_eq(formula = y ~ x,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE, color = "black")
As you can see I use a gamma(log) distribution to model my data. I also use the same analysis in the glm function which provides me with two coefficients, output of glm:
glm(formula = Kilos ~ Year, family = Gamma(link = "log"), data = DataSB)
Deviance Residuals:
Min 1Q Median 3Q Max
-4.4636 -0.9370 -0.3679 0.3633 2.1094
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 31.081487 9.571677 3.247 0.00149 **
Year -0.012418 0.004771 -2.603 0.01035 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for Gamma family taken to be 0.903844)
Null deviance: 199.67 on 128 degrees of freedom
Residual deviance: 193.40 on 127 degrees of freedom
AIC: 1853.4
Number of Fisher Scoring iterations: 6
Now in order to use these coefficients I realise I need to put them in the following formula:
exp(b+a*x) #So:
exp(31.081487-0.012418*x)
The problem I'm struggling with is how to make stat_poly_eq print this formula. I've tried pretty much every combination for the formula, but nothing is quite right, is it even possible for stat_poly_eq to print this? If not is there a function that can, including the R-squared?
Data:
Num Reference Order Group Individuals Kilos Size TotalCatch Year
1 A001 01 Small Benthic 500.00 125.00 15 670.0000 2021
11 A002 01 Small Benthic 500.00 300.00 25 1381.0000 2021
21 A003 01 Small Benthic 500.00 60.00 16 5742.0000 2021
31 A004 01 Small Benthic 800.00 230.00 18 1535.0000 2021
41 A005 01 Small Benthic 225.00 111.00 18 3192.0000 2021
61 A008 01 Small Benthic 500.00 1200.00 18 4983.5000 2008
71 A009 01 Small Benthic 20.00 60.00 21 121.0000 2021
81 A010 01 Small Benthic 3600.00 600.00 17 4008.0000 2021
91 A011 01 Small Benthic 450.00 135.00 23 272.0000 2021
101 A012 01 Small Benthic 2100.00 350.00 26 2080.0000 2021
111 A013 01 Small Benthic 5.00 3.00 27 140.0000 2020
121 A014 01 Small Benthic 5000.00 2000.00 18 2135.0500 2017
131 A015 01 Small Benthic 1500.00 700.00 32 1483.0000 2021
141 A016 01 Small Benthic 1600.00 600.00 27 1993.0000 2021
151 A017 01 Small Benthic 120.00 80.00 26 626.0000 2021
161 A018 01 Small Benthic 0.00 0.01 <NA> 31.0000 2021
181 A020 01 Small Benthic 100.00 120.00 20 5210.0000 2021
191 A021 01 Small Benthic 2400.00 1800.00 35 7441.0000 2021
201 A022 01 Small Benthic 4000.00 800.00 35 7085.0000 2021
211 A023 01 Small Benthic 0.00 0.01 <NA> 2268.0000 2021
221 A024 01 Small Benthic 300.00 121.00 25 4152.0000 2021
231 A025 01 Small Benthic 1000.00 600.00 33 3697.0000 2021
241 A026 01 Small Benthic 300.00 131.00 28 2522.0000 2021
251 A027 01 Small Benthic 100.00 60.00 25 315.0000 2021
271 A029 01 Small Benthic 1000.00 520.00 27 2511.0000 2021
281 F001 01 Small Benthic 155.00 35.00 35 2855.5000 2006
291 F002 01 Small Benthic 50.00 10.00 17.5 270.0000 2021
301 F003 01 Small Benthic 0.46 14.00 40 145.5000 2021
311 F004 01 Small Benthic 75.00 15.00 28.5 829.2917 2021
331 L001 01 Small Benthic 1450.00 1000.00 41 4371.0000 2021
341 L002 01 Small Benthic 1500.00 800.00 63 2915.0000 2021
351 L003 01 Small Benthic 200.00 70.00 29 945.0000 2021
361 L004 01 Small Benthic 1040.00 1000.00 37 4329.5000 2021
371 L005 01 Small Benthic 1000.00 500.00 22 2024.0000 2021
381 L006 01 Small Benthic 2700.00 450.00 40 1470.0000 2021
391 L007 01 Small Benthic 1500.00 300.00 27 1048.0000 2012
401 L008 01 Small Benthic 900.00 400.00 30 2664.0000 2021
411 L009 01 Small Benthic 1000.00 200.00 24 5935.0000 2021
421 L010 01 Small Benthic 1500.00 1000.00 28 4375.0000 2021
431 L011 01 Small Benthic 1300.00 260.00 25 3343.0000 2021
441 L012 01 Small Benthic 500.00 100.00 28 2369.0000 2021
451 L013 01 Small Benthic 400.00 67.00 26 716.0000 2021
461 L014 01 Small Benthic 3000.00 500.00 28 1500.0000 2021
471 L015 01 Small Benthic 1000.00 200.00 20 1657.0000 2021
481 L016 01 Small Benthic 3540.00 590.00 20 3930.0000 2021
491 L017 01 Small Benthic 4000.00 800.00 22 2619.0000 2021
501 L018 01 Small Benthic 2530.00 422.00 30 7897.0000 2021
511 L019 01 Small Benthic 455.00 76.00 23 2018.0000 2021
521 L020 01 Small Benthic 3000.00 500.00 23 4037.0000 2010
531 L021 01 Small Benthic 6300.00 1260.00 27 5709.0000 2021
541 L022 01 Small Benthic 450.00 90.00 26 1188.0000 2016
551 L023 01 Small Benthic 478.00 120.00 24 526.0000 2021
561 L024 01 Small Benthic 2100.00 350.00 20 2171.0000 2021
571 L025 01 Small Benthic 812.00 163.00 25 891.0000 2021
581 L026 01 Small Benthic 6000.00 1050.00 20 8748.0000 2021
591 L027 01 Small Benthic 4500.00 900.00 23 8197.0000 2021
601 L028 01 Small Benthic 2380.00 476.00 21 3621.0000 2012
611 L029 01 Small Benthic 1172.00 235.00 23 8493.0000 2021
621 L030 01 Small Benthic 780.00 130.00 15 4268.0000 2021
631 L031 01 Small Benthic 3500.00 700.00 20 1842.0000 2021
641 L032 01 Small Benthic 400.00 134.00 22 2304.0000 2021
651 L033 01 Small Benthic 1275.00 260.00 25 1244.0000 2021
661 L034 01 Small Benthic 1200.00 240.00 20 2211.0000 2002
671 L035 01 Small Benthic 1700.00 283.00 24 3023.0000 2005
681 L036 01 Small Benthic 2750.00 458.00 20 2798.0000 2021
701 L037 01 Small Benthic 1100.00 183.00 20 2645.0000 2021
711 L038 01 Small Benthic 1090.00 182.00 25 540.0000 2021
721 L039 01 Small Benthic 1300.00 217.00 19 1212.0000 2021
731 L040 01 Small Benthic 1250.00 210.00 19 1853.0000 2021
741 A001 01 Small Benthic 3050.00 762.50 22 1312.5000 1993
751 A002 01 Small Benthic 800.00 500.00 31 4528.0000 2011
761 A003 01 Small Benthic 1000.00 400.00 23 6165.0000 2001
771 A004 01 Small Benthic 1500.00 400.00 23 9650.0000 1993
791 A007 01 Small Benthic 500.00 2500.00 25 3886.0000 1972
811 A009 01 Small Benthic 200.00 400.00 21 594.0000 2014
831 A011 01 Small Benthic 750.00 225.00 28 1100.0000 1994
841 A012 01 Small Benthic 2000.00 500.00 26 2595.0000 1984
851 A013 01 Small Benthic 5.00 3.00 27 140.0000 2002
861 A014 01 Small Benthic 5000.00 2000.00 18 2135.0500 1987
871 A015 01 Small Benthic 2500.00 875.00 41 3033.0000 1996
881 A016 01 Small Benthic 1600.00 600.00 27 1993.0000 2014
891 A017 01 Small Benthic 120.00 80.00 26 626.0000 2006
901 A018 01 Small Benthic 0.00 0.01 <NA> 32.0000 1991
981 A026 01 Small Benthic 900.00 320.00 28 8025.0000 1991
991 A027 01 Small Benthic 400.00 200.00 25 957.0000 1993
1011 A029 01 Small Benthic 1800.00 800.00 27 2935.0000 2011
1021 F001 01 Small Benthic 155.00 35.00 35 2949.5000 2000
1031 F002 01 Small Benthic 20.00 2.00 17.5 130.0000 2006
1041 F003 01 Small Benthic 1.50 45.00 60 408.0000 1973
1051 F004 01 Small Benthic 75.00 15.00 28.5 328.4931 1982
1071 L001 01 Small Benthic 1450.00 1000.00 41 4880.0000 1996
1081 L002 01 Small Benthic 1500.00 800.00 63 3035.0000 2010
1091 L003 01 Small Benthic 200.00 70.00 29 982.0000 2015
1101 L004 01 Small Benthic 1040.00 1000.00 37 4802.5000 2011
1111 L005 01 Small Benthic 1000.00 500.00 22 2024.0000 1986
1121 L006 01 Small Benthic 2700.00 450.00 40 1930.0000 2002
1131 L007 01 Small Benthic 2000.00 350.00 27 1188.0000 1985
1141 L008 01 Small Benthic 2000.00 900.00 30 4630.0000 2000
1151 L009 01 Small Benthic 2000.00 400.00 33 5372.0000 1996
1161 L010 01 Small Benthic 4400.00 2000.00 28 6170.0000 1993
1171 L011 01 Small Benthic 1795.00 445.00 27 6136.0000 1999
1181 L012 01 Small Benthic 3600.00 720.00 28 2791.0000 1971
1191 L013 01 Small Benthic 2432.00 405.00 34 2939.0000 2009
1201 L014 01 Small Benthic 2260.00 377.00 28 2263.0000 1991
1211 L015 01 Small Benthic 1650.00 330.00 24 4977.0000 1983
1221 L016 01 Small Benthic 640.00 107.00 20 4758.0000 1988
1231 L017 01 Small Benthic 3750.00 750.00 28 3356.0000 1981
1251 L019 01 Small Benthic 2750.00 458.00 23 2952.0000 1996
1261 L020 01 Small Benthic 3500.00 583.00 40 4756.0000 1993
1271 L021 01 Small Benthic 6600.00 1320.00 27 9607.0000 1997
1281 L022 01 Small Benthic 1350.00 270.00 26 2035.0000 1970
1291 L023 01 Small Benthic 608.00 152.00 24 1362.0000 2003
1301 L024 01 Small Benthic 6443.00 1074.00 22 3063.0000 1999
1311 L025 01 Small Benthic 1209.00 242.00 31 1298.0000 1983
1321 L026 01 Small Benthic 12500.00 2083.00 20 4793.0000 1978
1331 L027 01 Small Benthic 4320.00 864.00 21 5456.0000 1986
1341 L028 01 Small Benthic 3780.00 756.00 32 8515.0000 1960
1351 L029 01 Small Benthic 4810.00 962.00 25 4044.0000 1979
1361 L030 01 Small Benthic 1740.00 290.00 25 2953.0000 2001
1371 L031 01 Small Benthic 6650.00 1330.00 24 4273.0000 1980
1381 L032 01 Small Benthic 700.00 233.00 22 8991.0000 1986
1391 L033 01 Small Benthic 2750.00 550.00 25 2706.0000 1984
1401 L034 01 Small Benthic 1900.00 380.00 28 3438.0000 1962
1411 L035 01 Small Benthic 3090.00 515.00 24 5297.0000 1963
1421 L036 01 Small Benthic 3230.00 538.00 23 4420.0000 1965```
A: As you not share the data with us I will give you only description how to solve it.
*
*(1) ..eq.label.. is a regular character so you could apply strsplit on it and other string operations. You could write your own function which consume ..eq.label.. and return proper equation.
*(2) Another idea which will not be very efficient will be to assess glm model twice and paste proper string equation instead of using ..eq.label...
*Last (3) solution, using ggplot2::ggplot_build:
# generate artificial data
library(ggplot2)
library(ggpmisc)
#> Loading required package: ggpp
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
set.seed(4321)
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x, y = y,
group = c("A", "B"),
y2 = y * c(0.5,2),
w = sqrt(x))
# give a name to a formula
formula <- y ~ poly(x, 3, raw = TRUE)
# no weights
gg <- ggplot(my.data, aes(x, y)) +
geom_point() +
geom_smooth(method = "lm", formula = formula) +
stat_poly_eq(formula = y ~ x,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE, color = "black")
gg_raw <- ggplot_build(gg)
process_label <- function(x) gsub("~~~",")~~~", gsub(")~`=`~",")~`=`~exp(",x))
gg_raw$data[[3]]$label <- process_label(gg_raw$data[[3]]$label)
gtable <- ggplot_gtable(gg_raw)
cowplot::plot_grid(gtable)
Created on 2021-07-16 by the reprex package (v2.0.0)
A: stat_poly_eq() is designed for equations of polynomials. For other types of formulas you can use stat_fit_tidy(), also from package 'ggpmisc'. See for a similar case, but using nls(), my answer to this other question
You can find also other examples in the package documentatiion
| |
doc_23536895
|
<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:animateLayoutChanges="true"
tools:context=".MainActivity$PlaceholderFragment">
<ActionMenuView
android:minHeight="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
android:minWidth="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|start"
android:id="@+id/toolbarMap1" />
<com.esri.android.map.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mapView"
android:src="@drawable/map"
android:layout_below="@id/toolbarMap1"
android:background="@android:color/white" />
<TextView
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="@+id/textViewStatus1" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_alignParentEnd="true"
android:layout_height="wrap_content"
android:clickable="false"
android:layout_below="@id/toolbarMap1"
android:id="@+id/frame_layout_visible"
android:layout_marginVertical="@dimen/_60sdp">
<ImageView
android:id="@+id/imageZwin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/drag_drop"/>
</FrameLayout>
<FrameLayout
android:layout_width="@dimen/_40sdp"
android:layout_height="wrap_content"
android:id="@+id/frameLayout2"
android:layout_marginEnd="@dimen/_10sdp"
android:animateLayoutChanges="true"
android:clickable="false"
android:layout_marginVertical="@dimen/_80sdp"
android:orientation="vertical"
android:foregroundGravity="center"
android:background="@drawable/rounded_background"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@id/frame_layout_visible"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/imageLegenda"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/legenda"/>
<ImageView
android:id="@+id/imageSzukaj"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/szukaj"/>
<ImageView
android:id="@+id/imageInfoObiekt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/infoObiekt"/>
<ImageView
android:id="@+id/imageObszar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/obszar"/>
<ImageView
android:id="@+id/imageOdswiez"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_5sdp"
android:layout_gravity="center"
android:clickable="true"
android:src="@drawable/odswiez"/>
</LinearLayout>
</FrameLayout>
</RelativeLayout>
A: remove android:layout_alignParentEnd="true" from first FrameLayout - it makes this View stick to right edge of the screen, so your second FrameLayout (one with android:layout_toRightOf) is pushed out of the screen. or maybe you can exchange it to android:layout_toLeftOf. also remove android:layout_alignParentEnd="true" from second one FrameLayout
| |
doc_23536896
|
Comparing a float and an int in Python
https://numpy.org/doc/stable/user/basics.types.html
my question is, why and how does arange interpret the int as the stop point is '6' and not '3', if int is used, should it not stop at 2?
Many thanks for enlightenment.
x = np.arange(-1, 3, 0.5, dtype=int)
y = np.arange(-1, 3, 0.5, dtype=float)
print('x = ', x)
print('y = ', y)
x = [-1 0 1 2 3 4 5 6]
y = [-1. -0.5 0. 0.5 1. 1.5 2. 2.5]
A: According to the docs, which you must have read, since your example is close to the one given there
Another stability issue is due to the internal implementation of
`numpy.arange`.
The actual step value used to populate the array is
``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
can occur here, due to casting or due to using floating points when
`start` is much larger than `step`. This can lead to unexpected
behaviour.
That dtype(start + step) - dtype(start):
In [25]: int(-1 + .5) - int(-1)
Out[25]: 1
Looks like it initially calculates the number of values to return, using the same math as with the float case - hence x and y have the same length.
ceil((stop - start)/step)
In [29]: np.ceil((3-(-1))/.5)
Out[29]: 8.0
My guess is that it 'iterates' for [29] values with the [25] step. It's not a 'iterate until it reaches/passes the stop' logic.
A: Answer to my question is as what hpaulj mentioned, in correct use of arange could lead to unexpected behavior. decimal point for int is bad practise and therefore resulted in the behavior.
| |
doc_23536897
|
A: Yes, just remove the WatchKit extension from your target dependencies and from "Embed App Extensions" in your Build Phases.
Edit for further explanation: When you click on your project in the project navigator, several sections appear such as "General", "Capabilities" etc. Click on "Build Phases". There you will find "Target Dependencies" and "Embed App Extensions".
| |
doc_23536898
|
Anyone can explain?
Permutations with Duplicates: Write a method to compute all
permutations of a string whose characters are not necessarily unique.
The list of permutations should not have duplicates.
public static HashMap<Character, Integer> getFreqTable(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : s.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 0);
}
map.put(c, map.get(c) + 1);
}
return map;
}
public static void getPerms(HashMap<Character, Integer> map, String prefix, int remaining, ArrayList<String> result) {
if (remaining == 0) {
result.add(prefix);
return;
}
for (Character c : map.keySet()) {
int count = map.get(c);
if (count > 0) {
map.put(c, count - 1);
printPerms(map, prefix + c, remaining - 1, result);
map.put(c, count);
}
}
}
public static ArrayList<String> getPerms(String s) {
ArrayList<String> result = new ArrayList<String>();
HashMap<Character, Integer> map = getFreqTable(s);
getPerms(map, "", s.length(), result);
return result;
}
public static void main(String[] args) {
String s = "aab";
ArrayList<String> result = getPerms(s);
System.out.println(result.toString());
}
Update
Thansk @trincot for his answer.
Sorry for not making it clear. I understand the use of HashMap, but I was looking for the reasoning for using it for this permutation question, particularly with duplicate numbers in the input.
For example, the reasoning why using HashMap and recursive backtracking can resolve this issue. I debugged and traced the getPerms but I cannot understand the backtracking logic naturally. The backtracking controls whether or not some permutation can be generated. But I cannot come up with it if I do it myself.
Below is the trace of first part of getPerms. X means if is not executed because a or b is zero.
aab -> aab,aba,baa
a2 b1
"" 3
a:2
a:1,
p(a,2)
a:0
p(aa,1)
a: X aaa
b: b=0
p(aab,0)
re: aab
b=1
a=1
b:1
b=0
p(ab,1)
a:0
a=0
p(aba,0)
a:1
b:0
X abb
a=2
b:1
Update 2
below is another example that explains why using HashMap helps
without HashMap
ab
[aa, ab, ba, bb]
ab
a
a b
aa
bb
b
b a
ba
bb
with HashMap
ab
[ab, ba]
This tells using HashMap and backtracking avoid duplicate in the input
A: The getFreqTable will create a HashMap that has as keys the characters of the input, and as values the count of occurrence of the corresponding character. So for input "aacbac", this function returns a HashMap that can be described as follows:
"a": 3
"b": 1
"c": 2
This is a very common use of a HashMap. As it provides quick lookup of a key (of a character in this case) and quick insertion of a new key, it is the ideal solution for counting the occurrence of each character in the input.
Then this map is used to select characters for a permutation. Whenever a character is selected for use in a permutation, its counter is decreased:
map.put(c, count - 1);
And when backtracking from recursion (which will produce all permutations with that character c as prefix), that counter is restored again:
map.put(c, count);
Whenever the counter for a certain character is 0, it cannot be selected anymore for a permutation. This is why there is this condition:
if (count > 0)
I hope this explains it.
Addendum
By maintaining the count of duplicate letters, this algorithm avoids to make an artificial distinction between these duplicate letters, by which the permutation "aa" would be considered the same as "aa", just because those two letters were swapped with eachother. A decrement of a counter does not mind where exactly that duplicate came from (position in the input). It just "takes one of them, no matter which".
| |
doc_23536899
|
QGraphicsPathItem *item = scene->addPath(path, pen);
item->setZValue(z);
and the other I create my own QGraphicsItem subclass, but get the exact same problem.
The cause of the slow down appears to be on the Qt side of things. It takes a very long time for the scene to generate once I set the z-value (it takes a few minutes before anything displays, and I get the spinning beach ball of death), but once it's generated, the speed is back to normal. Additionally, when I try to close the application it hangs for a few minutes before closing. I don't see any of these issues if I leave the z-value alone, and I've added debugging code to verify it's not occurring in my own code.
Unfortunately, I need to set the z-value in order to render streets correctly (e.g. outlines around roads, make highways a higher order than through streets, etc.).
Any help is greatly appreciated!
A: You may try setting bspTreeDepth to a fixed value. It controls how an item in the scene is located. Changing the depth with a large number of existing items can be very costly.
Another candidate for optimization is itemIndexMethod. Setting it to noIndex may actually increase the performance.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.