text:
Q: logrotate для файлов с изменяющимися именами возник вопрос как делать ротацию файла, который генерируется каждый день
Система федора 7
students.auto-20200313
students.auto-20200314
.....
students.auto-20200512
чтобы хранило только файлы за последний день, а остальные удаляло автоматом? Спасибо за помощь, гуглом не разобрался как это сделать правильно.


text:
Q: Return function does not seem to be working I am trying to make a Blackjack game in Python and I made a separate function for each option to hit stay etc... When I call each function, I pass it the players hand total so far:
def hit(PlayerHand):
    PlayerCard3 = random.randint(2,10)
    print("You got %s" %PlayerCard3)
    PlayerHand = PlayerHand+PlayerCard3
    return(PlayerHand)

And then I print the players total hand outside of the function but it returns the previous value of PlayerHand and not the new value. I'm not sure what to do.

A: Make sure you are saving the new value:
print("New value is: {}".format(hit(PlayerHand)))

or
PlayerHand=hit(PlayerHand)
print(PlayerHand)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting error when trying to order by up votes (act_as_votable gem) So I have the voting working perfectly fine. But when I try to order my posts by most up votes I get this error saying statement invalid in Post Index.
Error message
This is my post controller
def index
 @posts = Post.all.order(:cached_votes_up => :desc)
end

I have added the Cached votes to posts table migration as well here is the first half of it
class AddCachedVotesToPosts < ActiveRecord::Migration
 def self.up
  add_column :posts, :cached_votes_total, :integer, :default => 0
  add_column :posts, :cached_votes_score, :integer, :default => 0
  add_column :posts, :cached_votes_up, :integer, :default => 0
  add_column :posts, :cached_votes_down, :integer, :default => 0
  add_column :posts, :cached_weighted_score, :integer, :default => 0
  add_column :posts, :cached_weighted_total, :integer, :default => 0
  add_column :posts, :cached_weighted_average, :float, :default => 0.0
  add_index  :posts, :cached_votes_total
  add_index  :posts, :cached_votes_score
  add_index  :posts, :cached_votes_up
  add_index  :posts, :cached_votes_down
  add_index  :posts, :cached_weighted_score
  add_index  :posts, :cached_weighted_total
  add_index  :posts, :cached_weighted_average

If anymore code will help I will gladly post it
Posts table
create_table "posts", force: :cascade do |t|
t.string   "description"
t.datetime "created_at",         null: false
t.datetime "updated_at",         null: false
t.integer  "user_id"
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"
end

A: cached_votes_up column not added to your database yet. Please run this command,
rake db:migrate:reset

It will reset your database migrations and all new columns will be added. It should solve your problem.
note: all your database records will be removed by using this command.


text:
Q: PixiJS - Set container size in px So I've started using Pixi and trying to place 3 separate PIXI.Cotnainer's in one PIXI.Container which is rendered by the renderer.
I want those three Containers to have fixed size in px, but I do not get it how to achieve this. Setting the width or height does not work.
So my question is very simple: How to set a Containers width and height to eg. "300px"?


text:
Q: Select records where range between two timestamps is less 30 seconds In Microsoft SQL Server 2008 R2, I am trying to query for records from one table, that records start and end times of job steps as timestamp columns, that are within thirty seconds of the timestamp column of an error log table.  The error log table simply records the error event as an identity column and the date/time of the event as a timestamp, it does NOT contain any reference to the event that caused the error.
This is the query I wrote (I only need records within the last week, thus my first select statement, which works just fine):
SELECT
    js.job_name, js.start_time, js.end_time
FROM
    job_step AS js
WHERE
    js.end_time > Dateadd(day, -8, Getdate())
    AND Datediff(ss, (SELECT el.err_timestamp
                      FROM   error_log AS el), js.end_time) < 31

Until I add that second select, everything works fine, but when I add that select, I get this error:

Msg 512, Level 16, State 1, Line 1
  Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , > >, >= or when the subquery is used as an expression.

Note--I am NOT a developer, I am a product analyst, but have a better than average grasp of sql than many non-developers; that said, please remember in your response that I am NOT a developer/coder.

A: Either you need to correlate the sub-query or you should use TOP 1 with Order by
SELECT js.job_name,
       js.start_time,
       js.end_time
FROM   job_step AS js
WHERE  js.end_time > Dateadd(day, -8, Getdate())
       AND Datediff(ss, (SELECT TOP 1 el.err_timestamp
                         FROM   error_log AS el
                         ORDER BY some_col), js.end_time) < 31

A: I would use exists for this purpoase:
WHERE js.end_time > Dateadd(day, -8, Getdate()) AND
      EXISTS (SELECT 1
              FROM error_log el
              WHERE DATEDIFF(second, el.err_timestamp, js.end_time) < 31
             );

I am guessing that you really want some sort of "between" logic.  Perhaps:
WHERE js.end_time > Dateadd(day, -8, Getdate()) AND
      EXISTS (SELECT 1
              FROM error_log el
              WHERE DATEDIFF(second, el.err_timestamp, js.end_time) BETWEEN -30 AND 30
             );

A: This will give you all of the job steps that have an error within 30 seconds of it. It might give you multiple rows per job step if multiple errors fit that criteria, but I would expect that you would want that.
SELECT
    JS.job_name,
    JS.start_time,
    JS.end_time,
    EL.event AS potential_error_in_job
FROM
    dbo.Job_Step JS
INNER JOIN dbo.Error_Log EL ON
    EL.err_timestamp BETWEEN DATEADD(ss, -30, JS.start_time) AND DATEADD(ss, 30, JS.end_time)


text:
Q: Is there a risk of inbred children with fake fatherhood? I got an event where my wife cheated on me and got pregnant, but I was unable to prove it. Now her son is listed as my legitimate son. We appear as father and son in family trees, relationship screens etc., even though his actual biological father is definitely someone else.
When I marry him to a close relative from my side of the family, is there a risk that their children will turn inbred? Common sense would say "no", but it seems like the game treats me as the biological father for all intents and purposes, so I have my doubts.

A: It'd be based on their biological father (probably the other guy).
A character's real father is recorded in their stats. This is not normally displayed, but is visible in non-ironman save files or by entering charinfo into the console.
This means that you can safely marry your son to other dynasty members. On the other hand, you probably shouldn't marry him to anyone who might be his half-sister.
Bear in mind that the "but wasn't I away" event can happen with legitimate children, especially if you are paranoid. The child might actually be yours.

A: No, it shouldn't. In case of bastards, the game records the real fatherhood behind the curtain, and calculates the risk of inbreeding by the genetic family ties.
Example character:
        birth_name="Aghsartan"
        birth_date="1214.2.3"
        father=582283
        real_father=568231
        mother=583069

That also means, that you can inadvertently commit incest, when the real paternity of the characters are unknown to the characters.
If you want to avoid this, you can turn extra character info on, by typing charinfo on in the console. The character tooltips will now show you some hidden info, such as their health pool, ethnicity, fertility, biological father and more.

A: The game mechanics have an internal awareness of who the actual father was, this enables in game events to be triggered such as:

*

*"I am a bastard"

*"The father's wife is angered"

and my personal favourite:

*

*"I'm not your son. I'm your brother"

So IF the father is of a different family and you marry him off to a relative then there will be no risk of inbreeding.
That is IF the father is of a different family and that is a big IF, the real father will likely be someone in your court which could include your sons, brothers etc etc.


text:
Q: What could make this code more efficient (for Hackerrank problem)? See this code I have written to solve this hackerrank challenge.
https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps
Essentially, at this point, I KNOW that my code is algorithmically fast enough to be acceptable for this challenge, because what I have done is EXACTLY what is discussed in the editorial section. However, the code terminates due to timeout. Therefore, I'm wondering whether theres some glaring inefficiencies in the data structures I used or if it could be a memory problem or something. Also, it is worth noting that the editorial is written in c++ and I have written my code in java
I'll describe what's going on. Queries is the list of queries to perform. countMap is a HashMap that will store how many times a given number appears in the array. freqMap is a HashMap that stores how many instances there are of a number appearing x (key) times in the array. So for example, if I add the number 5 to the array, I will add 1 to the value at key 5 in countMap. Then, if the value at key 5 in countMap is now 6, meaning that 5 occurs 6 times in the array, I will add 1 to the value at key 6 in the freqMap, since a number occurs 6 times in the array. Then, if a query happens to check if there are any numbers that appear exactly 6 times in the array, I can check directly in freqMap, and if the value at key 6 is >0, I add the number 1 to the result ArrayList. Else, I add a 0 to the result ArrayList.
static List<Integer> freqQuery(List<List<Integer>> queries) {

    HashMap<Integer,Integer> countMap = new HashMap();
    HashMap<Integer,Integer> freqMap = new HashMap();
    List<Integer> res = new ArrayList();
    for(int i = 0; i < queries.size(); i++){
        List<Integer> query = queries.get(i);
        Integer qType = query.get(0);
        Integer qVal = query.get(1);
        if(qType == 1){
            Integer countVal = countMap.get(qVal);
            if(countVal == null){
                countVal = new Integer(0);
            }
            countVal += 1;
            countMap.put(qVal,countVal);
            Integer freqVal = freqMap.get(countVal);
            if(freqVal == null){
                freqVal = new Integer(0);
            }
            freqVal += 1;
            freqMap.put(countVal,freqVal);
            if ((countVal - 1) > 0) {
                Integer prevFreqVal = freqMap.get(countVal - 1);
                prevFreqVal -= 1;
                freqMap.put((countVal -1),prevFreqVal);
            }
        }else if(qType == 2){
            Integer countVal = countMap.get(qVal);
            if(countVal != null && countVal != 0){
                countVal -= 1;
                countMap.put(qVal,countVal);
                Integer freqVal = freqMap.get(countVal);
                if(freqVal == null){
                    freqVal = new Integer(0);
                }
                freqVal += 1;
                freqMap.put(countVal,freqVal);
                Integer prevFreqVal = freqMap.get(countVal + 1);
                prevFreqVal -= 1;
                freqMap.put((countVal + 1),prevFreqVal);
            }
        }else if(qType == 3){
            Integer freqVal = freqMap.get(qVal);
            if(freqVal == null || freqVal < 1){
                res.add(0);
            }else{
                res.add(1);
            }
        }
    }
    return res;

}

All the results are correct, but I'm getting a timeout error, indicating that my code is not fast enough. I'm lost as to why this is.
HashMap get and put operations are O(1), iterating through the queries once is obviously O(q). Adding to the end of arraylist seems to be O(n), where n is length of arraylist.

A: Well stupid me didn't check the discussion section and apparently the boilerplate code for reading in the queries was too slow, mostly due to what's already been discussed to be using get() from a List is apparently O(n) complexity. On top of this, for add() for the result, one should use a LinkedList as opposed to an ArrayList for O(1) complexity.
The changes I made were to actually change from a List<List<Integer>> to a List<int[]>, thereby accessing the query and value in constant time. I could also get even faster by simply using a 2-d array if the input lengths are already known.
Also, while reading in the input, I kept count of how many queries there were that required me to actually add a value to my result List, say n, and passed that to my method. With that knowledge, I could instantiate an array int[n] and then add to the result array in constant time as well. Much faster

A: A bit cleaner and closer to what you were doing:
static List<Integer> freqQuery(List<List<Integer>> queries) {
    Map<Integer, Integer> countMap = new HashMap<>();
    Map<Integer, Integer> freqMap = new HashMap<>();
    List<Integer> res = new LinkedList<>();
    for (List<Integer> query : queries) {
        Integer qType = query.get(0);
        Integer qVal = query.get(1);
        switch (qType) {
        case 1:
            Integer countVal = countMap.merge(qVal, 1, Integer::sum);
            freqMap.merge(countVal, 1, Integer::sum);
            freqMap.computeIfPresent(countVal - 1, (key, value) -> value - 1);
        case 2:
            countMap.computeIfPresent(qVal, (key, value) -> {
                freqMap.merge(value, -1, Integer::sum);
                freqMap.merge(value - 1, 1, Integer::sum);
                return value - 1;
            });
        case 3:
            Integer freqVal = freqMap.get(qVal);
            res.add(freqVal == null || freqVal < 1 ? 0 : 1);
        }
    }
    return res;
}


text:
Q: KVO for one-to-many but NSNull object passed into observeValueForKeyPath I have one managed object with a one-to-many relationship to member class. When I add the observers for members, it worked. When one new member is added to the relationship, the observeValueForKeyPath will be invoked with the new object and change dictionary contains the new member object. However, observeValueForKeyPath will be triggered second time with all values nil and change dictionary new="NULL". What is the second trigger? I set a breakpoint, but not sure who made the trigger.
@interface FooObject : NSManagedObject {}
@property (nonatomic, strong) NSString *fooId;
@property (nonatomic, strong) NSSet* members;
@end

@implementation FooObject
@dynamic fooId;
@dynamic members;

- (NSMutableSet*)membersSet {
    [self willAccessValueForKey:@"members"];

    NSMutableSet *result = (NSMutableSet*)[self mutableSetValueForKey:@"members"];

    [self didAccessValueForKey:@"members"];
    return result;
}

- (void)registerObservers {
    [self addObserver:self
           forKeyPath:@"members"
              options:NSKeyValueObservingOptionNew
              context:nil];
}

- (void)unregisterObservers {
    @try{
        [self removeObserver:self forKeyPath:@"members"];
    }@catch(id anException){
        //do nothing, obviously it wasn't attached because an exception was thrown
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
    id valueNewSet = [change objectForKey:NSKeyValueChangeNewKey];
    if (![valueNewSet isKindOfClass:[NSSet class]]) {
            // not a NSSet, it contains <null> value
            NSLog(@"%@", change);
            NSLog(@"%@", object);
    }
    if ([[change objectForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeInsertion) {
           // insert change is valid, process the changes
    }

}
@end

Log output:
{
    kind = 1;
    new = "<null>";
}

<FooObject: 0xfa9cc60> (entity: FooObject; id: 0xfa9be00 <x-coredata://39DB31FD-6795-4FDE-B700-819AB22E5170/SHInterest/p6> ; data: {
    fooId = nil;
    members = nil;
})

EDIT 1
I set a breakpoint at NSLog(@"%@", change);
This is the stack trace but not really helpful to figure who makes this call.
main -> UIApplicationMain -> NSKeyValueNotifyObserver -> observeValueForKeyPath:ofObject:change:context
EDIT 2
Maybe this is still a bug?
http://www.cocoabuilder.com/archive/cocoa/182567-kvo-observevalueforkeypath-not-reflecting-changes.html

A: I am running into the same issue where the "implicit" assignment (and hence the notification of the KVO observer) apparently occurs only as part of deallocating MOs: I save a child MOC, then release it, then iOS releases its MOs. I assume that it then sets one-to-many relationships temporarily to NSNull in the process of deallocating related MOs (where delete rule cascade applies).
So next to change kinds for insertion and deletion my KVO observer now also accepts NSKeyValueChangeSetting and asserts change[NSKeyValueChangeNewKey] == NSNull.null. Call it a pragmatic solution.


text:
Q: Why is gdb looking for assembly files? I am attempting to learn about gdb using Ubuntu 13.10.  I am using the gcc compiler and following example:
https://en.wikipedia.org/wiki/Gdb#An_example_session
Instead of the output shown in the example, I get:
Program received signal SIGSEGV, Segmentation fault.
__strlen_sse2_pminub () at ../sysdeps/x86_64/multiarch/strlen-sse2-pminub.S:38
38      ../sysdeps/x86_64/multiarch/strlen-sse2-pminub.S: No such file or directory.

Why is the debugger looking for what I assume is an assembly source file, that I apparently don't have installed?

A: Why is it looking for an assembly source file?
Because the code in question is library code that is written in assembler, and the debug information for it references that file.  (In particular, it's one of [e]glibc's optimized strlen() implementations for x86-64 (aka amd64).)
Presumably, the debuggee has passed an incorrect argument to strlen(), and this has made it crash.  (Theoretically it could be a problem with the implementation of strlen(), but such a fundamental function seems quite unlikely to have bugs, especially given the popularity of amd64 and the fact that [e]glibc only has 3 choices of strlen() on that arch
Why isn't that file installed?
Mostly because it is not easy to arrange for that to happen.
What follows is a fairly technical summary of the issues involved, and may expect a lot of knowledge that you do not, in fact, have; if you have questions, you can ask in #debian-mentors on OFTC.
Key facts:

*

*Ubuntu uses largely the same collection of source packages as Debian, with a relatively small number of packages that are not taken straight from Debian.

*Most of Ubuntu's debug info is in -dbgsym packages generated automatically at dh_strip time by pkg-create-dbgsym (which installs a wrapper around dh_strip).  (This doesn't happen on Debian.)  This works because 99% of packages use dh_strip to strip their binaries.

*A few key source packages explicitly generate their own -dbg packages, primarily so that these will be available on Debian, but potentially also because they need to install more than just separate DWARF info.

*eglibc is one of these key source packages.
Due to the almost limitless freedom that Debian source packages have in how they can build, it is decidedly non-trivial for a general-purpose tool to identify which files, exactly, are the relevant source files that should be bundled into a debugging-source package.
You might think that just unpacking the source package would suffice, but that wouldn't work terribly well with packages like gcc which actually contain a tarball inside their so-called .orig tarball, or even with packages that merely use a patch system more complicated than what you get with the 3.0 (quilt) format. (Another thing that would screw things up is if the upstream package generates any sources during the build that either lack #line directives, or refer to themselves in those #line directives.)
However, it seems that the binaries do contain absolute paths to all source files, so if they are still intact at this time they could be packaged.  Unfortunately, I seem to have hallucinated the objcopy flags that would allow you to rewrite the source paths in the DWARF to match the install paths, so GDB still would not be able to find them.

A: Note that the wiki page says your output may be different. You can follow the discussion about this example that led to that warning being added to the Wiki page at LinuxQuestions.
In general, these differences are based on how things like libc (and maybe gdb) are compiled on different systems. Note that the example is run on Fedora, not Ubuntu; so the base system may have some key differences in how it's setup.
I think this is the main reason for the difference. In fact, I ran the example on Fedora and received output that was more or less identical to the output in the example.
The larger point is that the output you are receiving is the normal output for Ubuntu. I got the same output. You can issue the bt command from that point and the next set of output will be very similar to the output in the example.
So why is gdb looking for assembly files when you are working in C? Well, keep in mind that it's libc that is looking for the assembly file. GDB is just reporting what happened.
And libc is looking for the assembly file essentially because it is supposed to: parts of the library are implemented in assembly.
I'm not a guru in the inner workings of the the C standard library or assembly, so I want to be careful not to say something that is incorrect.
But note 2 things about this example:

*

*It's about length, which by definition will get into system dependent definitions.
If you look at the message, you will see that indeed the lib is looking into it's own internal sysdeps directory, where system dependent directories are stored . This directory is part of the compiled library and is not part of the visible filesystem on the computer.
According to the GNU C Library documentation this structure is created based on the result of the configure utility, which determines how the library is compiled.
If you look at the source code for libc you will see that strlen calls hidden built-in functions based on system architecture, which in turn calls another hidden built-in system dependent assembly strlen.S (I count 18 files with that name, all for different archs), which in turn calls (or may call?) an additional hidden built-in .S function for different processors. The sse and pminub relate to processor details.

*And why isn't it finding the file? I imagine it doesn't find it because it is not there. The compiled binary doesn't include it (I presume) because it is not needed on this system and configure did not say it should be created during the build.
The point here is that the example is passing a NULL to a function that expects a string, which is a big error. Unlike in higher-level languages, the compiler does not catch this. The result is undefined behavior, so anything can happen.
My guess is that the library is trying to find the the version of the function that it thinks makes the most sense; but since the NULL is meaningless here, it guesses wrong and looks for a version that is not there.
Either way it will fail with a core dump. I would also guess that the library compiled for Fedora does not exhibit exactly the same behavior because of various system differences and because any behavior is legal at this point.

A: I found the answer on this website
Here's the short version

*

*From the terminal, run strace -o gdboutput.txt gdb example and go through the wiki example you linked to

*Open gdboutput.txt and look for the text No such file or directory.  There you'll find a path for strlen-sse2-pminub.S

*Download the most recent glibc library using sudo apt-get source glibc

*Look for strlen-sse2-pminub.S in the directory you just downloaded using find -iname strlen-sse2-pminub.S

*Move the glibc to the location found in step 2.  you might need to create the directory.  Or you can change where gdb looks for those files (I don't know enough to do that yet)
Now running the gdb example won't return a file not found error.  But it still didn't give me the wikipedia result.  I'm using Ubuntu. It worked on an cent-os as shown in wikipedia.
I'll copy the full discussion below in case the site goes off.

Debugging in Ubuntu 12.10 – missing file syscall-template.S
NOTE: There is an update at the bottom of this post. Please read it!
After upgrading my development machine to Ubuntu 12.04, I was disappointed to find that debugging suddenly stopped working properly. Every time I tried I got the error:
Cannot find file '../sysdeps/unix/syscall-template.S'

After that none of the debugging made much sense (and the repeated warnings were just getting in the way).
Life kind of got in the way and I didn't do any C development for a good while – so much so that the 12.10 upgrade came around before I'd even thought about it any more. Sadly the problem hadn't gone away, so after another period of inactivity I'm now fixing it.
I discovered that the file in question is in the sources for libc6. These can be obtained using the following command:
sudo apt-get source libc6

This downloads the sources to the current directory. Back to the debugger, and it still couldn't find the files – not really a surprise, but I didn't know where to put them. In desperation I ran strace on the debugger (nemiver, in this case) to see where it was looking for our friend. This is what I got:
stat("/build/buildd/eglibc-2.15/misc/../sysdeps/unix/syscall-template.S", 0x7fff0ba361f0) = -1 ENOENT (No such file or directory)
stat("/home/test/../sysdeps/unix/syscall-template.S", 0x7fff0ba361f0) = -1 ENOENT (No such file or directory)
stat("/build/buildd/eglibc-2.15/misc/syscall-template.S", 0x7fff0ba36200) = -1 ENOENT (No such file or directory)
stat("/home/test/syscall-template.S", 0x7fff0ba36200) = -1 ENOENT (No such file or directory)

Not knowing the inner workings of debuggers, and wanting to keep the files visible to all users, I decided to create the directory /build/buildd and put the libc6 sources in there:
sudo mkdir -p /build/buildd
cd /build/buildd
sudo mv ~/eglic* .

Success! Nemiver found the files and was happy evermore. And since nemiver is a wrapper on gdb, I checked and confirmed that that's happy too, so if you're one of those crazy people who can understand gdb* then this will work for you.
By the way, I have no idea whether or not this is the 'right' way to do this kind of thing, and I strongly suspect it isn't. But it works so I'm happy. If someone knows what I should have done I'll be all ears.
*My only experience of debugging prior to learning C was Java debugging, which is the nicest debugging experience you can have. After that, gdb is a scary nightmare.
UPDATE 6th May 2014: It appears that the libc6 sources are available in newer Ubuntu releases as an installable package. You should be able to just do
sudo apt-get install eglibc-source

and everything will get installed in the right place and be visible to the debugger.
This information came to me from Adventures in Code.


text:
Q: How to write a script that reads a file and counts the number of intgers after an "=" sign I am trying to write a script that reads a file that has multiple values similar to the below i.e log extract
1=232=343=5610=66=???????
1=332=343=2010=46=????????
1=392=343=3610=36=????????
1=132=343=9610=16=???????
Where the value 6=??????? or ???????? (could be any 7/8 byte integer or a 7/8 character).
I want to read/check the log that and prints any field with "6"=
Then check the length of this value, if it is greater than 8 integer/bytes
Then write the lines that have this value to a new file"

A: For lines that start with 6= followed by no more than 7 decimal digits (would match on 6=, 6=123 or 6=123X45678 but not 6=12345678):
grep -E '^6=[0-9]{0,7}([^0-9]|$)' < in > out

For lines that start with 6= followed by no more than  7 characters:
grep -xE '6=.{0,7}' < in > out

For lines that start with 6= followed by no more than  7 bytes:
LC_ALL=C grep -xE '6=.{0,7}' < in > out


text:
Q: KML mapping for ancient India I'm getting started with KML and would like to know how to proceed with some special features of my project.
I am working on a map of India in 500BCE. This raises a number of issues.

*
*Uncertainty. Many of the places I want to map are uncertain, and can only be specified in approximate terms. Places fall into 3 categories:

*
*known places (like Rajagaha=Rajgir)

*uncertain but with uniquely identifiable features (eg. "on the road between Rajagaha and Nalanda")

*uncertain and non-unique (such as towns that are specified only as being in a certain region).

So, how should I approach this? The first category is unproblematic. For the second one I would like to indicate a place, while clearly alerting the user that it is no more than an educated guess. For the third, we can to no better than placing a list of towns (etc.) inside a region. Can this be captured in a useful way in KML?

*Multiple Names. Many of the places have multiple names, whether variant readings in the texts, or translated names in Chinese and so on. Is it possible to record a list of alternative names with the KML data. Of course, only one of these will be displayed, but the others are there for interfacing with other applications. For example, someone's reading a text, they come across a place name in Chinese, and Bingo! they can go to the map, which has the name in Pali.


text:
Q: UIViewAnimationOptionTransitionCurlUp start from left bottom corner I try to use method [UIView transitionFromView:toView:duration:options:completion:]; for change some images and hide some elements with UIViewAnimationOptionTransitionCurlUp (and UIViewAnimationOptionTransitionCurlDown in the reverse situation). It works, but I would like to start flipping from the bottom left corner.
Does anyone know a solution?

A: Try setting the transform of your container view (the one that has the transition applied to it) to CGAffineTransformMakeScale(-1,1) to flip the transition effect, and apply the same transform on its content view to flip the content back.


text:
Q: NVRTC and __device__ functions I am trying to optimize my simulator by leveraging run-time compilation. My code is pretty long and complex, but I identified a specific __device__ function whose performances can be strongly improved by removing all global memory accesses.
Does CUDA allow the dynamic compilation and linking of a single __device__ function (not a __global__), in order to "override" an existing function?

A: I am pretty sure the really short answer is no.
Although CUDA has dynamic/JIT device linker support, it is important to remember that the linkage process itself is still static.
So you can't delay load a particular function in an existing compiled GPU payload at runtime as you can in a conventional dynamic link loading environment. And the linker still requires that a single instance of all code objects and symbols be present at link time, whether that is a priori or at runtime. So you would be free to JIT link together precompiled objects with different versions of the same code, as long as a single instance of everything is present when the session is finalised and the code is loaded into the context. But that is as far as you can go.

A: It looks like you have a "main" kernel with a part that is "switchable" at run time.
You can definitely do this using nvrtc. You'd need to go about doing something like this:

*

*Instead of compiling the main kernel ahead of time, store it as as string to be compiled and linked at runtime.

*Let's say the main kernel calls "myFunc" which is a device kernel that is chosen at runtime.

*You can generate the appropriate "myFunc" kernel based on equations at run time.

*Now you can create an nvrtc program using multiple sources using nvrtcCreateProgram.

That's about it. The key is to delay compiling the main kernel until you need it at run time. You may also want to cache your kernels somehow so you end up compiling only once.
There is one problem I foresee. nvrtc may not find the curand device calls which may cause some issues. One work around would be to look at the header the device function call is in and use nvcc to compile the appropriate device kernel to ptx. You can store the resulting ptx as text and use cuLinkAddData to link with your module. You can find more information in this section.


text:
Q: como soluciono este error en deploy con heroku Este error es el que me sale al intentar hacer el deploy en heroku ,me podrian ayudar, es mi primer intento de hacer un deploy y me he encontrado con errores que no he podido comprender, si alguien tiene alguna ayuda sera bien recibida
Collecting psycopg2==2.8.6
     Downloading psycopg2-2.8.6.tar.gz (383 kB)
   Collecting py2exe==0.10.1.0
     Downloading py2exe-0.10.1.0.tar.gz (104 kB)
       ERROR: Command errored out with exit status 1:
        command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jzhxv2xo/py2exe/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jzhxv2xo/py2exe/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-zqwmc0ba
            cwd: /tmp/pip-install-jzhxv2xo/py2exe/
       Complete output (17 lines):
       Traceback (most recent call last):
         File "<string>", line 1, in <module>
         File "/tmp/pip-install-jzhxv2xo/py2exe/setup.py", line 16, in <module>
           from py2exe.py2exe_distutils import Dist, Interpreter, BuildInterpreters
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/__init__.py", line 9, in <module>
           patch_distutils()
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/patch_distutils.py", line 68, in patch_distutils
           from . import distutils_buildexe
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/distutils_buildexe.py", line 91, in <module>
           from . import runtime
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/runtime.py", line 3, in <module>
           from .dllfinder import Scanner, pydll
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/dllfinder.py", line 5, in <module>
           from . import _wapi
         File "/tmp/pip-install-jzhxv2xo/py2exe/py2exe/_wapi.py", line 4, in <module>
           _kernel32 = WinDLL("kernel32")
       NameError: name 'WinDLL' is not defined
  ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
  Push rejected, failed to compile Python app.
  Push failed


text:
Q: How to compare a date string to current date? I have a date picker through which I am setting up a date in string i.e. mDate.
Now to set up time I want to check if current date and the mDate is same if they are same I want to set minTime to TimePicker dialog and if they are not same min time should not be set to time.
If mDate is empty still time should show all time.
   mEditTxt_Time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Date date = null;
                try {

                    if(!mDate.equals("")) {
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                        date = format.parse(mDate);
                    }

                    Calendar compareDate = Calendar.getInstance();
                    compareDate.getTime();

                Calendar now = Calendar.getInstance();

                TimePickerDialog tpd = TimePickerDialog.newInstance(
                        PostShippingFragment.this,
                        now.get(Calendar.HOUR_OF_DAY),
                        now.get(Calendar.MINUTE),
                        true
                );

                    if(date!=null) {
                        if (date.compareTo(compareDate.getTime())) {
                            tpd.setMinTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
                        }
                    }
                    else {

                        tpd.setVersion(TimePickerDialog.Version.VERSION_2);

                        tpd.setAccentColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));

                        tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialogInterface) {
                                Log.d("TimePicker", "Dialog was cancelled");
                            }
                        });

                        tpd.show(getFragmentManager(), "Timepickerdialog");
                    }
            }
                catch (ParseException e)
                {
                    Log.e("exception",e.toString());

                }
            }
        });

I tried this but I am not able to do the comparison.
Please help. Thank you.

A: You can use compareTo() method of Date.
It will return an integer value,

*

*return a value 0 if the argument Date (compareDate) is equal to this Date;

*return a value less than 0 if this Date is before the Date argument (compareDate);

*return a value greater than 0 if this Date is after the Date
argument (compareDate).

So, you need to modify your if condition as below, if you want to check both date are same or not.
if (date.compareTo(compareDate.getTime()) == 0) {

A: Use any of the following method to compare the dates
Method 1

*

*date1.after(date2)

*date1.before(date2)

*date1.equals(date2)

Method 2
if(date1.compareTo(date2)>0){
  Log.d("Date", "Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
    Log.d("Date", "Date1 is before Date2");
}else{
      Log.d("Date", "Date1 is equal to Date2");
}

Method 3
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);

*

*cal1.after(cal2)

*cal1.before(cal2)

*cal1.equals(cal2)


text:
Q: What does this error when I'm trying to run an example in Apache Mahout? I configured and ran examples with mahout but I get the following error :

hadoop binary is not in PATH,HADOOP_HOME/bin,HADOOP_PREFIX/bin,
  running locally Error occurred during initialization of VM

In my, .bashrc, I defined the following aliases :

JAVA_HOME,HADOOP_CONF_DIR,MAHOUT_CONF_DIR,HADOOP_HOME

I already have configured this in /etc/bash.bashrc :

*

*export JAVA_HOME=/usr/lib/jvm/java-6-openjdk-i386

*export PATH=$PATH:$JAVA_HOME/bin

*export HADOOP_HOME=/home/user/hadoop-0.20.2

*export PATH=$PATH:$HADOOP_HOME/bin

*export MAHOUT_HOME=/home/user/mahout/trunk

*export classpath=$classpath:$MAHOUT_HOME/src/conf

*export HADOOP_CONF_DIR=/home/user/hadoop-0.20.2/conf

*export classpath=$classpath:$HADOOP_CONF_DIR
However,  I have the following error :
MAHOUT_LOCAL is set, so we don't add HADOOP_CONF_DIR to classpath. Error: Could not find or load main class classpath MAHOUT_LOCAL is set, running locally Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine.

A: This is nothing to do with Mahout or Hadoop, but your shell. You appear to be using HADOOP_HOME instead of $HADOOP_HOME in your path expression somewhere, for example.

A: maybe you can try: unset MAHOUT_LOCAL


text:
Q: Будет ли состояние гонок, если один поток меняет переменную типа bool, а другой читает из неё? Существует 2 потока, один из которых читает данные из переменной типа bool, а другой может менять её значение.
Являются ли эти две операции атомарными по отношению друг к другу?
А если нет, то подскажите, пожалуйста, какую-нибудь стандартную обертку, чтобы сделать монопольный доступ к этой переменной.
Разумеется, можно сделать метод доступа, который бы синхронизировал доступ, но мне не хочется изобретать велосипед.
Используются ОС Unix
A: *

*Операции не могут быть атомарными по отношению друг к другу, они либо атомарные, либо неатомарные.

*Собственно, если переформулировать ваш вопрос как "Являются ли read и write для bool атомарными?", то на него уже можно попытаться ответить.

*А ответ достаточно простой - нет, не являются.

*

*Атомарность этих операций нигде не специфицирована, поскольку она зависит от архитектуры машины, на которой выполняется скомпилированный код. Так, чтение bool в unaligned случае вполне может привести к генерированию 2+ инструкций.

*Вторая проблема - когерентность кэшей. Операция должна быть инвариантной относительно всех кэшей процессора, а значит потенциально она перестает быть атомарной.

*

*Теперь чуть ближе к практике. В новом стандарте C++11 для гарантированной атомарности операций над интегральными типами следует использовать std::atomic_bool.

*Если используется boost, то лично я бы (не знаком с вашей задачей и тыкаю пальцем в небо) организовал сихронизацию при работе с переменной типа bool с помощью boost::condition_variable.

*Возможно, вам подойдет использование (специфично для WinAPI) Interlocked функций для доступа к переменной или же, например, какой-нибудь классический механизм синхронизации типа Critical Section.

*...

*

*Подробнее по поводу атомарности операций read / write, их архитектурозависимости и про Microsoft-specific обещания касательно применения volatile можно почитать здесь и здесь.

A: Самый типичный случай гонки. Просто так атомарными эти операции не будут. Для синхронизации надо использовать мьютексы или семафоры. Конкретная реализация зависит от операционной системы, а также от того, как Вы организуете многопоточность: используя низкоуровневые API или обертки.


text:
Q: Como referenciar elementos HTML sem ID no C# Windows Forms Boa noite!
Tenho o seguinte código:

Dados Cadastrais

    Avalista:
    VINICIUS ALVES GONZALEZ
    Contrato:
    72001018

Como posso referenciar este elemento usando C# para pegar o nome do cliente dentro do  e o numero do contrato tbm ...
Consigo somente com items que possuem ID usando o document.getElementById

A: Você já tentou utilizar o AngleSharp

Install-Package AngleSharp

var xml = @"

Dados Cadastrais

    Avalista:
    VINICIUS ALVES GONZALEZ
    Contrato:
    72001018

";

var parser = new HtmlParser();
var document = parser.Parse(xml);

Console.WriteLine(document.QuerySelector("td:nth-child(2)").InnerHtml);
Console.WriteLine(document.QuerySelector("td:nth-child(4)").InnerHtml);

resultado:

VINICIUS ALVES GONZALEZ
72001018

A: Você quiser dizer pegar os elementos DOM utilizando JavaScript para depois mandar esses dados para C#?
Você pode utilizar além do document.getElementById(), o document.getElementsByTagName("td")[0] note que o índice [0] é por que no seu caso retornaria os dois td's.
Tem também o document.getElementsByClassName("nome") note que para este funcionar, você teria que em seu html alterar o campo td onde está o nome para VINICIUS ALVES GONZALEZ	.
Você ainda pode pegar elementos pelos values e por qualquer outro atributo que quiser, só que você precisará de uma função mais complexa para isso. Esta função primeiro irá pegar todos os elementos e verificar em todos se existe o atributo que você deseja e se o valor desse atributo seja o mesmo que você deseja.


text:
Q: How reliable is the delivery of tumbling window data from AWS Kinesis Analytics? When I analyze the contents of a Kinesis stream using a Kinesis Analytics SQL query grouping by time blocks, how certain can I be that all items in the stream are contained in the aggregates? Suppose I update the query during runtime, will the analytics application output aggregates v1 up to a point and then aggregates v2 for all items that were not yet reported on by v1? I something fails under the hood in the implementation, will a new node start reporting exactly from the point where the previous node ended? Or should you not rely on the completeness of these aggregations?

A: Answer posted on the AWS Forums, where I had cross posted:
Please see delivery semantics the service guarantees at https://docs.aws.amazon.com/kinesisanalytics/latest/dev/failover-checkpoint.html
Analytics service maintains checkpoints and if an update happens or any kind of failure happens, the application resumes from these checkpoints. Due to the design, it is possible the service reprocesses some of the same data and produces duplicates. Downstream applications should be able to handle that.


text:
Q: Extract array elements from JSON array with Newtonsoft JSON I have a JSON data like bellow
[{"Staffs":[5,10,12,14]},{"Staffs":[11,13,15,17]}]

and I want to extract value from it and expect bellow data
[5,10,12,14,11,13,15,17]

How can I do this with newtonsoft JSON .

A: You can first parse the JSON to a JArray:
using Newtonsoft.Json.Linq;

var array = JArray.Parse(yourJSONString);

Then, use SelectMany to flatten it and convert it to a List<int>:
var result = array.SelectMany(x => x["Staffs"]).Values<int>().ToList();

A: first of all create a model
class StaffsModel
{
    [JsonProperty("Staffs")]
    public int[] Staffs { get; set; }
}

if we consider to created a json value by object like this
var staffsList = new List<StaffsModel>();
staffsList.Add(new StaffsModel { Staffs = new[] { 5, 10, 12, 14 } });
staffsList.Add(new StaffsModel { Staffs = new[] { 11, 13, 15, 17 } });

we can serialize to array with this method
string json = JsonConvert.SerializeObject(staffsList);

with this output [{"Staffs":[5,10,12,14]},{"Staffs":[11,13,15,17]}]
and finally added to list of numbers
var data = JsonConvert.DeserializeObject<StaffsModel[]>(json);
if (data?.Length > 0)
{
    var listOfNumbers = new List<int>();
    foreach (var staff in data)
    {
        foreach (var number in staff.Staffs)
        {
             listOfNumbers.Add(number);
        }
    }
}


text:
Q: Refactoring a React function with repeated if else blocs I have some nasty code smell and want to refactor. My function has about 20 blocks of these if else statements and growing too. I had a go at refactoring but it didn't work because a) I am inexperienced in how to do it and b) the props need to be passed down again to the new function as a result of refactoring, and I don't know how to do this.
How would you refactor this function?
export default function myContent(props) {

  // Check for Kings
  if (props.tagText === `White's King is present`) {
    return <KingPresentWhite tagText={props.tagText} fen={props.fen} />;
  } else if (props.tagText === `Black's King is present`) {
    return <KingPresentBlack tagText={props.tagText} fen={props.fen} />;
  }

  // Check for unopposed Kings
  if (props.tagText.includes(`Unopposed`) & (props.tagColour === 'White')) {
    return <UnopposedKingWhite tagText={props.tagText} fen={props.fen} />;
  } else if (
    props.tagText.includes(`Unopposed`) &
    (props.tagColour === 'Black')
  ) {
    return <UnopposedKingBlack tagText={props.tagText} fen={props.fen} />;
  }

  // Lots more of these if else statement blocks, maybe about 20 of them

}

A: My advice would be to not have so many different components. Why not have a Knight or even just Figure component which takes color, opposed status and type as parameters. That way the component does whatever it needs to do with that information internally (pethaps inside of a hook) and you dont need to do the if checks here. Presumably, a lot if the properties of these figures are shared.

A: The only improvement I can see there is at the return. The props are the same for each component.
You can set a variable type that takes which component is returned. Then, at the end, you can return :
const element = React.createElement(type,
                [tagText={props.tagText}, fen={props.fen}])
return element;

However, from the way the second if statement is written, it may pose problems depending on the way the following checks are done.
What you could do is split that function in two. The first part doing the checks and returning a value. The second part, taking that value through a switch statement and returning the correct element.
The way information is passed, is also arguable. Giving information through sentences is not the best way. But, I don't know the inner working of your code and you may not be able to change that.
It's possible that multiples functions need to be refactored in order to have clean code.

A: The flow of logic above doesn't make sense to me since an unopposed king implies that a king is in fact present, but if a king is present then the function returns before testing if unopposed. When logical conditions are mutually dependent like that, then the logic is usually cleaner if nested.
Another thing you can do is calculate conditions ahead of time using something like a "playerState" object as shown below. That helps by separating the way you define and test for conditions from the logical flow that depends on those conditions.
Lastly, whenever refactoring its a good idea to test early and test often. The code below shows example refactoring with mock data and log statements to confirm that it is working as expected. You can even run this code in a REPL session for real-time feedback. It's also a good idea to write automated tests that cover ever permutation of your logic.
let props = {
  tagText: "UnopposedKing is present",
  tagColor: "Black"
}

let playerState = {
  isBlack: props.tagColor.includes('Black'),
  hasKing: props.tagText.includes('King is present'),
  unopposed: props.tagText.includes('Unopposed')
}

if (playerState.isBlack) {
  if (playerState.hasKing) {
    if (playerState.unopposed) {
      console.log(playerState)
      //<UnopposedKingBlack...
    } else {
      console.log(playerState)
      //There is a king but the king is opposed
      //<OpposedKingBlack...
    }
  } else {
    console.log(playerState)
    //Something went wrong - did a player toss the board?
  }
} else {
  if (playerState.hasKing) {
    if (playerState.unopposed) {
      console.log(playerState)
      //<UnopposedKingWhite...
    } else {
      console.log(playerState)
      //There is a king but the king is opposed
      //<OpposedKingWhite...
    }
  } else {
    console.log(playerState)
    //Something went wrong - did a player toss the board?
  }
}

Finally, it makes sense to me to go a step further and combine the various components into a single component that handles these conditions as its own properties. As can be seen from the logic I posted, a lot of code is copied between black vs white, so making the component itself able to handle player color would be a good start. Also, it'd be good to move away from checking text and towards dedicated properties for the player state in general.


text:
Q: Regex to extract multiple pieces across multiple lines I am working on making basic Zabbix items for Wazuh. Its not to replace Wazuh, but our techs live in Zabbix and this provides an alert in Zabbix so techs can know something and can go check to Wazuh.
The issue is that Wazuh alerts are multi-line alerts and we need 2 pieces of information.
From the example below, we would like to get:

*

*(server)

*(level 10) -> 'High amount of POST requests in a small period of time (likely bot).'

I use the following regex:
([\r\n].*?)(?:=?\r|\n)(.*?(?:(level 10.*)).*)

This will match on level 10 and then I can use group 1 to get the host name (server). But I am unable to get the second part. I can create an item for each level of rule (1-10 for example) and can get host name. But I can not get the alert itself. I read that I need to create individual items for each pience but what I found is that Zabbix does not always grab right piece from alert. Maybe alert 10 is one item captured but host name is from another log entry.
Is there a way to capture all of these in one item using regex in Zabbix?
Thank you. I appreciate all your help.
** Alert 1646336311.8104996: - web,appsec,attack,pci_dss_6.5,pci_dss_11.4,gdpr_IV_35.7.d,nist_800_53_SA.11,nist_800_53_SI.4,tsc_CC6.6,tsc_CC7.1,tsc_CC8.1,tsc_CC6.1,tsc_CC6.8,tsc_CC7.2,tsc_CC7.3,
2022 Mar 03 19:38:31 (server) any->/var/log/nginx/access.log
Rule: 31533 (level 10) -> 'High amount of POST requests in a small period of time (likely bot).'

A: If I understand correctly, you can use Javascript in Preprocessing:
value1 = value.replace(/.*1.*/g,'Mobile"')
value2 = value.replace(/.*2.*/g,'Mobile"')
finishvalue = value1.concat(value2);
return(finishvalue)


text:
Q: Using XLRD module and Python to determine cell font style (italics or not) I'm trying to parse data in an excel spreadsheet using XLRD to determine which cell values are italicized. This information will be used to set a flag as to whether the value is an estimated or reported value. Below is an example of the data:
owner_name          year    Jan     Feb     Mar     Apr     May     Jun     Jul     Aug     Sep     Oct     Nov     Dec
Alachua, city of    1978    17.4    15.7    16.7    18.3    18.9    18.9    19.2    17.4    19.5    19.8    17.1    16.4
Archer, city of     1978    5.6      3.6     4.3     4.5     4.7     4.8     5.3     5.3     5.4     5.6     3.9     2.8

I have not used XLRD to any great extent, aside from playing around with some of the basic functions to get a feel for how to pull data from the spreadsheet. Now I need to add that extra bit of functionality to identify italicized cell values.
Thanks in advance for your help...
EDIT:
XLRD provided me with the functionality I need; thanks to John Machin for the answer. Here is teh codez:
import xlrd

book = xlrd.open_workbook('fl_data.xls',formatting_info=True)
sh = book.sheet_by_index(0)

for row in range(0,sh.nrows):
    font = book.font_list
    cell_val = sh.cell_value(row,1)
    cell_xf = book.xf_list[sh.cell_xf_index(row,1)]

    print cell_val,font[cell_xf.font_index].italic

A: My solution here was based on a class written by 'timmorgan' which can be found here. The class requires that the excel document you wish to act upon be open. You then create the excel document object and then call the 'get_range' method which returns a range object. This range object can then be used to get at font properties of the cell specified.
#--Requires excel document to be open
import pyexcel
book = pyexcel.ExcelDocument(visible=True) #--keeps excel open
cell = 'r171'
r = book.get_range(cell)
val = book.get_value(cell)

print val, r.font.italic, r.font.name

A: Using xlrd (by itself, not with pyexcel):
Here is a link to a topic to the python-excel google-group. It's about getting font colour but that gets you 99% of the way.


text:
Q: WiFi inoperative ONLY when automatically connecting to VPN (18.04) I connect to WiFi. Internet works.
Then I manually connect to a VPN with network-manager-openvpn-gnome package (ie: top right corner VPN menu). Internet works.
I set up "Automatically connect to VPN" with nm-connection-editor and restart. Internet does not work.
I disconnect from the VPN manually. Internet does not work.
I deselect "Automatically connect to VPN" and reboot. Internet works.

I am using the exact same ovpn files on other computers with no issues. Any ideas on why this is happening (specific to this laptop)?

Sample OVPN config
client
dev tun
proto udp
remote us-ga.gw.ivpn.net 2049
auth-user-pass

resolv-retry infinite
nobind
persist-tun
persist-key
persist-remote-ip

cipher AES-256-CBC
tls-cipher TLS-DHE-RSA-WITH-AES-256-CBC-SHA:TLS-DHE-DSS-WITH-AES-256-CBC-SHA:TLS-RSA-WITH-AES-256-CBC-SHA
remote-cert-tls server
verify-x509-name us-ga name-prefix
key-direction 1
comp-lzo
verb 3

script-security 2
setenv PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
up /etc/openvpn/scripts/update-systemd-resolved
down /etc/openvpn/scripts/update-systemd-resolved
down-pre

;ca ca.crt


text:
Q: Can somebody give concrete examples(code) of using Artificial Neural Networks in OCR? I am trying to implement OCR for my Windows Mobile application. I would like to give ANN a shot but after some searching I cannot find any concrete examples (code) to do this. I have literally no idea how this would work - although I have already read a bit about them.
Can anyone post here some code or specific examples how it can be done ?

A: Assuming that you have labeled example images of individual characters, and that isolating characters is a solved problem, then the basic steps would be something like:

*

*Clean up and pre-process the images (center the character, standardize the contrast, eliminate noise, etc.)

*Calculate useful features, such as mean and standard deviation of ink pixels, horizontal and vertical projections (row and column totals, respectively)

*Train a classifier (neural network, linear discriminant, decision tree, etc.) using the features

*Test on new example images

*Deploy


text:
Q: Error inserting data into two joined serializers I am making an application in Django Rest Framework which the user can register multiple tasks in a project, but I am running into a problem and it is that when I want to record the data it generates an error where it says that task_id cannot be null:
This my model:
class Task(models.Model):
    title = models.CharField(max_length=25)
    description = models.TextField()
    slug = models.SlugField(max_length=50, unique=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now())
    updated_at = models.DateTimeField(auto_now=timezone.now())

class Project(models.Model):
    developer = models.ManyToManyField(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=25, unique=True)
    description = models.TextField()
    start_project = models.DateTimeField()
    end_project = models.DateTimeField()
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    project_state = models.ForeignKey(ProjectState, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=50, unique=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now)
    updated_at = models.DateTimeField(auto_now=timezone.now)

This my serializer:
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = (
            'title', 'description'
        )
class ProjectSerializer(serializers.ModelSerializer):
    start_project = serializers.DateField(input_formats=['%Y-%m-%d'])
    end_project = serializers.DateField(input_formats=['%Y-%m-%d'])
    task = TaskSerializer(read_only=True, many=True)

    class Meta:
        model = Project
        fields = (
            'developer', 'title', 'description', 'start_project', 'end_project', 'task', 'project_state'
        )

This is the json that I send:
{
    "developer": [
        1
    ],
    "title": "Inicio",
    "description": "Iniciar",
    "start_project": "1999-02-02",
    "end_project": "1999-02-02",
    "task": [
        {
            "title": "Titulo",
            "description": "empezar"
        }
    ],
    "project_state": 1
}

When I show the response by console it returns the complete data:
data={'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'task': [{'title': 'Titulo', 'description': 'empezar'}], 'project_state': 1}

But when I want to get the data from the serializer it doesn't show me the tasks:
{'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'project_state': 1}

A: You have put read_only=True for your task field.
In the DRF serializer fields docs they say about read_only that:

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

And if you don't put read_only for that field, you will have to write an explicit .create() method for your serializer if you want to be able to use create operations.
If you want to create Task objects for each task in your sent json, and associate them with the Project object that will be created, the method can look like this:
class ProjectSerializer(serializers.ModelSerializer):
    # [...]

    def create(self, validated_data):
        tasks_data = validated_data.pop("task")
        project = Project.objects.create(**validated_data)
        for task_data in tasks_data:
            task = Task.objects.create(**task_data)
            project.task.add(task)
        return project

Specific code with the model information
I have renamed the task ForeignKey to project and moved it in Task model, because from your serialisers' structure I guess that you want one project to have several tasks and not the contrary. The name task still exists as a related name.
I have also added your slug fields in the serializers as they are mandatory and have to be unique in your models.
The models:
from django.contrib.auth import get_user_model

User = get_user_model()

class Task(models.Model):
    title = models.CharField(max_length=25)
    description = models.TextField()
    slug = models.SlugField(max_length=50, unique=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now())
    updated_at = models.DateTimeField(auto_now=timezone.now())
    project = models.ForeignKey(
        "Project", on_delete=models.CASCADE, related_name="task"
    )

class Project(models.Model):
    developer = models.ManyToManyField(User)
    title = models.CharField(max_length=25, unique=True)
    description = models.TextField()
    start_project = models.DateTimeField()
    end_project = models.DateTimeField()
    project_state = models.ForeignKey(ProjectState, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=50, unique=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now)
    updated_at = models.DateTimeField(auto_now=timezone.now)

The serializers:
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ("title", "description", "slug")

class ProjectSerializer(serializers.ModelSerializer):
    start_project = serializers.DateTimeField(input_formats=["%Y-%m-%d"])
    end_project = serializers.DateTimeField(input_formats=["%Y-%m-%d"])
    task = TaskSerializer(many=True)

    class Meta:
        model = Project
        fields = (
            "developer",
            "title",
            "description",
            "slug",
            "start_project",
            "end_project",
            "task",
            "project_state",
        )

    def create(self, validated_data):
        tasks_data = validated_data.pop("task")
        developers_data = validated_data.pop("developer")
        project = Project.objects.create(**validated_data)
        project.developer.set(developers_data)
        for task_data in tasks_data:
            task = Task.objects.create(**task_data, project=project)
            project.task.add(task)
        return project

Example of POST request:
{
    "developer": [
        1
    ],
    "title": "Inicio",
    "description": "Iniciar",
    "slug": "inicio",
    "start_project": "1999-02-02",
    "end_project": "1999-02-02",
    "task": [
        {
            "title": "Titulo",
            "description": "empezar",
            "slug": "titulo"
        }
    ],
    "project_state": 1
}


text:
Q: Stored procedure call from Enitiy Framwork 5 to MySQL I am trying to make a stored procedure call from Entity fromawork 5.0 to MySQL. I am able to connect to MySQL but when I am making call to stored procedure,I am getting empty entites(no data). How could I resolve this issue -
Below code I am using to make call to stored procedure -
public virtual ObjectResult<usp_GetFileType_Result> usp_GetFileType()
        {
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_GetFileType_Result>("usp_GetFileType");
        }

I observe on more thing is that whenever I am updating .edmx file from stored porcedure I am getting empty model like this -
namespace MySQLwithEntity
    {
        using System;

        public partial class usp_GetFileType_Result
        {

        }
    }

So I filled it manually like below -
namespace MySQLwithEntity
    {
        using System;

        public partial class usp_GetFileType_Result
        {
          public int FileTypeId { get; set; }
          public string FileTypeName { get; set; }
        }
    }

But still I am getting empty values -

A: After searching for hours I found solution of this.It might helpful for someone -
Reason of above way of calling SP from MySQL was not working was autogenerated entity model was blank, .edmx file was NOT generating mapping for the columns those were returning from MySQL SP.
namespace MySQLwithEntity
    {
        using System;

        public partial class usp_GetFileType_Result
        {

        }
    }

Put entititis manually -
namespace MySQLwithEntity
    {
        using System;

        public partial class usp_GetFileType_Result
        {
          public int FileTypeId { get; set; }
          public string FileTypeName { get; set; }
        }
    }

Created mappinng manually in .edmx file like below, although it is not recommended, but I had no choice. .edmx file will have to edit for "CSDL content" section and "C-S mapping content" section when you open it as xml file -
 <FunctionImportMapping FunctionImportName="usp_GetFileType" FunctionName="Model1.Store.usp_GetFileType">
              <ResultMapping>
              <ComplexTypeMapping TypeName="Model1.usp_GetFileType_Result">
                <ScalarProperty Name="FileTypeId" ColumnName="FileTypeId" />
                <ScalarProperty Name="FileTypeName" ColumnName="FileTypeName" />
              </ComplexTypeMapping>
            </ResultMapping>
          </FunctionImportMapping>

Second is, the code to call to SP. I changed code to call SP like below -
public virtual IList<usp_GetFileType_Result> GetCustOrderHist()
        {
            IList<usp_GetFileType_Result> data = ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<usp_GetFileType_Result>("CALL usp_GetFileType();").ToList();

            return data;
        }

Call in MySQL is equivelent of EXEC of MS SQL.


text: Q: pandas: difference between df.pop('x') and df.drop('x', axis=1,inplace=True) and del df['x']? Do they have the same exact effect (other than the fact that only one returns the popped column)? If so, is there ever a reason to use df.drop('x', axis=1,inplace=True) or del df['x']over the more concise df.pop('x')?


text:
Q: How to make my android calculator working I am making a basic calculator for Android in Java.  I am stuck in one final step where it must add the input with the previous input. Have a look at the code:
    public void displayValue(){

    String mything = display.getText().toString();
    input = Integer.parseInt(mything);

}
public void number1(View view){
    if (input == 0){display.setText("");}

    display.append(Integer.toString(1));
    displayValue();

}
public void number2(View view){
    if (input == 0){display.setText("");}

    display.append(Integer.toString(2));
    displayValue();

}
public void plus(View view){
    displayValue();            //result= 0
    result = result + input;   //result= input
    input = 0;                 //input=0

    //in this step input becomes 0 to let the user enter new number input but this
    //input never add the old result and the equal shows the old result.
}
public void equal(View view){
    displayValue();
    display.setText(Integer.toString(result));

}

I noticed that if I add a line in equal method and add the result to input I get the correct answer but that's not gonna be helpful as there will be minus button too.
Any ideas?
Thanks.

A: It's definitely hard to tell because you don't include full code, which would be helpful, but could it be because you call displayValue(); in some places before doing the math? Specifically in the plus method.

A: Ok finally I came up with a solution.
As the only option for calculation of result and new input is in equal method (because logically when user press the equal button, so wants to ends the equation), so I added two boolean values for each minus and plus calculation. Then I added both calculation for adding or minus 2 values.
Then when the user inter first part of the calculation and then hit plus sign, the boolean value of plus becomes true and after entering new input and hitting the equal sign, it does the true part of the calculation. Well it is a bit hard to explain but i guess by looking at the code you would get what I mean.
boolean whenMinus = false;
boolean whenPlus = false;

public void plus(View view){
    displayValue();
    result = input;
    input = 0;
    whenPlus = true;
}
public void minus(View view){
    displayValue();
    result = input;
    input = 0;
    whenMinus = true;
}
public void equal(View view){
    if (whenPlus == true){result = result + input; whenPlus = false;}
    if (whenMinus == true){result = result - input; whenMinus = false;}

    display.setText(Integer.toString(result));

}

I am not sure if it is the correct way of making this calculator. But I fixed my problem anyway.  It would be great to comment me and let me know if it is the standard way or its kinda hacking. I am not a pro anyway.


text:
Q: Variable change in controller not being reflected on UI - AngularJS I am changing a variable in my controller by calling a function. The variable
isSameTaxonomyElements is bind with an element in UI. But it is being reflected on UI.
$scope.validateAddElementButton = function (name, label) {
            for (var i = 0; i < $scope.elements.length; i++) {
                if (name === $scope.elements[i].name || label === $scope.elements[i].label) {
                  $scope.isSameTaxonomyElements = true;
                  break;
                } else {
                  $scope.isSameTaxonomyElements = false;
                }
            }
        }

This is my UI.

No two elements should have same label or name.

I have also tried adding $timeout, $apply etc, but still not working.

A: Basically, JavaScript variable will take only last assigned value. So according to your code, in side that for loop, if the condition is satisfied, isSameTaxonomyElements will be true and your loop breaks (i.e. no more loop); or else isSameTaxonomyElements will be false, and eventually isSameTaxonomyElements will be false if the loop doesn't early exit.
And check basic things like controller name, app name, etc.

A: Your variable isn't in controller scope. add new html page and add new controller also then create a new route. test your function in added new controller.
second: check scope id in old controller. i think your html not in controller scope.


text:
Q: PRISM - How to get DLL's name and version information? Is it possible to get DLL's names and version information from a appmanifest.xml which resides in a VS2010 project corresponding to a PRISM Module ?
My Silverlight 4 application loads on demand all modules listed in the modules catalog. I guess this means that it has downloaded all the modules corresponding XAP files, appmanifest.xml files – to load the necessary resources (DLL's, etc)
So, at this point, how can I access DLL's names and if possible DLL's version number of every module from within my "main" Silverlight project ??
Thanks for your feedback!

A: You can do this in the ModuleInit.cs of each PRISM module. Somewhat like:
public class ModuleInit : IModule
{
    private readonly IUnityContainer _container;
    private readonly IRegionManager _regionManager;

    public ModuleInit(IUnityContainer container, IRegionManager regionManager)
    {
        _container = container;
        _regionManager = regionManager;

        // Add this assembly details to a global collection
        Global.ClientAssemblies.Add(GeneralHelper.GetAssemblyInfo(System.Reflection.Assembly.GetExecutingAssembly()));
    }...

Helper function:
public static string GetAssemblyInfo(Assembly assembly)
        {
            return assembly.ToString();
        }


text:
Q: Optimize update user profile fields using query Attempting to update some user profile fields in Joomla from an imported users table that has table look ups for particular fields. Looking for some speed improvements as my user database is large and the following query times out...
    CREATE TABLE joomla.updated_users(UserID varchar(255),Active varchar(255),Absent varchar(255),AllowReconcile varchar(255),Prefix varchar(255),FirstName varchar(255),MiddleName varchar(255),LastName varchar(255),Suffix varchar(255),Email varchar(255),PhoneWork varchar(255),PhoneHome varchar(255),PhoneMobile varchar(255),Fax varchar(255),CountryCode varchar(255),AddressLine1 varchar(255),AddressLine2 varchar(255),MailStop varchar(255),City varchar(255),State varchar(255),PostalCode varchar(255),RequiredApprovals varchar(255),DivisionId varchar(255),OrganizationID varchar(255),LocationID varchar(255),PositionID varchar(255),CostCenterID varchar(255),PartnerType varchar(255),PartnerStatus varchar(255),TrendSegment varchar(255),MonthofService varchar(255),Status varchar(255),Classification varchar(255),LastHireDate varchar(255),OriginalHireDate varchar(255),ApproverID varchar(255),ManagerID varchar(255),Ethnicity varchar(255),Username varchar(255)) CHARACTER SET utf8 COLLATE utf8_general_ci;

    CREATE TABLE joomla.updated_organisation(ID varchar(255),Title varchar(255),ParentID varchar(255),Active varchar(255)) CHARACTER SET utf8 COLLATE utf8_general_ci;

    UPDATE joomla.user_profiles
    INNER JOIN joomla.users ON joomla.users.id = joomla.user_profiles.user_id AND joomla.user_profiles.profile_key = 'organisation'
    INNER JOIN joomla.updated_users ON joomla.updated_users.Email = joomla.users.email
    INNER JOIN joomla.updated_organisation ON joomla.updated_users.OrganizationID = joomla.updated_organisation.ID
    SET joomla.user_profiles.profile_value = joomla.updated_organisation.Title;

Thanks in advance!


text:
Q: Tab of Lightning Design System I have 2 problems:

*

*I'm trying to use the tab tag in salesforce lightning : https://www.lightningdesignsystem.com/components/tabs (i use the first one) but my tab is not responsive to the width of the browser, i need to use it in Salesforce 1 (tablette and Mobile). What should i do ?

*In my page i have a click button to edit a record (onClick="sforce.one.editRecord("SomeID")) but when i click, i need to refresh my parent page to see the changes.

Thank you

A: *

*You might need to handle that manually (For example, in mobile you can either add a scroll or arrange tabs in a different manner if your individual tabs are very wide).

*You can use force:refreshView.

Refer https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_force_refreshView.htm


text:
Q: How to get column header if sub-string is found in sheet? I am attempting to get the column header of a cell in Sheet1 when that cell contains a substring that is defined by cell Sheet2!A2. I have used this formula successfully for cases where the string=substring however when there are other characters it fails:
=INDEX(Sheet1!$A$1:$Z$1,SMALL(IF(Sheet1!$C$2:$J$8=$A2,COLUMN(Sheet1!$C$2:$J$8)-COLUMN($A2)+1),1))

I have attempted to replace the IF test condition with COUNTIF(Sheet1!$C$2:$J$8, $A2)>0, which successfully finds all relevant substrings but always returns the column header of the third column. I am not sure why this change occurs.

A: COUNTIF will not return an array.  Try this array-entered formula (confirm by holding down ctrl+shift while hitting enter:
=INDEX(Sheet1!$A$1:$Z$1,SMALL(IF(ISNUMBER(SEARCH(A2,Sheet1!$C$2:$J$8)),COLUMN(Sheet1!$C$2:$J$8)),1))


text:
Q: Using ICommand and ServiceLocator to pass Parent object to load Child objects in an MVVM way I am creating a WPF application with the MVVMLight toolkit. I have a "parent" form (ParentView) and would like to load a "child" form (ChildView) by passing the "parent" object (Parent) that will load all of the "child" objects.
I have included code snippets of 3 main classes I feel are important in anyone's analysis: ViewModelLocator, ChildViewModel, ParentViewModel. I was initially thinking of implementing an ICommand property within the ParentViewModel by instantiating the ParentView (see below), but this doesn't seem right since I am trying to do this in an MVVM way. Could someone assist with the following current structure and how I can pass the parent to a child?
// ----- ChildViewModel -----
public class ChildViewModel
{

  // this ctor doesn't make sense in the MVVM world, right?...
  public ChildViewModel(Parent selectedParent)
  {
     this.Parent = selectedParent;
     // ...
  }

  // how do I plug into this one?...
  public ChildViewModel(IParentService parentService)
  {
     this.ParentService = parentService
     // ...
  }

  // ... removed other code for brevity
}

// ----- ParentViewModel -----
{
  public ICommand ShowChildCommand
  {
     get { return new RelayCommand(() => new ChildView(SelectedParent).Show()); }
  }

  // ... removed other code for brevity
}

// ----- ViewModelLocator -----
public class ViewModelLocator
{
  public ChildModel ChildViewModel
  {
     get { return ServiceLocator.Current.GetInstance<ChildViewModel>(); }
  }

  public ParentModel ParentViewModel
  {
     get { return ServiceLocator.Current.GetInstance<ParentViewModel>(); }
  }

  public ViewModelLocator()
  {
      SimpleIoc.Default.Register<IChildService, ChildService>();
      SimpleIoc.Default.Register<IParentService, ParentService>();
      // ... removed other code for brevity
      SimpleIoc.Default.Register<ChildViewModel>();
      SimpleIoc.Default.Register<ParentViewModel>();
  }

  // ... removed other code for brevity
}

// ------ REVISION 2 EDITS ------------
I incorporated the latest suggestions from user @kidshaw, but I was stumped by the comment in which I had to create an instance of the ChildView within the ParentView.  I am not sure how to do that. I read again the MSDN article about the Messenger, but do not see how it could help me with that question. I have included the following latest code. Please reference the commented sections.
public class ParentViewModel
{

 public ICommand ShowChildCommand
  {
      get { return new RelayCommand(OnLoadChildCommand); }
  }

 private void OnLoadChildCommand()
  {
     Messenger.Default.Send(new ParentToChildMessage { Parent = this.CurrentParent });
     // ****** this is where I instantiated the child view
     // I am sure this is wrong...
     var view = new ChildView().Show();
  }

 public class ParentToChildMessage : MessageBase
  {
      public Parent Parent { get; set; }
  }
...
}

And the ChildViewModel looks like:
public class ChildViewModel
{
  public ChildViewModel(IChildService service)
        {
            this.ServiceProxy = service;
            this.MessengerInstance.Register<ParentViewModel.ParentToChildMessage>(this, this.OnParentToChildMessage);
            this.ChildCollection = new ObservableCollection<Child>();
            GetChildInfo(this.CurrentParent);
        }
}

A: In your sample, it suggests that a ViewModel is talking to a view. This is to be avoided if you've already made the jump to an MVVM pattern.
I would look to use the message framework in MVVM light to do this. You can keep your parent and child views separate this way and pass data without coupling the two together. You can control visibility of your child view in your child view model and toggle that in your message handler.
This msdn article will introduce the concepts.  http://msdn.microsoft.com/en-us/magazine/dn745866.aspx.
Based upon your edits...
First basic step is to create a message class to carry your data from parent to child.
public class ParentToChildMessage : MessageBase
{
    /// Include any properties you want to send
}

If you have no data to pass, you can use the GenericMessage<> object from MVVM Light to pass a bool to save yourself a bit of code. However, messages are registered by type so using the generic means your register method will have to do more inspection - I'll show his in a moment.
In your parent view model, you have a command ShowChildCommand - we can use that as a point to send the message from.
public class ParentViewModel : ViewModelBase
{
    public ParentViewModel()
    {

    }

    public ICommand ShowChildCommand
    {
        get
        {
            return new RelayCommand(()=>this.MessengerInstance.Send<ParentToChildMessage>(new ParentToChildMessage()));
        }
    }
}

That's it for the parent view model. Next we register a message receiver in the child view model.
public class ChildViewModel : ViewModelBase
{
    public ChildViewModel()
    {
        this.MessengerInstance.Register<ParentToChildMessage>(this, this.OnParentToChildMessage);
    }

    private void OnParentToChildMessage(ParentToChildMessage obj)
    {
        // Inspect obj to decide what to do - let's just set as visible
        this.IsVisible = true;
    }

    public bool IsVisible
    {
        get
        {
            return _IsVisible;
        }
        set
        {
            if (value != _IsVisible)
            {
                _IsVisible = value;
                RaisePropertyChanged();
            }
        }
    }
    private bool _IsVisible;
}

You can see here, in the constructor we register a message to the strong type. If we used a generic the body of the OnParentToChildMessage would have to distinguish between this and other possible messages of the same type - not pretty code, especially as you'll likely end up building several message interactions over time.
The child view model updates a simple bool IsVisible property - for this to work, your Parent view will need to have an instance of Child view within it. That will ensure your child view is created, and an instance of your child view model.
I hope this helps.


text:
Q: Constraint the interface of ios application to look same in all simulator I make my application in xcode 8. I set my interface design in iphone 5 simulator in main.storyboard. My interface has scroll view and the image button all is put inside the scroll view. I constraint the scroll view and image buttons with reset to suggested constraint. When run in simulator, only iphone 5 look nice but other iphone look no good. I post my output in below, i think it is easy to understand what i want? If know how to do, please tell me. I want my application design look same in all simulator. First picture is iphone 5 and second picture is iphone 7 plus.
Output:


text:
Q: Adding an extra item to the legend I have the following data:
trait,beta,se,p,analysis,signif
trait1,0.078,0.01,9.00E-13,group1,1
trait2,0.076,0.01,1.70E-11,group1,1
trait3,-0.032,0.01,0.004,group1,0
trait4,0.026,0.01,0.024,group1,0
trait5,0.023,0.01,0.037,group1,0
trait1,0.042,0.01,4.50E-04,group2,1
trait2,0.04,0.01,0.002,group2,1
trait3,0.03,0.01,0.025,group2,0
trait4,0.025,0.01,0.078,group2,0
trait5,0.015,0.01,0.294,group2,0
trait1,0.02,0.01,0.078,group3,0
trait2,0.03,0.01,0.078,group3,0
trait3,0.043,0.01,1.90E-04,group3,0
trait4,0.043,0.01,2.40E-04,group3,1
trait5,0.029,0.01,0.013,group3,0

And make a plot with the following code:
library(ggplot2)
ggplot(GEE, aes(y=beta, x=reorder(trait, beta), group=analysis)) +
  geom_point(data = GEE[GEE$signif == 1, ],
             color="red",
             shape = "*",
             size=12,
             show.legend = F) +
  geom_point(aes(color=analysis)) +
  geom_errorbar(aes(ymin=beta-2*se, ymax=beta+2*se,color=analysis), width=.2,
                position=position_dodge(.2)) +
  geom_hline(yintercept = 0) +
  theme_light() +
  theme(axis.title.y=element_blank(),
        legend.title=element_blank()) +
  coord_flip()

Which gives me the following plot:

I would like to add an extra element to the legend, namely the red asterisk, and I want it to say "significant". How do I go about doing that?
PS. If you like this piece of code, I have another problem with it, specified here :)

A: Add dummy aes() to geom_point - for example fill that is named significant aes(fill = "Significant").
# Using OPs data
library(ggplot2)
ggplot(GEE, aes(y=beta, x=reorder(trait, beta), group=analysis)) +
  geom_point(data = GEE[GEE$signif == 1, ],
             color="red",
             shape = "*",
             size=12,
             aes(fill = "Significant")) +
  geom_point(aes(color=analysis)) +
  geom_errorbar(aes(ymin=beta-2*se, ymax=beta+2*se,color=analysis), width=.2,
                position=position_dodge(.2)) +
  geom_hline(yintercept = 0) +
  theme_light() +
  theme(axis.title.y=element_blank(),
        legend.title=element_blank()) +
  coord_flip() +
  guides(colour = guide_legend(order = 1),
         fill = guide_legend(override.aes = list(size = 5))) +
  theme(legend.margin = margin(-0.5,0,0,0, unit="cm"))

PS: I also removed show.legend = F from asterik geom_point


text:
Q: Replacing Every date before a Certain Day with that Day SQL SELECT
    "Trade Details 2".Portfolio,
    "Trade Details 2".CONTRACT_ID,
    "Trade Details 2".START_DATE,
    "Trade Details 2".MATURITY_DATE,
    "Trade Details 2".NOTIONAL1,
    "Trade Details 2".CONTRACT_NPV,
    "Trade Details".TERM
FROM
    "Trade Details 2"
JOIN
    "Trade Details"
WHERE
    "Trade Details 2".CONTRACT_ID = "Trade Details".FCC_ID
    AND ("Trade Details 2".NOTIONAL1 > "0.0")
    AND ("Trade Details 2".MATURITY_DATE > "20180621")
ORDER BY
    CONTRACT_ID asc

I've been able to make sure that every Maturity_Date is after June 21st, 2018, but I'm having trouble with the START_DATE. My goal is to have every date before June 22nd, 2018 be replaced by June 22nd, 2018, in the START_DATE column.
I have tried to replace "Trade Details 2".START_DATE<2018-06-22 WITH 2018-06-22), to no avail. Is there any way to do this in SQL?

A: You can write the query like this, assuming SQLite:
SELECT td2.Portfolio, td2.CONTRACT_ID,
       MAX(td2.START_DATE, '2018-06-22') as START_DATE
       td2.MATURITY_DATE, td2.NOTIONAL1, td2.CONTRACT_NPV,
       td.TERM
FROM "Trade Details 2" td2 JOIN
     "Trade Details" td
     ON td2.CONTRACT_ID = td.FCC_ID AND
        td2.NOTIONAL1 > 0.0 AND
        td2.MATURITY_DATE > '20180621'
ORDER BY  CONTRACT_ID asc;

Notes:

*

*Table aliases make the query easier to write and to read.

*Presumably, NOTIONAL1 is a number, so compare to a number, not a string.

*JOIN is good syntax.  There should always be an ON clause.

*In SQLite, MIN() and MAX() take multiple arguments.  With multiple arguments they are not aggregation functions, instead behaving like LEAST() and GREATEST() in other databases.

A: See start_date_bounded. Since you didn't tag your dbms the syntax might need tweaked (ex. DATE '2018-06-22'.
SELECT "Trade Details 2".Portfolio, "Trade Details 2".CONTRACT_ID,
CASE WHEN "Trade Details 2".START_DATE < 2018-06-22 THEN 2018-06-22
     ELSE "Trade Details 2".START_DATE
 END AS start_date_bounded, "Trade Details 2".MATURITY_DATE, "Trade Details
2".NOTIONAL1, "Trade Details 2".CONTRACT_NPV, "Trade Details".TERM
FROM "Trade Details 2"
JOIN "Trade Details"
WHERE "Trade Details 2".CONTRACT_ID="Trade Details".FCC_ID and
("Trade Details 2".NOTIONAL1 > "0.0") and
("Trade Details 2".MATURITY_DATE > "20180621")

ORDER BY CONTRACT_ID asc


text:
Q: Z3: Modeling with Quantifiers I want to prove (∀i(0≤i<k→a[i]>0)∧a[k]>0)→∀i(0≤i≤k→a[i]>0) by z3. The negation of it is: ∀i(0≤i<k→a[i]>0)∧a[k]>0∧∃i(0≤i≤k∧¬(a[i]>0)). First, I set the value of k to 5 and ignore the part a[k]>0, and try:
from z3 import *
i = Int('i')`
a = Array('a',IntSort(),IntSort())
solver = Solver()
solver.add(ForAll(i, Implies(And(i >= 0,i < 5),a[i] > 0)))
solver.add(Exists(i, And(i >= 0,i <= 5, Not(a[i] > 0))))
print solver.check()
print solver.model()

The output is:
sat
[i!0 = 5,
a = [else -> k!8!10(k!9(Var(0)))],
k!8 = [else -> k!8!10(k!9(Var(0)))],
k!9 = [else -> If(Var(0) >= 4, If(Var(0) >= 5, 5, 4), 0)],
k!8!10 = [0 -> 7720, 4 -> 1, else -> -38]]

I don't know the meaning of the output and I think its model should be i = 5. Then, I add in a[5] > 0, and I think it should be unsatisfied. The code is as follows:
from z3 import *
i = Int('i')
a = Array('a',IntSort(),IntSort())
solver = Solver()
solver.add(ForAll(i, Implies(And(i >= 0,i < 5),a[i] > 0)))
solver.add(Exists(i, And(i >= 0,i <= 5, Not(a[i] > 0))))
solver.add(a[5] > 0)
print solver.check()
print solver.model()

And the output is:
unsat

So, how can I prove (∀i(0≤i<k→a[i]>0)∧a[k]>0)→∀i(0≤i≤k→a[i]>0) by z3py, and what's the meaning of the output?

A: It's a little unclear to me what you are trying to do with your queries. Why do you "set" the value of k? This doesn't seem to correspond with the general case of what you are trying to prove, according to the start of the question, but perhaps the special case is all you're interested in for now.
You have correctly turned your validity question into a satisfiability one: the negation of the formula is satisfiable iff the original formula is valid.
In the first response from Z3, you indeed get a model; this indicates a counter-example to the (weaker) first implication you are trying to prove. If you think about what the demonstration of this counter-example requires, you have to choose to instantiate the (bound) existential variable to 5. This is the meaning of i!0 in the model; it is a new (free) name representing the element of your model to which the existentially-bound variable gets assigned.
Looking at this another way (and more accurately, with respect to what the tool does), the existential quantifier is "skolemised" away (the existentially-bound variable is replaced with a fresh constant) before Z3 does the interesting work, so it's actually tackling a query equivalent to querying satifiability of the formula:
∀i(0≤i<k→a[i]>0)∧a[k]>0∧(0≤ i!0 ≤k∧¬(a[ i!0 ]>0))

When you strengthen the query back to the negation of your original implication, you get unsat from Z3. This means that this negated formula was unsatisfiable, so the implication you are interested in is valid; you have proved
    ∀i(0≤i<5→a[i]>0)∧a[5]>0)→∀i(0≤i≤5→a[i]>0)
You should get the same outcome if you skip setting k to be 5 in your problem.
With respect to the other information in the first response from Z3, the model must contain not only a value for (skolemised) i, but also for the array a in your problem. Arrays are represented as functions, which can be defined by cases in such a model; the "else" case is the catch-all, and the only case in each of the functions used here. Var(0) is the syntax for the function's (first, and only) parameter. In this model, the array is defined indirectly via the composition of two other functions, k!9 (which seems to be used to identify a partial set of indices relevant to the model; in this case, 0,4 and 5), and k!8!10 (which defines the mapping of these indices to values). In particular, in this model, the array stores 7720 at index 0, 1 at index 4, and -38 at index 5 (no other indices get produced by the cases of k!9's definition; conceptually, I would understand this as meaning that the array in this model is undefined at the other indices).