text:
Q: Recordwildcards crashes at runtime in yesod app I ran into the following error which is quite surprising. I added a field to the AppSettings in a Yesod app (using the Yesod scaffholding) and to my surprise, everything compiled even though I didn't do anything else (I was expecting to have to add somewhere a default value to the construction of AppSettings, but not). I got a runtime error instead telling me that a field was missing.
It appears that the only construction to AppSetting uses the RecordWildCards extension and looks like AppSettings{..}. Not defining the new field didn't generate an error but a warning (I didn't see it, because I was running test in continuous mode using stack test --file-watch). How is that possible ?
I try to reproduce the problem in a simple file and I get an error not a warning. So why do I get a warning for Yesod ? Is it a compilation flag or something ?
Edit
This is not specific to Yesod. I've made the test again with a simple file and it generates a warning not an error.

A: According to changelog in GHC, "that not a bug, it's a feature": https://ghc.haskell.org/trac/ghc/ticket/5334
You can change this behavior by changing type of your fields to strict (prepend a ! to type name - like !Int) - however, then you lose laziness (more about effects of strict types: Advantages of strict fields in data types)
Of course, you can also make it an error by slamming in -Werror compilation option, but then you need to be very strict about your code (no unused imports, no unused variables, even when unpacking a record etc.), or get rid of -Wall and turn on only warnings you perceive as important.


text:
Q: Is there a possibility of generating a 6 digit unique random number every time with xdmp:random() or some other way in Marklogic I tried using xdmp:random(999999) but it sometimes generates a 5 digit value and sometimes a 6 digit value - Is there any way of getting the every time unique 6 digit value?

A: Simplest is to pad with zeros using fn:format-number:
format-number(xdmp:random(999999), '000000')

Alternatively, you could also look at sem:uuid-string, which gives better random results with a fixed string-length.
HTH!

A: If leading zeroes don't work, make sure your base value is 100,000 and go up to 999,999.
xdmp:random(899999) + 100000

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't my values swap? I am supposed to write a function name double_swap that takes two doubles as arguments and interchanges the values that are stored in those arguments. The function should return no value, so I know that means it must be a void function.
For example, if the following code fragment is executed,
int main()
{
double x = 4.8, y = 0.7;
double_swap(x,y);
cout<<"x = "<<x<<" y = "<<y;
}

The output will be:
x = 0.7 y = 4.8
The program I wrote is not swapping the values. I'd greatly appreciate if someone could point out my errors.
#include <iostream>

using namespace std;

void double_swap(double x, double y)
{
        x = 1.9;
        y = 4.2;
}

int main()
{
        double x = 4.2, y = 1.9;
        double_swap(x,y);
        cout<<"x = "<<x<<" y = "<<y<<endl;

return 0;
}

A: You need to pass the variables by reference in order for the modifications in the function to apply to the variables from the call site.  As it is right now all you are doing is modifying copies that get destroyed once the function ends.
Change
void double_swap(double x, double y)

to
void double_swap(double& x, double& y)

Also instead of hard coding the values lets do a real swap using
void double_swap(double& x, double& y)
{
    double temp = x;
    x = y;
    y = temp;
}

You could also use pointers for the function paramters for this but then your call site would have to be changed to double_swap(&x,&y); and you would have to remember to reference the pointers in the function.
Instead of doing all of this though we can just use std::swap and let it do this for us.

A: When calling a function in c++ , There is 3 way to pass the parameters. The first one is by Copy where it only make a copy of the variable in parameters and then delete them.
 void double_swap(double x, double y)

The second one is by Reference, where the paramaters refere to the real variable (Whats you want).
 void double_swap(double& x, double& y)

And the last one is by address where you pass the address of the variables.
   void double_swap(double* x, double* y)


text:
Q: Core Data: Can a Large Background Fetch Block Fetch Request on the Main Thread? I have an iPad app with quite a bit of text data in Core Data (approx 75MB). New data is imported weekly. The import happens on a secondary thread with its own NSManagedObjectContext and even its own NSPersistentStoreCoordinator.
The import process contains a number of fetches, all of which are very efficient except one, as it returns a vast number of records (this can perhaps be optimized slightly more, but not materially so.)  Unfortunately, during the time the large fetch is made, the main UI is blocked (as it also has to fetch from the store and the fetch is delayed).
I have tested the import process at various points to confirm that it is indeed on a background thread. I have double checked code to ensure the import context with the separate coordinator is used. The undomanager is nil and the import context is reset frequently.
Is it possible that even with a separate NSPersistentStoreCoordinator a large fetch request in the background can still block fetch requests on the main thread or am I doing something wrong?

A: An operation on a background thread cannot block the main thread but it can consume so much memory that the main thread can longer operate efficiently.
It sounds like your numerous background fetches which "returns a vast number of records" is creating a large object graph of live objects in memory which is eating your memory. The low memory impedes the main thread.
Use Instruments to profile your memory to confirm.
The solution is to keep only the actual live, populated objects in memory you absolutely have to. You can use smaller fetches, fetch as faults, fetch properties or fetch as managedObjectIDs and similar methods to reduce the memory footprint.
Also, make sure your network operations that download the data itself don't eat memory or cycles.

A: Sounds like you're already dealing with threading correctly (though you do'nt technically need a new NSPersistentStoreCoordinator per thread, as long as you have a NSManagedObjectContext per thread).
Your large fetch sounds like the problem; have you looked at NSFetchedResultsController to batch the results?
If you already have then you need to find some way of optimizing your query - what is the NSPredicate you are using for the large fetch?

The other approach might be to offload your text data into flat files and just keep the filename in core data - this would reduce the amount of data you need to write, therefore blocking other threads for a shorter amount of time.
You could just add a method to your NSManagedObject subclass that got the text on request from the file - your UI shouldn't know how you are storing your text!

A:
as it also has to fetch from the store and the fetch is delayed

This is exactly the culprit, so, depending on your circumstances, the answer may be a definitive yes.  Specifically, if your large fetch happens on the same store as any other fetches, subsequent fetches will be blocked until the first one completes.
One tactic in this case is to pre-fetch, with returnsObjectsAsFaults = NO, any objects you're likely to use during the massive fetch.

Is it possible that even with a separate NSPersistentStoreCoordinator a large fetch request in the background can still block fetch requests on the main thread

In this case it should not block - but as you note in your question there are other factors which can cause a block.  This solution has its own problems re: integrating changes, but if you can merge the two coordinators then it works in principal.


text:
Q: Actualización crtl+f5 windows.reload JavaScript & PHP buenos dias , estoy tratando de hacer una actualizacion => ctrol+f5
que cuando tome la variable por el metodo get o post , y segun la variable se actualice la pagina pero solo una vez.
mi idea es hacer :
ejemplo :
<script type="text/javascript">

actualizar=<?php   if(isset($_GET["actualizar"])){
      echo $_GET["actualizar"];}
      else {
        echo "null";
      }
      ?>;

 if (actualizar!=null ){
  /* aca viene mi duda :
  cambiar la url (ya que viene con la variable
  ejemplo index.php?actualizar="si"),
  limpiar las variables quedando url =  index.php;
  osea la limpio para que no quede en un bucle infinito.

  y despues : pero me sigue dando el bucle infinito.

  location.reload(true);
 }

<script>

Gracias

A: Si lo que quieres es quitar todos los parámetros, podrías hacer algo como esto:
if (actualizar!=null ){
    document.location.href = document.location.pathname;
}

La idea es que document.location.pathname contiene la parte de la URL sin los parámetros o hash (#). Entonces si el parámetro actualizar está especificado, se redireccionará a la página sin parámetros y sin nada. Y así evitas el bucle infinito.

Si lo que quieres es quitar sólo el parámetro actualizar, preservando los otros parámetros y el hash, entonces podrías hacer esto:
if (actualizar!=null ){
    // obtenemos los parámetros sin el ?
    var paramString = document.location.search.substring(1);
    // lo convertimos en un array partiendo por los &
    var params = paramString.split("&");
    // eliminamos aquellos que comiencen con "actualizar"
    var newParams = params.filter(function(item) {
        if (item.indexOf("actualizar") != 0) { return item; }
    });
    // los unimos de nuevo
    var newParamsString = newParams.join("&");

    // redireccionamos a la url sin el parámetro actualizar, manteniendo lo demás
    document.location.href = document.location.pathname +
                             "?" + newParamsString +
                             document.location.hash;
}


text:
Q: http get request to https://stackoverflow.com/jobs/feed fails with CORS I want to read the StackOverflow job RSS feed, I tried adding "Access-Control-Allow-Headers" and proxy implementation as well, it errors out. Please help me to achieve this [SOLVED, Please see the answer below]
API URL: https://stackoverflow.com/jobs/feed
  private proxyPrefix = '/api';
  private hostName = 'stackoverflow.com';
  private location='sydney'
  private query = `location=${this.location}`;
  private path = 'jobs/feed';

  private stackOverFlowJobsRssFeedUrl = `${this.hostName}/${this.path}?${this.query}`;
  constructor(private http: HttpClient) { }

  private getData$(url: string): Observable<any> {
    const requestOptions = { headers: new HttpHeaders({ 'Access-Control-Allow-Headers': '*' }) };
    return this.http.get<any>(url, requestOptions);
  }

  private get stackOverflowJobs$(): Observable<any> {
    const proxyURL = `${this.proxyPrefix}/${this.path}?${this.query}`;
    return fromFetch(proxyURL, {
      selector: response => response.json()
    });
  }

  ngOnInit(): void {

    // http get
    this.getData$(this.stackOverFlowJobsRssFeedUrl)
      .subscribe((x) => {
        console.log(x);
      });

    // rxJs fetch using proxy
    this.stackOverflowJobs$.subscribe({
      next: result => console.log('jobs:',result),
      complete: () => console.log('done')
    });

  }

proxy.config

{
  "/api/jobs": {
     "target":  {
       "host": "https://stackoverflow.com",
       "protocol": "https:",
       "port": 443
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}

Error
[HPM] Error occurred while trying to proxy request /api/jobs/feed?location=sydney from localhost:4200 to https://stackoverflow.com (ENOTFOUND) (https://nodejs.org/api/errors.html#errors_common_system_errors)

A: Are you sure that CORS is allowed on the SO server-side? Try to send this from SO and another domain console in dev tools, you will get a response only from SO.
One of the options is to set up some server and use it as middleware, then the CORS issue will be not relevant
fetch('https://stackoverflow.com/jobs/feed')
  .then(function(response) {
    return response.text();
  }).then(function(data) {
    console.log(data); // this will be a string
});

A: {
  "/proxy/*": {
  "target": "https://stackoverflow.com",
  "secure": false,
  "changeOrigin": true,
  "logLevel": "debug",
  "pathRewrite": {"^/proxy" : ""}
  }
}

This proxy config solved my problem :)
StackOverflow Ref: Angular-CLI proxy to backend doesn't work


text:
Q: Pikachoose thumbnail carousel not working I am using the Pikachoose plugin for the image galleries on my website (http://www.clare-eileen-callahan.com/inthehangar/). Everything seems to be working except for the thumbnail carousel. They just pile up on the bottom of the page, where I want the carousel to be horizontally scrollable, so that only x amount of thumbnails are visible. I can't figure out what is going on with the CSS and Javascript that is preventing it from displaying as it should.
Here is the code I'm using: http://codepen.io/anon/pen/ybExq
Sorry there is a lot of it for the plug in!

A: For whatever reason, there was an unexpected element in the original jquery carousel script. I was able to find it by breaking apart the script into short lines and referring back to the console.


text:
Q: SDL 2.0 Build Error(Duplicate) I haven't actually been able to use SDL 2.0 on my laptop, so I am reposting the whole post again. Hopefully somebody else can help me, as I am a little desperate.
"Apparently, I don't have SDL installed correctly since a sample program I found in some of the tutorials for SDL 2.0 don't buid correctly.
Mind you, I am using Ubuntu 12.04 as my operating system, used the instructions in the source code of SDL 2.0.3 to install it on my OS, am using CodeLite 5.4, and am using C as my programming language.
Here is the code I try to test:
#include <SDL2/SDL.h>
#include <stdio.h>

int main(int argn,char **argv)
{
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        fprintf(stderr,"Could not initialize SDL: %s\n", SDL_GetError());

    }

    printf("SDL Initialized\n");
    SDL_Quit();
    printf("SDL Shutdown\n");
    return 0;
}

However, I get this:
/bin/sh -c 'make -j 1 -e -f  Makefile'
----------Building project:[ SDL - Debug ]----------
make[1]: Entering directory `/home/user/Documents/Programming/C/SDL'
gcc -o ./Debug/SDL @"SDL.txt" -L.
./Debug/main.o: In function `main':
/home/user/Documents/Programming/C/SDL/main.c:6: undefined reference to `SDL_Init'
/home/user/Documents/Programming/C/SDL/main.c:8: undefined reference to `SDL_GetError'
/home/user/Documents/Programming/C/SDL/main.c:13: undefined reference to `SDL_Quit'
collect2: ld returned 1 exit status
make[1]: *** [Debug/SDL] Error 1
make[1]: Leaving directory `/home/user/Documents/Programming/C/SDL'
make: *** [All] Error 2
3 errors, 0 warnings

Can someone please explain to me what the issue is and how I can fix it?"

A: From codelite:
Right click on the active project icon (in the tree view) -> Settings -> Common Settings -> Linker -> Libraries
and add:
SDL2 (no need to add -l, or .a/.so codelite will fix this for you)
Hit F7 and it should link fine
Eran


text:
Q: Laravel app doesn't send email notifications to gmail account I just wanna enquire something
I have a school application done in laravel whereby when a user is added to the system it will send a notification email informing the user about his registration is success, passwords and stuff.
The problem now when I try to register a user who has a gmail account (vusumzi@gmail.com) as an email, it doesn't send the notification mail, but when I use other email account (vusumzi@yeboict.co.za) it does work fine.
what could be the problem?... my website is on production not dev


text:
Q: Should I use a many-to-many relationship or obtain info through one-to-many relationships? So I have a war-like game with three tables: User, Player, and Game.

*

*The User table contains email, username, password hash, and other user-specific info.

*The Game table contains info about each game and the state of each game world.

*The Player table contains info about each player in a game: how many units they have, etc.

I have the following relationships:

*

*A one-to-many relationship between User and Player, since each User can be in several different Games, and control several different Players simultaneously.

*A one-to-many relationship between Game and Player, since each Game has multiple Players in it.

So in order to find the Games that a specific User is in, is it better practice to either:

*

*Make a many-to-many relationship between User and Game, or

*Write a function that takes the list of Players from a User, then find the Game IDs from the Player columns?

(I'm using SQLAlchemy with SQLite and Flask, but I don't think that's important to this question.)
The attached image may explain it better: should I have any database connections between User and Game?
I'd be glad to clarify anything, and thanks for any possible help! Sorry if this is a bad question for StackOverflow.

A: When a many-to-many relationship exists, say gameUsers,  a common implementation is to create an intermediary table, containing the ids of each of the tables, in this case a list of user_id, game_id pairs representing which games each user is in.
But... you already have such a table, the player table. So my approach would be to think of the player table as that resolution table. The player table already contains which games each user is in, so that second many-to-many is not really required.


text:
Q: Access Python class defined "inline" in Matlab workspace I just discovered today that I can call Python code from Matlab and I wanted to create a Python class directly in the Matlab workspace and then access it, instead of having it defined in a module in a separated file. I managed to do it (there must be a more elegant way to do it, though) but when I try to access the class, as the class seems to be stored in the main scope/module of Python "__main__", I cannot reach it without using pyrun.
So, I create the dummy class as:
idt=@(n) strjoin(repmat("    ",1,n));
pyrun(["class PyClass(object):",
       idt(1)+"def __init__(self):",
       idt(2)+"self.value = 5",
       idt(1)+"def setValue(self, v):",
       idt(2)+"self.value = v"]);

But if I try
myObj1 = py.PyClass();  %not working
myObj2 = py.__main__.PyClass(); %not working

I found a workaround by doing:
myObj3 = pyrun("myObj=PyClass()","myObj");

But I want to know how I can access my inline class directly or how I can reference the __main__ module of Python.
Thanks in advance.


text:
Q: Get $_SESSION position with & Why this code doesn't work?
public function get($key) {
    return isset($_SESSION[$key]) ? &$_SESSION[$key] : false;
}

Error
Parse error: syntax error, unexpected '&' in C:\Arquivos de programas\EasyPHP-5.3.3\www\myphpblog\code\sessionstorage.class.php on line 12

Thank you.

A: A ternary operator is really three expressions, e.g. expr1 ? expr2 : expr3;
See the Notes in Returning References:

If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else.

A: The syntax for returning a reference in PHP is &<function name>(){ return <referece> }
Also, Only variable references should be returned by reference
So, you should probably rewrite it:
function &get($key) {
    $a = false;
    if( isset($_SESSION[$key]) )
        return $_SESSION[ $key ];
    return $a;
}

A: Just remove the & and it will work. Dah...


text:
Q: How to get a ragged-right footnote with Memoir I need to put a rather long list of names in a footnote. They can't be properly hyphenated and do not break into pretty lines, so leaving the right side of text ragged seems a perfect solution to me.
However, I was surprised when \footnote{\raggedright ABC} did not work out. \RaggedRight from ragged2e package fails too as well as \usepackage[ragged]{footmisc}.
I'm using memoir as a document style, so I tried plain article instead... and \raggedright started working as expected.
\documentclass[a4paper, 12pt]{memoir}
%\documentclass[a4paper, 12pt]{article}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.\footnote{\raggedright Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.} Excepteur sint occaecat upidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.\footnote{Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.} Excepteur sint occaecat upidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\end{document}

I suspect memoir's footnote series are the cause, but their source code is, ugh... complex.
So, a question: how do a I make a certain footnote left-justified with memoir?

A: Using a redefinition of \@makefntext you can achieve what you want. The original definition is
\newcommand{\@makefntext}[1]{\makefootmark #1}

so you can say something like
\renewcommand{\@makefntext}[1]{\makefootmark\raggedright##1}}

In the example below I used the redefinitions inside commands such that you can switch to the new style (and restore the original behaviour) at any moment:
\documentclass[a4paper, 12pt]{memoir}

\makeatletter
\newcommand\RaggedFootnote{%
  \renewcommand{\@makefntext}[1]{\makefootmark\raggedright##1}}
\newcommand\StandardFootnote{%
  \renewcommand{\@makefntext}[1]{\makefootmark##1}}
\makeatother

\begin{document}
\null\vfill%just for the example
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.\RaggedFootnote\footnote{Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.}\StandardFootnote Excepteur sint occaecat upidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.\footnote{Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.} Excepteur sint occaecat upidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\end{document}

A: There's no real need to mess with the internal footnoting commands, as long as you are using the ragged2e package, since memoir provides a hook for styling the footnote text.  You simply need to add
\renewcommand\foottextfont{\footnotesize\RaggedRight}

(assuming you're loading ragged2e).
For some reason this doesn't work with plain \raggedright.


text:
Q: OneToMany between 2 classes with Hibernate I'm trying to get the hang of Hibernate.
After getting my project to compile, I've started to convert my classes to be "Hibernate-enabled"
Currently, I'm having 2 classes
1) Person (id, name, firstname, ...)
2) Task (Id, name, description, idOwner)
I would like to have a OneToMany relationship between Person(id) and Task (idOwner)
So when the users gets the List from the Person class, they would get all the tasks linked to that.
After some trying and failing, here's my current code:
Person.java
@Entity
@Table(name = "people", uniqueConstraints = {
@UniqueConstraint(columnNames = "PERSON_ID")
})
public class Person implements Serializable {

private int id;
private String firstName;
private String name;
private String function;
private String email;
private String password;
private RoleEnum role;
private List<Task> lstTasks;

public Person(String firstName, String name, String function) {
    this.firstName = firstName;
    this.name = name;
    this.function = function;
    this.email = "";
    this.password = "";
    this.setRole(RoleEnum.User);
}

// <editor-fold defaultstate="collapsed" desc="Getters">

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "PERSON_ID", unique = true, nullable = false)
public int getId() {
    return id;
}

@Column(name = "PERSON_FIRSTNAME", unique = false, nullable = false, length = 30)
public String getFirstName() {
    return firstName;
}

@Column(name = "PERSON_NAME", unique = false, nullable = false, length = 30)
public String getName() {
    return name;
}

@Column(name = "PERSON_FUNCTION", unique = false, nullable = false, length = 30)
public String getFunction() {
    return function;
}

@Column(name = "PERSON_EMAIL", unique = false, nullable = false, length = 30)
public String getEmail() {
    return email;
}

@Column(name = "PERSON_PASSWORD", unique = false, nullable = false, length = 30)
public String getPassword() {
    return password;
}

@Column(name = "PERSON_ROLE", unique = false, nullable = false, length = 30)
public RoleEnum getRole() {
    return role;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
    return lstTasks;
}

//Setters

}

Task.java
@Entity
@Table(name="tasks", uniqueConstraints =
@UniqueConstraint(columnNames = "TASK_ID"))
public class Task implements Serializable {

private int id;
private String name;
private String description;
private int idOwner;

public Task(int id, String name, int idOwner) {
    this.id = id;
    this.name = name;
    this.idOwner = idOwner;
}

// <editor-fold defaultstate="collapsed" desc="Getters">

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "TASK_ID", unique = true, nullable = false)
public int getId() {
    return id;
}

@Column(name = "TASK_NAME")
public String getName() {
    return name;
}

@Column(name = "TASK_DESCRIPTION")
public String getDescription() {
    return description;
}

@Column(name = "TASK_ID_OWNER")
public int getIdOwner() {
    return idOwner;
}

// </editor-fold>

//Setters

}

Can somebody tell/show/explain me what I have to do exactly, to make this work?

A: Currently your mapping should linking ownerId instead of Task class.
Change your Task class to this
private Person person;

@ManyToOne
@JoinColumn(name = "TASK_ID_OWNER")
public Person getPerson() {
    return person;
}

A: In your Person entity you have declared one-to-many relationship with Task entity like this:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
    return lstTasks;
}

Here you have given idOwner to mappedBy attribute, it means you are telling hibernate that there is property in Task class called idOwner which is of type Person.
So you have to modify your Tasks class like this (Changing the variable type from int to Person):
private Person idOwner;

@ManyToOne
@JoinColumn(name = "TASK_ID_OWNER")
public Person getIdOwner() {
    return idOwner;
}

public void setIdOwner(Person idOwner) {
    this.idOwner=idOwner;
}

If you remove the @JoinColumn annotation then hibernate will create a Join table for your relationship, else it will just create a foreign key in Task table with foreign key column name as TASK_ID_OWNER.


text:
Q: Add off click and escape functionality to fadeToggle I'd like to have the ability to re-activate the fadeToggle to close if it detects an off canvas click or the esc button is pressed.
http://jsfiddle.net/sj6kdyLk/
$("#name").click(function() {
$("#about").fadeToggle(500, "linear");
});

$(document).keyup(function(e) {
 if (e.keyCode == 27) {
   if($('#about').css === 'block'){
     $('#about').hide(200)
   }
}
});

A: $('#about').css wont work in this case. You should use is(':visible'), so your code should look like:
if ($('#about').is(':visible')) {
...
}

Updated fiddle: http://jsfiddle.net/sj6kdyLk/2/


text:
Q: Entity Framework Objects Serialization through WCF the situation is as following: while adding an object which has 2 level of details into the database using EF the process works fine on SaveChanges() for the first time since all data is loaded from the database.
I tried to store the lists in Sessions and even ViewState (to avoid any serialization problems)
but when i create a new object and add the details to it , the insert process failed at the web level due a serialization problem
Note : the call to the business and data-layer is routed through WCF service


text:
Q: Why my site isn't fully functioning on public domain (in the world wide web)? I made a simple website. The site is fully functionable in my localhost (my computer). Everything working fine here.
But problem arises when I upload the files into the web server in order for running that in public domain. There, no content is showing except the layout. No link or tab is working, no paragraph inside the body is displaying. You may have a look here.
For what reason?
I uploaded all the files (with source code) associated my website except the images and videos (since there are a lots of images and I will upload it a bit later).
[NOTE: I have xampp local server installed in my computer. All the
sourse codes files are stored inside the htdocs folder. Inside the
htdocs folder I have a folder named jquery(which was installed with
the package). I saved my .JS file inside the JQuery folder (since I
used jquery code too). So when I upload file into the server do I need
to upload the whole htdocs folder? Or how about the JQuery folder
(which contains the JQuery source code)? Do I also need to upload it?
My paths set are the following:
C:\xampp\htdocs\jquery [contains the whole project's source file]
C:\xampp\htdocs\jquery\js  [Contains only JavaScript&JQuery file]

A: I tried debugging the HTML on your website. I found the following code in design.css at line number 258
#all_contents >div {
display:none;
}

Once you remove this(display:none), all the content is available on the website link that you shared.
Also, I am not sure why this is working on your local. Are you sure that you have uploaded the same version which is running in your local?
You can debug your webpage by pressing F12 and then selecting the problematic area. On the right hand side, you can see the css rules associated with the selected element.
For getting the specific content in a page and not all, create a new file by the name who_im.html and put your content over there and then You should do something like
    About Me
Like this you will have to make other pages as well and add the hyper links to the menu in every page.

A: If you inspect your page and look where you expect the content to be, you'll find <div id="home">.  Looking at the CSS for this, it shows line 258 of your css file has this:
#all_contents >div {
display:none;
}

This is causing all of your contents to not display. Removing this will fix the problem.
Also, if you look on the browser's console when your page loads, you'll notice a lot of 404s trying to load various scripts, stylesheets, and images. That's potentially contributing to the problem. I'd focus on fixing those first, to make sure everything is loading properly.


text:
Q: Create transparent gif/png with dynamic dimensions Trying to create a gif or png with user-defined dimensions. The closest I've got is with this:
$imgWidth = intval($_GET['x']);
$imgWidth = $imgWidth > 0 ? $imgWidth : 1;

$imgHeight = intval($_GET['y']);
$imgHeight = $imgHeight > 0 ? $imgHeight : 1;

$im = imagecreatetruecolor($imgWidth, $imgHeight);
$white = imagecolorallocate($im, 0, 0, 0);

imagecolortransparent($im, $white);

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

This appears to work but on closer inspection it actually creates an image with the correct dimensions but with a 0 x 0px foreground. This is causing the image to display incorrectly in some clients, e.g. I get a memory error in Photoshop. I can open it in Fireworks but it displays the zero pixel bitmap at the extreme top left in front of a transparent background:

I tried adding imagefilledrectangle($im, 0, 0, $imgWidth, $imgHeight, $white); directly after imagecolortransparent($im, $white); but it has no effect.
What am I missing?

A: This seems to be a peculiarity of the Adobe applications you mention. I don't have a copy of those so I can't test with them, but every other application I've tried renders the image as expected.
Perhaps try the following to see if the resulting image is more acceptable to Adobe:
$imgWidth = intval($_GET['x']);
$imgWidth = $imgWidth > 0 ? $imgWidth : 1;

$imgHeight = intval($_GET['y']);
$imgHeight = $imgHeight > 0 ? $imgHeight : 1;

$im = imagecreatetruecolor($imgWidth, $imgHeight);
imagealphablending($im, false);
imagesavealpha($im, true);
$white = imagecolorallocatealpha($im, 255, 255, 255, 127); // fully transparent white.

imagefill($im, 0, 0, $white);

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

At a guess, I would say the problem occurs because you're setting the transparency as a property of the image rather than as a property of the colour (or, more accurately, pixel).
The former is ordinarily used for palette-based images (imagecreate) where the pixel is either fully opaque or fully transparent and cannot otherwise appear in the image. That is, if red (ff0000) is considered fully transparent by the image, all red pixels will be transparent and the colour won't display at all.
For a true-colour image (imagecreatetruecolor) the ability to specify the transparency as a property of the pixel is a better approach since it enables partial transparency.  This means you can use the same colour with a different transparency level for different pixels.
The script above uses the latter approach.


text:
Q: Getting "error: cannot convert 'std::__cxx11::string* {aka std::__cxx11::basic_string*}' to 'const char*' error while passing a path as argument I am new to programming.I want to access all the directories and sub-directories from default installed directory,but it is failing in traversing the folder, here i am passing path to constant char.Below is the code
using namespace std;

int reading(const char *d_path)
{
    cout<<"In Reading"<<endl;

    /*bfs::path pathSource("c:\\Program Files\\");*/
    struct stat info; //

    DIR *dir;
    struct dirent *ent;
    dir= opendir (d_path);
    cout<<dir<<endl;
  if ((dir = opendir (d_path)) != NULL)
  {
      cout<<"in IF"<<endl;
       while ((ent = readdir (dir)) != NULL)
       {
          if (ent->d_name[0] != NULL)
          {
              cout<<"New"<<endl;
              string path = string (d_path) + string(ent->d_name) + '\\' ;
              cout<< "Entry = "<<path<<endl;
              stat (path,&info);
              if(S_ISDIR(info.st_mode))
              {
                  reading(path);
              }

          }
       }
       closedir (dir);
  }
  /* print all the files and directories within directory */

 else
    {
  /* could not open directory */
      perror ("");

    }

return 0;
}

A: Use the string::c_str() method, like stat(path.c_str()), to convert a C++ string to a C string.
See http://cplusplus.com/reference/string/string/c_str/ for more information.


text:
Q: make MariaDB update from Python much faster I have a python script that aggregates data from multiple sources to one, for technical reasons.
In this script, I create an employees table fills it with data and in a second step, fetch each employee's name/last name from another data source. My code is the following:
Create the table and fill it with data:
def createIdentite(mariaConnector, fmsConnector):
    print('Creating table "Identite"...')
    mariadbCursor = mariaConnector.cursor()

    # verify we have the destination tables we need
    print(' Checking for table Identite...')
    if mariaCheckTableExists(mariadbConnector, 'Identite') == False:
        print(' Table doesn\'t exist, creating it...')
        mariadbCursor.execute("""
            CREATE TABLE Identite (
                PK_FP VARCHAR(50) NOT NULL,
                LieuNaissance TEXT,
                PaysNaissance TEXT,
                Name TEXT,
                LastName TEXT,

                Nationalite TEXT,
                PaysResidence TEXT,
                PersonneAPrevenir TEXT,
                Tel1_PAP TEXT,
                Tel2_PAP TEXT,
                CategorieMutuelle TEXT,
                Ep1_MUTUELLE BOOLEAN,
                TypeMutuelle BOOLEAN,
                NiveauMutuelle BOOLEAN,
                NiveauMutuelle2 BOOLEAN,
                NiveauMutuelle3 BOOLEAN,
                PartMutuelleSalarie FLOAT,
                PartMutuelleSalarieOption FLOAT,
                PRIMARY KEY (PK_FP)
            )
            """)
        mariadbCursor.execute("CREATE INDEX IdentitePK_FP ON Identite(PK_FP)")
    else:
        # flush the table
        print(' Table exists, flushing it...')
        mariadbCursor.execute("DELETE FROM Identite")

    # now fill it with fresh data
    print(' Retrieving the data from FMS...')
    fmsCursor = fmsConnector.cursor()
    fmsCursor.execute("""
        SELECT
            PK_FP,
            Lieu_Naiss_Txt,
            Pays_Naiss_Txt,
            Nationalite_Txt,
            Pays_Resid__Txt,
            Pers_URG,
            Tel1_URG,
            Tel2_URG,
            CAT_MUTUELLE,
            CASE WHEN Ep1_MUTUELLE = 'OUI' THEN 1 ELSE 0 END as Ep1_MUTUELLE,
            CASE WHEN TYPE_MUT = 'OUI' THEN 1 ELSE 0 END as TYPE_MUT,
            CASE WHEN Niv_Mutuelle IS NULL THEN 0 ELSE 1 END as Niv_Mutuelle,
            CASE WHEN NIV_MUTUELLE[2] IS NULL THEN 0 ELSE 1 END as Niv_Mutuelle2,
            CASE WHEN NIV_MUTUELLE[3] IS NULL THEN 0 ELSE 1 END as Niv_Mutuelle3,
            PART_MUT_SAL,
            PART_MUT_SAL_Option
        FROM B_EMPLOYE
        WHERE PK_FP IS NOT NULL
        """)

    print(' Transferring...')
    #for row in fmsCursor:
    insert = """INSERT INTO Identite (
                PK_FP,
                LieuNaissance,
                PaysNaissance,
                Nationalite,
                PaysResidence,
                PersonneAPrevenir,
                Tel1_PAP,
                Tel2_PAP,
                CategorieMutuelle,
                Ep1_MUTUELLE,
                TypeMutuelle,
                NiveauMutuelle,
                NiveauMutuelle2,
                NiveauMutuelle3,
                PartMutuelleSalarie,
                PartMutuelleSalarieOption
            ) VALUES (
                %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
            )"""
    values = fmsCursor.fetchall()
    mariadbCursor.executemany(insert, values)
    mariaConnector.commit()
    print(' Inserted '+str(len(values))+' values')
    return len(values)

And the part where I retrieve first name and last name:
def updateEmployeeNames(mariaConnector, mssqlConnector):
    print("Updating employee names...")
    mariadbCursor = mariaConnector.cursor()
    mssqlCursor = mssqlConnector.cursor()

    mssqlCursor.execute("SELECT Name, LastName, PK_FP FROM F_Person")
    rows = mssqlCursor.fetchall()

    query = """
        UPDATE Identite
        SET Name = %s, LastName = %s
        WHERE PK_FP = %s
    """
    mariadbCursor.executemany(query, rows)

    mariadbConnector.commit()

As you might have guessed, the first function takes almost no time to execute (less that 2 seconds), where the second one take almost 20.
Python's not my strong suit, but there might be another way, the aim is to make it much faster.
I already tried adding values to createIdentite's each tuple before the executeMany, but Mysql connector won't let me do that.
Thanks a lot for your help.

A: So the UPDATE to the existing MariaDB table is the bottleneck, in which case it might be faster to do the update on a pandas DataFrame and then push the result the MariaDB table using pandas to_sql method. A simplified example would be ...
df_main = pd.read_sql_query(fms_query, fms_engine, index_col='PK_FP')
df_mssql = pd.read_sql_query(mssql_query, mssql_engine, index_col='PK_FP')
df_main.update(df_mssql)
df_main.to_sql('Identite', mariadb_engine, if_exists='replace',
               dtype={'PK_FP': sqlalchemy.types.String(50)})

... where fms_query and mssql_query are the queries from your question. fms_engine, mssql_engine, and mariadb_engine would be SQLAlchemy Engine objects.

A: In all MySQL Python Drivers the execute_many is rewritten, since bulk operations are not supported in MySQL, they are supported only via binary protocol in MariaDB since 10.2, full support (including delete and update) was added later and is available in the lastest 10.2, 10.3 and 10.4 versions of MariaDB Server.
The python Driver is rewriting an insert query, iterates over the number of rows and transforms the statement to
INSERT INTO t1 VALUES (row1_id, row1_data), (row2_id, row2_data),....(rown_id, row_n data)

This is quite fast, but the SQL Syntax doesn't allow this for UPDATE or DELETE. In this case the Driver needs to execute the statement n times (n= number of rows), passing the values for each row in a single statment.
MariaDB binary protocol allows to prepare the statement, executing it by sending all data at once (The execute package also contains the data).
If C would be an alternative, take a look at the bulk unittests on Github repository of MariaDB Connector/C. Otherwise you have to wait, MariaDB will likey release it's own python Driver next year.

A: *

*Create the index as you create the temp table.

*These combined statements work:  CREATE TABLE ... SELECT ...; and INSERT INTO table ... SELECT ....  However, they may be difficult to perform from Python.

*It is unclear whether you need the temp table at all.

*Learn how to use JOIN to get information simultaneously from two tables.


text:
Q: SSAS Calculated Table without data I am developing a SSAS tabular model , and I have one calculated table for the dates (=DimDate).
When I use the model in Power BI or in SSMS, the calculated table has no rows.
What could be the problem?
Thanks

A: Process the table, if that doesn't work you may need to rebuild it. I've noticed SSAS can be finicky with calculated tables sometimes.


text:
Q: Cannot login using listener name on secondary server after failover i am not able to connect using AG listener name after fail-over to secondary server. SSMS gives error 18456 ( login failed for user ''). I have tested following scenarios:
- 1st server is working as expected with listener. Problem occurs when second server becomes primary
- Can login using instance name with same user but not when use listener name
- Pinging listener name from both servers return correct IP address
Not sure what else to check. Any help would be greatly appreciated

A: May I know when you connected to listener name, what kind of authentication you were using?  SQL Authentication or Windows Integration authentication?
If it was windows authentication, was that local windows user or AD user?
If it was SQL Authentication, can you check if the SQL logins has the same SID? Please run the following on both primary replica and secondary replica and post here:
USE <your db name>
SELECT name, sid FROM sys.sysusers WHERE name = 'your user name'
GO
USE MASTER
SELECT name, sid FROM sys.sql_logins WHERE name = 'your user name' GO

Per my experience, I suspect you were using SQL Authentication. Let me know!


text:
Q: How to parse(append) value to existing xml file in oracle? How to parse(append) value to existing xml file in oracle???
(I have standard fields in my xml file, i want to change that field value dynamically from oracle database).
Thank you.

A: SELECT UpdateXML(XMLTYPE('d'), '/a/b/text()', 'c') FROM dual;


text:
Q: Passing python objects to C Gstreamer functions, using Cython I'm using Python3.6 with GStreamer-1.0 and PyGObject (for python access) to read video frames from a camera (tiscamera).
The frames are gotten via python code and eventually I get a GstBuffer:
import gi
gi.require_version("Gst", "1.0")
from gi.repository import

# Set up
Gst.init([])
pipeline = Gst.parse_launch("tcambin serial=12345678 name=source ! video/x-raw,format=GRAY8,width=1920,height=1080,framerate=18/1 ! appsink name=sink")
sink = pipeline.get_by_name("sink")
sink.set_property("max-buffers", 10)
sink.set_property("drop", 1)
sink.set_property("emit-signals", 1)
pipeline.set_state(Gst.State.PLAYING)

# Get sample
sample = sink.emit("pull-sample")
buffer = sample.get_buffer()
meta = buffer.get_meta("TcamStatisticsMetaApi")

The type of meta is gi.repository.Gst.Meta, but in C it's actually TcamStatisticsMeta*, as can be understood by looking at tiscamera's c code example 10-metadata.c. The C code there is:
GstBuffer* buffer = gst_sample_get_buffer(sample);
GstMeta* meta = gst_buffer_get_meta(buffer, g_type_from_name("TcamStatisticsMetaApi"));
GstStructure* struc = ((TcamStatisticsMeta*)meta)->structure;

My problem is that in Python, I can't access struct attributes defined in TcamStatisticsMeta. I'm simply missing the casting bit from GstMeta* to TcamStatisticsMeta* and the translation of TcamStatisticsMeta* into a PyObject.
Does anyone have a direction of how this can be done without needing to modify/recompile the gstreamer-1.0 C code? Using Cython perhaps?
I've started using Cython to try and call a C function with data I get from Python. The python object is of type gi.repository.Gst.Buffer and the function should get a GstBuffer*, but I can't find a way to get the struct pointer from the Python object.
Here is my .pxd file:
cdef extern from "gstreamer-1.0/gstmetatcamstatistics.h":
    ctypedef unsigned long GType
    ctypedef struct GstBuffer:
        pass
    ctypedef struct GstMeta:
        pass

    GstMeta* gst_buffer_get_meta(GstBuffer* buffer, GType api)
    GType g_type_from_name(const char* name)

And my .pyx file:
from my_pxd_file cimport GType, g_type_from_name, GstMeta, gst_buffer_get_meta

cdef void c_a(buffer):
    cdef char* tcam_statistics_meta_api = "TcamStatisticsMetaApi"
    cdef GType gt = g_type_from_name(tcam_statistics_meta_api)
    cdef GstMeta* meta = gst_buffer_get_meta(buffer, gt)

def a(buffer):
    c_a(buffer)

And my python file:
# No need to use pyximport as I've cythonized the code in setup.py
from . import my_pyx_file
...
buffer = sample.get_buffer()
my_pyx_file.a(buffer)

This results in a SIGSEGV error:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

The  problem is that I can't cast buffer into a GstBuffer*. Does anyone know how to do that?
Debugging in Pycharm, I can actually see the GstBuffer* address:
<Gst.Buffer object at 0x7f3a0b4fc348 (GstBuffer at 0x7f39ec007060)>

But how do I get this address so I can pass it to gst_buffer_get_meta?
Is there a canonical Cython way to do that?


text:
Q: Abort request while navigating away from the component in React I am using react, redux and react-router. One of my page is making an API request and showing the data. It works fine. What I want to know is, if the API request is not yet finished, and the user navigates to another route, I want to be able to abort the request.
I am assuming I should dispatch some action in the componentWillUnmount. Just not able to understand how will it work. Something like...
componentWillUnmount() {
    this.props.dispatch(Actions.abortRequest());
}

And I'll store the xhr reference somewhere in the action. Not sure if this is the correct approach or not (I think not), can someone point me in the right direction?

A: I don't think storing xhr in action is correct.
Actions should be serializable, and XMLHttpRequest definitely isn't.
Instead, I'd use Redux Thunk to return a custom object from my action creator, and do something like this:
function fetchPost(id) {
  return dispatch => {
    // Assuming you have a helper to make requests:
    const xhr = makePostRequest(id);

    dispatch({ type: 'FETCH_POST_REQUEST', response, id });

    // Assuming you have a helper to attach event handlers:
    trackXHR(xhr,
      (response) => dispatch({ type: 'FETCH_POST_SUCCESS', response, id }),
      (err) => dispatch({ type: 'FETCH_POST_FAILURE', err, id })
    );

    // Return an object with `abort` function to be used by component
    return { abort: () => xhr.abort() };
  };
}

Now you can use abort from your component:
componentDidMount() {
  this.requests = [];
  this.requests.push(
    this.props.dispatch(fetchPost(this.props.postId))
  );
}

componentWillUnmount() {
  this.requests.forEach(request => request.abort());
}

A: I don't see anything wrong with this approach. What you're holding in the store is the global application state; if you want to change the xhr behaviour based on other actions then you need to store that state somewhere.
I've seen plenty of examples where the store would look something like this:
{
  isFetching: false,
  items: [],
  lastUpdated: null
};

The isFetching state is then used to display a loading spinner or prevent multiple xhr requests being sent. I'd see your use and storing the xhr reference and being able to abort it is just an extension of this.


text:
Q: how to combine Isin , contains ,with case sensitive while filtering data I have a data frame and I have multiple conditions to filter that data
for ex:
state =  Andhra Pradesh, Uttar Pradesh, Madya Pradesh, Karnataka, Telangana

and
field_id = 23234,23235,34342,34343...

 Input:
 --------
field_id,state,latitude,longitude
23234,Uttar Pradesh,28.05990445,78.34249247
23235,Uttar Pradesh,27.6206712,78.7132515
23236,Uttar Pradesh,27.95378227,79.04653615
23237,Uttar Pradesh,28.63232205,78.5763061
34342,Telangana,18.71517059,78.70715893
34343,Telangana,18.11666882,79.3873906
34344,Telangana,18.4527501,79.21027678
45452,Madhya Pradesh,21.70770808,75.67139279
45453,Madhya Pradesh,21.75613982,76.29656126
45454,Madhya Pradesh,22.05077277,79.2375098
56562,Karnataka,12.38318394,76.02965431
56563,Karnataka,12.38297092,76.02957524
56564,Karnataka,14.26369026,75.43180631
67672,Andhra Pradesh,16.83612945,80.99260486
67673,Andhra Pradesh,16.83277887,80.99537748
67674,Andhra Pradesh,16.83311322,80.99560818

I tried
state = Andhra Pradesh,Madhya Pradesh,Karnataka
State1 = State.split(',')
dsna = dsna.loc[dsna['State'].isin(State1)]

Which works with exact match case
field_id = 23234,34345
field_id1 = field_id.split(',')
dsna = dsna.loc[dsna['field_id'].isin(field_id1)]

Here also filters exact data frame
here dsna is my dataframe i will attach csv of that data frame or table
dsna = dsna.loc[dsna['field_id'].isin(field_id1)]
dsna = dsna.loc[dsna['State'].isin(State1)]

I wanted filter data based on regex format
like state = pradesh,telangana ( i gave lower case)
it should filter all data related to those states and list down latitude and longitude
similar way field_id= 232,343,454 should filter all fields reated to data expecting data should relate to the regex and case sensitive and filter multiple values any pandas functionality helps to do that Since my data already in data frame

A: By using Pandas
dsna = dsna[dsna['State'].str.contains('|'.join(State),
                                                     case=False)]

I used | to search throughout Strings.


text:
Q: How to make a sidebar form show at the top of page on mobile? There is a quote request form on the sidebar of homepage and all other pages. On mobile and tablets, this form used to show on the top. But something changed and now it shows on the bottom of page when using mobile. Only the homepage remains to show it on the top. All other pages show on bottom. Not sure what changed, but I would like to have it back on the top of page for mobile viewers.
Here is what it looks like: http://prntscr.com/o0ywj8
Anyone know how to get this to show on top of page for mobile?

A: Without knowing more, I can't tell you if this is a theme setting or plugin update that changed this, or if the code literally was changed, or why the homepage works but the rest doesn't.
I can tell you from the provided screenshot that the necessary bootstrap that would swap the positions isn't there. See their reordering guide for bootstrap 4. If you have the ability to edit the template, you should be able to apply this and have it ordered properly.


text:
Q: How to remove a workflow Is there a way to completely remove a workflow from an application when there are records still 'in process'? I've tried inactivating the workflow, but of course it won't allow that while there are records still 'in' the workflow.
Update: I did try setting the fields to 0/false. That did allow me to delete the workflow fields, but it did not allow the workflow itself to be deleted. I started looking through the database tables and found tblEnrolledContent and tblContentReviewStage. In tblEnrolledContent, I found the records 'stuck' in the review_stage id that matched to the workflow stage in tblContentReviewStage. I deleted the records equal to that stage id and I was able to then delete the workflow without issue. I did try this on a development environment. I have had no issues with the application, and I had no issues creating a new workflow on the application.

A: In 5.5 - found solution was to delete the rows in tblEnrolledContent where stage_id = the id of the stage of your workflow in tblContentReviewStage. This then allowed me to delete the workflow entirely in application builder.

A: Archer v6.x solution:
You can terminate existing workflow jobs in Archer from Administration -> Advanced Workflow -> Job Troubleshooting. There you can sort/filter and identify the workflow jobs that apply to the application you work on. You can select all that apply and press "Delete" button on the keyboard to bulk delete.
This should delete workflow jobs, but leave application records in place. After that you should be able to deactivate advanced workflow in your application.
Archer v5.x recommendations:
RSA recommend not to use workflow functionality in Archer v5.x due to various reasons (not flexible, not well documented, records get stuck and so on). This is why in v6 it has been replaced with Advanced Workflow running on a new engine on the back end.
I would do the following if you want to delete the workflow while the records are stuck there:

*

*Identify all fields in the application that are created and used by the workflow.

*Using SQL find these fields in the table "tblFieldDef" using GUIDs and   set the following flags to FALSE (or 0) if available: system, aso, locked

*After you set these flags to 0, you will be able to delete these fields using the application builder, so delete them.

*After you deleted the fields that drive the workflow try to delete the workflow itself.

I hope this works for you.
Note:[1] Back up your application by generating a package and saving it locally before you delete any workflow related fields.This should be tested first in non-production environment.[2] Test this in non-production environment. I have not tested this approach myself.
Good luck!


text:
Q: C# lambda in interface implementation I have read some about lambda.
But I have problems with the code below, Who can explain to me?
public class FakeProductRepository : IProductRepository
{
    public IEnumerable<Product> Products => new List<Product>
    {
        new Product { Name = "Football", Price = 25 },
        new Product { Name = "Surf board", Price = 179 },
        new Product { Name = "Running shoes", Price = 95 }
    };
}

how public IEnumerable<Product> Products => new List<Product> work??
Why when I use "=" instead of "=>" error occurs?:

Error CS0535  'FakeProductRepository' does not implement interface
  member 'IProductRepository.Products'


text:
Q: Area 51 feature request: method for high rep users to merge proposals There are a lot of very similar or duplicate proposals on Area 51 and it is bad if a proposal falters because half the people are following "US Civil War History" and the other half are following "US History". There should be some method of combing the two proposals.

A: It has to first be determined if a proposal is too broad or too narrow, and I would think that the final deciders of that would be the Team.

A: That would have a big side effect: high rep users would be able to post more that 5 example questions in 1 proposal:

*

*you ask 5 example questions in A

*you create proposal B

*you ask 5 example questions in B

*you merge B with A

Exept for that, merging the proposals give no benefit. You can as well reask your questions in the proposal you finds better and vote to close the second as duplicate.

A: I'd like to see something like implemented the same way duplicate questions are handled on the current sites where high rep users can "vote to close" and if enough people vote the proposal is closed with a link to the other one.

A: I agree.  One of the great benefits of StackOverflow is being exposed to things outside my specific interest.  For instance, I may only be interested in C++, but I'm bound to learn about Haskell in the process of using the site.  By having proposals that are subfields of subfields of subfields, we are losing some of the natural interdisciplinary mingling that could be really beneficial to these communities.
IMHO, we now have proposals with a fair amount of overlap that could be merged into a really great site:

*

*Artificial Intelligence

*Machine Learning

*NLP
These also have a lot of overlap with the Statistical Analysis proposal, although they have slightly more of a computer science focus than mathematics.

A: Here is the official response

I look at proposals and often feel as you do: "ugh, this is just a subset of [other proposal]." So, what do you do? How do you know the 2nd proposal isn't the better option? There's nothing inherently correct about being first. So, I leave it and watch. A proposal is not a site.

...

But there will be a time where two competing proposals have such a groundswell of support that both have sufficient momentum to sail through. That is the time to look closely at the two proposals. Are they different enough to justify separate sites? Or is the demand so high that, even after accidentally splitting the audience, each side still has sufficient support. In those cases, we'll have to step in and merge the proposals for their own good.


text:
Q: Publish data from a LAN webapp to a public site I have a struts 2 webapp. IT works very well and currently is only accessible to the office LAN. The client would like to be able to publish some of the data in the database to a public website. I would like to hear some ideas on how to do this.
My setup is tomcat 6 and using MYSQL as the DB.
I was thinking of creating a php website and having an almost duplicate DB on the public webserver. Perhaps I could create an XML string and fire it at the public site. Which would then have a php page parse the XML and put it in the public DB.
Any ideas on how to go about this ?


text:
Q: SWT WizardDialog not showing in TaskBar I am creating a WizardDialog as follows in a command line application
final Shell shell = new Shell(display);
Wizard wiz = new ImportWizard();
WizardDialog dialog = new WizardDialog(shell, wiz);
dialog.create();
dialog.open();

The wizard dialog does show. But it does not show up in Taskbar.
I also tried
shell.setVisible(true);
dialog.open();

This got the Shell to show up in the taskbar, but the shell window was visible behind the wizard.
How I can resolve this?

A: I was able to solve this using the following snippet
Wizard wiz = new ImportWizard();
WizardDialog dialog = new WizardDialog(null, wiz);
dialog.create();
dialog.open();

By passing null as Shell in the WizardDialog constructor.

A: I might assume, that the reason for such behavior is that WizardDialog class has only constructor to provide Shell, which in the end (in Dialog class) uses SameShellProvider as a shell provider. You need to inherit from something, where you can pass your own IShellProvider, for instance TrayDialog (or some other suitable class).


text:
Q: Git: get specific revision from remote server I'm setting up a test-architecture. In this system a VM has to test a specific revision of the code. The VM is completely clean, and does not have a local (updatable) version of the repo. The code is being hosted on an on-site git server, over ssh with a user named git. I have full control over both machines.
The easy solution is:
git clone --no-checkout git@gitserver:reponame.git
git checkout 8e8fdea8f8367f4a179d2faddbaadba495d6bc12

This works, but does too much: It transfers the full history over the network, something I want to avoid if at all possible.
It seems to me from the documentation that git clone can take a --branch option, but this doesn't allow me to specify a particular revision. If it would, this in combination with --depth 1 would work for me.
The alternative is to use git archive --remote. I understand the security implications of allowing this to get arbitrary revisions, and that is not a problem in this case, so I run
git config --global --bool --add uploadArchive.allowUnreachable 1

on the git server as the git user.
Now on the shell of the git user, I can do
git archive --format tar.gz --remote reponame.git 8e8fdea8f8367f4a179d2faddbaadba495d6bc12

Also, from my VM I can run
git archive --format tar.gz --remote git@gitserver:reponame.git master

However not working is:
git archive --format tar.gz --remote git@gitserver:reponame.git 8e8fdea8f8367f4a179d2faddbaadba495d6bc12

remote: fatal: no such ref: 8e8fdea8f8367f4a179d2faddbaadba495d6bc12
remote: git upload-archive: archiver died with error
fatal: sent error to the client: git upload-archive: archiver died with error

And yes, I'm pointing to the same repo, that revision definitely is in the repo, it will just not work with revision number. One thing that may be the case is that if the commands are executed over ssh, the default ~/.gitconfig file is not being read, although I could not find any information on this.
Currently I'm using bash as shell for the git user. It will work in the future with a restricted shell, but to show the basic problem, I wanted to use a normal shell.
I'm interested in both general remarks in how I should be getting a single revision to a clean machine, and a solution to the particular problem of not being able to use git archive with a revision.

EDIT: torek gave me some ideas about versions (I run on OSX, with git 1.8.5.2 stock, and 2.0.1 installed through brew), and I made a small wrapper script around git-upload-archive to figure out what was going on. The wrapper script:
/usr/local/bin/git --version > /tmp/version
tee /tmp/stdin | /usr/local/bin/git-upload-archive "$1" | tee /tmp/stdout

and calling the git-archive with the --exec option to run this script.
The version written is 2.0.1. The same problem persists however... From locally I can call git-archive with -remote and sha1 iff uploadarchive.allowunreachable is set, remotely I can't. Interestingly the request (in /tmp/stdin) is exactly the same in both cases, the reply is different. As far as I can see, this is because git-upload-archive is not picking up the correct config if started over ssh; this can be shown by using a local config in the repo, in which case it does work (my remark in the comments that this didn't work was because I was indeed picking up /usr/bin/git-upload-archive; the old version that doesn't allow this config flag).
The problem can actually be solved by calling /usr/local/bin/git upload-archive instead of /usr/local/bin/git-upload-archive. This can even be supplied as argument to git-archive: --exec='/usr/local/bin/git-upload-archive' doesn't work, --exec='/usr/local/bin/git upload-archive' does.
So problem works now. I would still be interested (from an academic point of view) in why git-upload-archive doesn't pick up the config. Possibly this is a bug that should be reported to the git project.

A: Just in case someone else runs into this issue: 90% of the answer is defined in the question under the EDIT part. The last 10% is probably not worth really diving into. The important points I repeat here:

*

*Take care that on OSX Mevericks the default GIT version is <2.0, and therefore doesn't support the uploadarchive.allowunreachable tag. When accessing git over SSH, it may select a different version depending on whether you start an interactive SSH session or not (your path may be different).

*git-upload-archive doesn't check for the uploadarchive.allowunreachable flag in the global git config. This seems to be a bug in GIT. The solution is to not use git-upload-archive, but git upload-archive (i.e. use the git script, with upload-archive as first argument). One way to do this is to supply --exec='/usr/local/bin/git upload-archive' to the git archive call.


text:
Q: Adding % sign to Y-Axis Labels in Bar Chart AChartEngine I am working on an android app and using AChartEngine for Charting. The Bar Chart is drawn on the basis of the dynamic data coming from a server.
Th Y-Axis labels are set to be shown from 0 to 100 and no of labels are 11 s it shows
0..10..20..30..40..60..70..80..90..100 as Y-Axis Labels. Is it possible to set custom Y-Axis labels such that it adds '%' sign after the Y-Axis title value so that it shows,
0%..10%..20%..30%..40%..60%..70%..80%..90%..100% as Y-Axis label values.
How to do it??

A: In order to set custom labels on the Y axis, you just need to use the following method:
mRenderer.addYTextLabel(10, "10%");
mRenderer.addYTextLabel(20, "20%");
...

Also, if you want to hide the default labels, do this:
mRenderer.setYLabels(0);

A: All what you need to do is: Enjoy ;)
renderer.addXTextLabel(0, "0");
    renderer.addYTextLabel(10, "10%");
    renderer.addYTextLabel(20, "20%");
    renderer.addYTextLabel(30, "30%");
    renderer.addYTextLabel(40, "40%");
    renderer.addYTextLabel(50, "50%");
    renderer.addYTextLabel(60, "60%");
    renderer.addYTextLabel(70, "70%");
    renderer.addYTextLabel(80, "80%");
    renderer.addYTextLabel(90, "90%");
    renderer.addYTextLabel(100, "100%");

    renderer.setYLabels(0);

A: I haven't actually done a lot with AChartEngine, but a quick glance at the source code suggests you could extend BarChart to accomplish what you're after.
Have a look at the getLabel(double label) method located in AbstractChart (BarChart extends XYChart, which on its turn extends AbstractChart).
 /**
   * Makes sure the fraction digit is not displayed, if not needed.
   *
   * @param label the input label value
   * @return the label without the useless fraction digit
   */
  protected String getLabel(double label) {
    String text = "";
    if (label == Math.round(label)) {
      text = Math.round(label) + "";
    } else {
      text = label + "";
    }
    return text;
  }

I would start with something naive to see how that works out; e.g. simply append "%" on the result of above:
@Override protected String getLabel(double label) {
    return super.getLabel(label) + "%";
}

Only thing I'm not too sure about is whether the same method is used to generate labels for the X-axis. If that's the case, you'll probably need to do something slightly smarter to enable it just for the axis you're interested in.


text:
Q: Multiple levels of cascading persists in Ebean I have a model class which defines a list of children that are models of the same class. Persisting a new object with some initial children works fine, but when I have two or more levels of children Ebean does not seem to be able to handle it well. This seemed unexpected so I'm worried I made a mistake. At the same time I couldn't find any examples or mentions about multiple level persist cascades so my questions are:
Is there an error in my code, Is this even a supported feature or did I find a bug?
My model class:
@Entity
public class TestEntity extends Model {
    @Id
    private int id;
    private String text;
    @ManyToOne
    private TestEntity parentEntity;
    @OneToMany(cascade = CascadeType.ALL)
    private List<TestEntity> childEntities;
...
}

My program:

TestEntity grandparent = new TestEntity();
grandparent.setText("grandparent");
TestEntity parent = new TestEntity();
parent.setText("parent");
TestEntity child = new TestEntity();
child.setText("child");
grandparent.setChildEntities(Collections.singletonList(parent));
parent.setChildEntities(Collections.singletonList(child));
grandparent.save();

I added logging for the sql statements and it is evident that the third insert didn't get the correct value for parent_entity_id. That row fails due to 0 not being a valid foreign key and the batch is reverted.
insert into test_entity (text, parent_entity_id) values ('grandparent',null);
insert into test_entity (text, parent_entity_id) values ('parent',1);
insert into test_entity (text, parent_entity_id) values ('child',0);

I'm using Play framework 2.7.3 with the ebean plugin version 5.0.2 and Ebean version 11.39

A: This is indeed a supported feature and the code snippet above is expected to persist all three entities.
There was a unit test added to verify that this is working correctly in the latest version of ebean.
In ebean 11.39 which is currently the latest supported by play framework the test fails. An easy workaround when using that version is to use Long instead of primitive int as ID for the models.
While not an answer to this specific question, it is good to be aware that these same symptoms also appear if the collections are set without using setters enhanced by ebean. I had some trouble using public fields and play enhancer  .


text:
Q: Anaconda Docker + Tensorflow installation = Shell problem I'm trying to create an image based on the official anaconda image with tensorflow so I can run jupyter and import tensorflow from it. I've tried several permutation of the procedure
https://docs.anaconda.com/anaconda/user-guide/tasks/tensorflow/
https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/install.html
https://github.com/conda/conda/issues/7980
But I always and up with this problem with the activation of the tensorflow environment.
My Dockerfile
FROM continuumio/anaconda3
RUN apt update
RUN apt -y upgrade
RUN apt -y install python3-dev python3-pip
RUN pip3 install -U virtualenv
RUN pip install --upgrade pip
RUN pip install pillow
RUN conda update -n base -c defaults conda
RUN conda create -n tf tensorflow pip python=3.6

Running command
source ./settings.sh
docker stop mdsdev
docker rm mdsdev
docker run -t -p 8888:8888 \
       --name mdsdev \
       -v "$NOTEBOOKS_PATH_LOCAL":"$NOTEBOOKS_PATH" \
       continuumio/anaconda3 \
       /bin/bash -c \
       "
       /opt/conda/bin/conda init bash && \
       /opt/conda/bin/conda activate tf && \
       /opt/conda/bin/conda install jupyter -y --quiet && \
       /opt/conda/bin/jupyter notebook --notebook-dir=$NOTEBOOKS_PATH --ip='0.0.0.0' --port=8888 --no-browser --allow-root"

Running output
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.


text:
Q: How to Implement Facebook Oauth with Zend? I want to Implement Facebook Oauth with Zend in my site.
My requirement is ,"Use Facebook for authentication and authorization when user login using Facebook in site".
Kindly provide some example link/tutorial.

A: some nice examples here http://socialdevelopers.net/


text:
Q: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]' Preciso gerar uma agenda de um certo periodo, mas está dando esse erro.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 '(day),data_agenda(month),data_agenda(year)) VALUES('19:00:00','31','12','2016')' at line 1

$dataInicio = '2016-01-01';
                $intervalo = 60;

                do {
                    list( $ano, $mes, $dia ) = explode('-', $dataInicio);
                    $inicio = '07:00:00';
                    $final = '19:00:00';
                    do {
                        list($hora, $minuto, $segundo ) = explode(':', $inicio);
                        $sql = "INSERT INTO agenda (hora_agenda,data_agenda(day),data_agenda(month),data_agenda(year)) VALUES('$inicio','$dia','$mes','$ano')";
                        $inicio = date("H:i:s", mktime($hora, $minuto + $intervalo, $segundo, $mes, $dia, $ano));
                    } while ($inicio <= $final);
                    $dataInicio = date('Y-m-d', mktime(0, 0, 0, $mes, $dia + 1, $ano));
                } while (date('Y') == date('Y', strtotime($dataInicio)));

                $dados = connection::exec($sql);

A: day(), month() e year() são funcões para extrair pedaços especificos de uma data e sua chamada no insert está 'invertida' no lugar de data_agenda(day) o certo seria day(data_agenda), porem você grava 3 valores diferentes no mesmo campo
O minimo suficiente para funcionar:
INSERT INTO agenda (hora_agenda,data_agenda, data_agenda,data_agenda)
            VALUES('$inicio','$dia','$mes','$ano')

Acredito que a sua intenção seja(gravar 3 valores em 3 campos diferentes):
INSERT INTO agenda (hora_agenda, dia_agenda, mes_agenda, ano_agenda)
            VALUES('$inicio','$dia','$mes','$ano')

É importante utilizar prepared statements para evitar sql injections e simplificar um pouco a string removendo as aspas simples nos valores.
Leitura recomendada:
Usar PDO é a maneira mais segura de se conectar a um BD com PHP?


text:
Q: How can I monitor the Exchange 2003 Event Service from my application? We had our server guys set up something on Exchange so that for a particular email address, any attachments sent to it will be dumped to a location on the file server.
The Exchange Event Service controls this behaviour, but it seems that this particular service fails fairly often. I dont know why - I dont have access to the Exchange server and it is run by a team in a different country.
Is it possible to monitor this exchange service programatically so I can warn the users if it goes down? I know that the 'right' solution is to have this handled by the Exchange team, but because of the timezone differences (and their massive workload) I really need to handle it from my end.
Could you do something like this with WebDav?

A: You could use the following powerShell script:
# Getting status of Exchange Services and look for anything that's "stopped"
$ServiceStatus = get-service MSExch* | where-object {$_.Status -eq "stopped"}

# Convert Result to String
$ServiceStatusText = $ServiceStatus | fl | Out-String

# If $ServiceStatus <> $null then send notification
If ($ServiceStatus -ne $null)
 {
 ###Exchange Server Values
 $FromAddress = "Exchange-Alert@YOUR_DOMAIN.local"
 $ToAddress = "your_address@YOUR_DOMAIN.com"
 $MessageSubject = "CRITICAL: An exchange service is has stopped"
 $MessageBody = "One or more Exchange services has stopped running or crashed. Please check the server ASAP for possible issues`n"
 $MessageBody = $MessageBody + $ServiceStatusText

 $SendingServer = "msexch02.pnlab.local"

 ###Create the mail message and add the statistics text file as an attachment
 $SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody

 ###Send the message
 $SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
 $SMTPClient.Send($SMTPMessage)
}

# Else don't do anything and exit
Else
  {
  $null
  }


text:
Q: AppShell Tabbar icons do not change color on iOS I have a .net maui application with AppShell that defines a tabbar with this code:
<TabBar>
    <Tab Title="{x:Static resources:Strings.HomeTitle}">
        <Tab.Icon>
            <FontImageSource FontFamily="MaterialIconsRound" Glyph="home" />
        </Tab.Icon>
        <ShellContent>
            <dashboard:DashboardPage />
        </ShellContent>
    </Tab>

    <Tab Title="{x:Static resources:Strings.StatisticsTitle}">
        <Tab.Icon>
            <FontImageSource FontFamily="MaterialIconsRound" Glyph="donut_small" />
        </Tab.Icon>
        <ShellContent Title="{x:Static resources:Strings.StatisticsTitle}">
            <statistics:StatisticSelectorPage />
        </ShellContent>
    </Tab>

    <Tab Title="{x:Static resources:Strings.MoreTitle}">
        <Tab.Icon>
            <FontImageSource FontFamily="MaterialIconsRound" Glyph="more_horiz" />
        </Tab.Icon>
        <ShellContent>
            <overflowMenu:OverflowMenuPage />
        </ShellContent>
    </Tab>
</TabBar>

On Android the icons do change correctly the color depending on the device theme or when they are selected. On iOS only the text changes.

Is that a bug or do I have to set a specific style for that?

A: There is a known issue about this problem. And this issue has been moved to the Backlog milestone.
You can follow it up here: https://github.com/dotnet/maui/issues/8244 .
Thanks for your support and feedback for maui.


text:
Q: Access 2010: The Oracle client and networking components were not found I've installed these Oracle client and ODAC files required for "Microsoft ODBC for Oracle":
ODAC112021Xcopy_32bit
win32_11gR1_client

But alas it will not work!
I'm on Windows 7, using Access 2010.
The PATH variable is set correctly:

C:\product\11.1.0\client_1;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Symantec\pcAnywhere\;C:\Program Files\Enterprise
  Vault\EVClient\;C:\Program Files\Microsoft Windows Performance
  Toolkit\;C:\Program Files\TortoiseSVN\bin;C:\Program
  Files\QuickTime\QTSystem\

Am I still missing something? Did I install the wrong files? It could be possible - the Oracle website is a giant mess.

A: When you install oracle client you need more than PATH environment var. You need an environment var called TNS_ADMIN which should point to the folder which has tnsnames.ora file. Inside that file you must have defined your database connections. It has this structure, I'll put an example:
<addressname> =
 (DESCRIPTION =
   (ADDRESS_LIST =
     (ADDRESS = (PROTOCOL = TCP)(Host = <hostname>)(Port = <port>))
   )
     (CONNECT_DATA =
   (SERVICE_NAME = <service_name>)
 )
)

Is a good practice to set too the NLS_LANG environment var too. Without it, maybe you could have some problems related to special chars depending of your database enconding.


text:
Q: Pass different functions with different method signatures to a function as a parameter in kotlin I am working on an android application using kotlin as my primary language. I needed to ask some runtime permissions for some parts of the app. So instead of writing similar boilerplate code to ask for the permissions I decided to to write a separate static function that checks for the permission, and run a method. Here is the static function
fun permissionExecution(childFragment: Fragment, permission: String, expression: ????) {

    Dexter.withActivity(childFragment.requireActivity())
        .withPermission(permission)
        .withListener(object : PermissionListener {
            override fun onPermissionGranted(response: PermissionGrantedResponse?) {
                expression()
            }

            override fun onPermissionRationaleShouldBeShown(
                permission: PermissionRequest?,
                token: PermissionToken
            ) {
                token.continuePermissionRequest()
            }

            override fun onPermissionDenied(response: PermissionDeniedResponse) {
                if(response.isPermanentlyDenied) {
                    openSettings(childFragment)
                }
            }

        }).check()
}

This code works perfectly when I passed in methods with no arguments. But I have some situations where I will like to pass in methods with different arguments types.

*

*calling the method like this permissionExecution(childfragment, permission, foo(string))

*calling the same method like this permissionExecution(childfrgment, permission, bas(string, Int))
what class type can I use for the espression argument in the permissionExecution() method

A: It doesn't make sense to include the function parameters in the definition of the lambda arument. You already have everything you need to call these other functions:
permissionExecution(myFragment, Manifest.permission.RECORD_AUDIO) {
    foo(myString)
}

permissionExecution(myFragment, Manifest.permission.CAMERA) {
    bar(myString, myInt)
}

If you need the PermissionGrantedResponse to determine what these parameters are, you can define that as the function input:
fun permissionExecution(childFragment: Fragment, permission: String, expression: (PermissionGrantedResponse) -> Unit) {

    Dexter.withActivity(childFragment.requireActivity())
        .withPermission(permission)
        .withListener(object : PermissionListener {
            override fun onPermissionGranted(response: PermissionGrantedResponse) {
                expression(response)
            }
    //...
}

//...

permissionExecution(myFragment, Manifest.permission.RECORD_AUDIO) { response ->
    foo(response.permissionName)
}

A: If I understand correctly, you have implemented a common static func that checks permission and pass some lambda to it that will be invoked when permission is granted. I do not understand why you these lambdas need some argument parameters. Is the below implementation what you desire?
class CameraFragment {

  fun onCreateView() {
    permissionExecution(childFragment = arg1, permission = "perm", expression = {
      // open camera
    })
  }
}

class LocationActivity {
  fun onCreate() {
    permissionExecution(childFragment = arg1, permission = "perm", expression = {
      fetchLocation()
    })
  }

  fun fetchLocation() {
    // get location, do stuff
  }
}

A: here is a not so elegant solution. I create a wrapper class with a single method interface like this
class Permissions(val childFragment: Fragment, private val permission: String, val runExpression: RunExpression) {
interface RunExpression{
    fun expression()
}

fun permissionExecution() {

    Dexter.withActivity(childFragment.requireActivity())
        .withPermission(permission)
        .withListener(object : PermissionListener {
            override fun onPermissionGranted(response: PermissionGrantedResponse?) {
                runExpression.expression()
            }

            override fun onPermissionRationaleShouldBeShown(
                permission: PermissionRequest?,
                token: PermissionToken
            ) {
                token.continuePermissionRequest()
            }

            override fun onPermissionDenied(response: PermissionDeniedResponse) {
                if(response.isPermanentlyDenied) {
                    openSettings(childFragment)
                }
            }

        }).check()
}

}
then call the class like this each time I need the permission
1.
Permissions(this, Manifest.permission.READ_CONTACTS, object : Permissions.RunExpression {
                override fun expression() {
                    startActivityForResult(intent, PICK_CONTACT)
                }
            }).permissionExecution()

2.
Permissions(this, Manifest.permission.READ_CONTACTS, object : Permissions.RunExpression {
                override fun expression() {
                    writeFileToLocation(file, locationPath)
                }
            }).permissionExecution()

A: a better way i find by adapting the solution here is firstly, create an interface like this
interface RunExpression{
fun expression()}

then use the interface in the function signature
fun permissionExecution(childFragment: Fragment, permission : String, runExpression: RunExpression) {

Dexter.withActivity(childFragment.requireActivity())
    .withPermission(permission)
    .withListener(object : PermissionListener {
        override fun onPermissionGranted(response: PermissionGrantedResponse?) {
            runExpression.expression()
        }

        override fun onPermissionRationaleShouldBeShown(
            permission: PermissionRequest?,
            token: PermissionToken
        ) {
            token.continuePermissionRequest()
        }

        override fun onPermissionDenied(response: PermissionDeniedResponse) {
            if(response.isPermanentlyDenied) {
                openSettings(childFragment)
            }
        }

    }).check()}

then wherever I want to call the function, I save the anonymous object that implement the interface into a variable
val startMyActivity = object : RunExpression {
            override fun expression() {
                startActivityForResult(intent, PICK_CONTACT)
            }
        }

then call the function with the variable
permissionExecution(this, Manifest.permission.READ_CONTACTS, startMyActivity)


text:
Q: ITK installation and sample program I am new to ITK and I did the following step to install ITK and use it to programme in VS2010

*

*Downloaded ITK 4.3.1 and build it with CMAKE

*The build was successful and I had a lib->Debug folder containing the libs.

*Added the bin folder path to environmental vairable path.

Following is my simple code...
#include <iostream>
#include <Core/Common/include/itkImage.h>

using namespace itk;
using namespace std;

int main()
{
    return 0;
}

the above code returns
Cannot open include file: 'itkConfigure.h'

I tried searching for that header but no luck. However in C:\InsightToolkit-4.3.1\Modules\Core\Common\src I found itkConfigure.h.in file. I am really clueless about how to go about this .in file. Any help is most welcome..

A: The easiest way to set up your project is to use CMake again.  Try creating a project with just a CMakeLists.txt and main.cpp.  The CMakeLists.txt should have something like:
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(ItkTest)

find_package(ITK REQUIRED)
include(${ITK_USE_FILE})

add_executable(MyTest main.cpp)
target_link_libraries(MyTest ITKCommon)

So say you create these 2 files in a dir called ItkProject, then from a Visual Studio Command Prompt just do:
cd <path to ItkProject>
mkdir build
cd build
cmake .. -DITK_DIR="<path to build dir of ITK>"

The <path to build dir of ITK> is where you ran CMake from to configure the ITK project.  It will contain the ITK.sln file, but critically it should also contain a file called ITKConfig.cmake.  It is this file which is searched for in the cmake command find_package(ITK REQUIRED) - if CMake can't find it the configuring will fail.
Once that's been found, it sets a bunch of CMake variables which you can then use in your own CMakeLists.txt, including ITK_USE_FILE.
When you then invoke include(${ITK_USE_FILE}), this goes on to set up things like your includes paths, library search paths, and compiler flags.  The path <path to ItkProject>/Core/Common/include will be added to the includes dirs, so in your main.cpp, you just need to do:
#include <Core/Common/include/itkImage.h>
#include "itkImage.h"
Anyway, the end result after running CMake should be solution file <path to ItkProject>\build\ItkTest.sln which is set up ready to use ITK.

A: I checked \ItkConfig.cmake and paths defined there should match physical paths, this is the case if ITK build has been untouched (directory wasn't renamed).
# The ITK source tree.
# For backward compatibility issues we still need to define this variable, although
# it is highly probable that it will cause more harm than being useful.
# Use ITK_INCLUDE_DIRS instead, since ITK_SOURCE_DIR may point to non-existent directory
IF(NOT ITK_LEGACY_REMOVE)
  SET(ITK_SOURCE_DIR "C:/ITK320")
ENDIF(NOT ITK_LEGACY_REMOVE)

# The ITK include file directories.
SET(ITK_INCLUDE_DIRS "C:/ITK320-build;C:/ITK320/Code/Algorithms;C:/ITK320/Code/BasicFilters;C:/ITK320/Code/Common;C:/ITK320/Code/Numerics;C:/ITK320/Code/IO;C:/ITK320/Code/Numerics/FEM;C:/ITK320/Code/Numerics/NeuralNetworks;C:/ITK320/Code/SpatialObject;C:/ITK320/Utilities/MetaIO;C:/ITK320/Utilities/NrrdIO;C:/ITK320-build/Utilities/NrrdIO;C:/ITK320/Utilities/DICOMParser;C:/ITK320-build/Utilities/DICOMParser;C:/ITK320-build/Utilities/expat;C:/ITK320/Utilities/expat;C:/ITK320/Utilities/nifti/niftilib;C:/ITK320/Utilities/nifti/znzlib;C:/ITK320/Utilities/itkExtHdrs;C:/ITK320-build/Utilities;C:/ITK320/Utilities;C:/ITK320/Code/Numerics/Statistics;C:/ITK320/Utilities/vxl/v3p/netlib;C:/ITK320/Utilities/vxl/vcl;C:/ITK320/Utilities/vxl/core;C:/ITK320-build/Utilities/vxl/v3p/netlib;C:/ITK320-build/Utilities/vxl/vcl;C:/ITK320-build/Utilities/vxl/core;C:/ITK320-build/Utilities/gdcm;C:/ITK320/Utilities/gdcm/src")

# The ITK library directories.
SET(ITK_LIBRARY_DIRS "C:/ITK320-build/bin")


text:
Q: 2dsphere index on nested document not working I wanted to save multiple locations in the below schema and run geolocation queries.
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Offer Schema
 */
 var LocSchema = new Schema({
  'type': {
      type: String,
      required: true,
      enum: ['Point', 'LineString', 'Polygon'],
      default: 'Point'
    },
    coordinates: [Number]
 });
var LocationSchema = new Schema({
    address:{type:String},
    loc:[LocSchema]
});
var OfferSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Offer name',
        trim: true
    },
    description:
    {
        type:String,
        default:'',
        required:'Please fill offer description',
        trim: true
    },
    shortDesc:
    {
        type:String,
        default:'',
        trim: true
    },
    image:
    {
        type:String,
        default:'',
        required:'Please upload image'
    },
    locations:[LocationSchema],
    created: {
        type: Date,
        default: Date.now
    },
    startDate: {
        type: Date,
        default: Date.now
    },
    endDate: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    category:
    {
     type: Schema.ObjectId,
      ref :'Category'
    }

});
OfferSchema.index({'locations.loc': '2dsphere'});
mongoose.model('Offer', OfferSchema);

When I run save on the object I get "something went wrong" error, however I am able to save the document if I delete the index.
Can someone tell me if I am doing something wrong.


text:
Q: delete row when delete buttton is pressed from table in reactjs Everything is working fine.
The problem is when I press the delete button, it deletes but not immediately from table. It deletes when I reload the page. I replace the student array in localStorage when I press delete. Your help will be appreciated. Thank you in advance.
const history = useHistory();
let student = JSON.parse(localStorage.getItem('student'))

This is the function for the deletion of an item
const deleteStudent = (event)=>{
  let id = event.currentTarget.id
  let students = student.map(student=>Number(student.id))
  let index = students.indexOf(Number(id))
  student.splice(index,1)
  localStorage.setItem('student',JSON.stringify(student))
}

A: You can use useEffect() hook for re rendering the component. You can set the dependency when it should render. I am not sure about the use case for local storage here but you can use useState() hook to update the data and render the component or you can use the useEffect() hook by adding the dependencies and render the component.
Link for the useEffect hook - https://reactjs.org/docs/hooks-effect.html
Link for the useState hook - https://reactjs.org/docs/hooks-state.html
  //declare this in the start of the component
  const studentsData = JSON.parse(localStorage.getItem('student'))
  const [students, setStudents] = useState(studentsData);

  const deleteStudent = (event)=>{
     let id = event.currentTarget.id
     let studentIds = students.map(student=>Number(student.id))
     let index = studentIds.indexOf(Number(id))
     students.splice(index,1)
     localStorage.setItem('student',JSON.stringify(student))
  }

  useEffect(() => {
     setStudents(JSON.parse(localStorage.getItem('student')))
  }, [localStorage.getItem('student')]);


text:
Q: Can I use easy connect library with the Roving Network XV Wifi module? I am trying to create a mqtt connection over WIFI using the mbed LPC 1768 dev board and the Roving Networks RN-XV wifi module. I can create a mqtt connection over ethernet using the HelloMQTT example. I have also created a wifi connect using the WiflyInterface. I would like to be able to create  the wifi connection using the easy-connect library or to make the WiflyInterface implement the NetworkInterface.
The current issue is that I cant add WiflyInterface to the mbed-os with getting a Socket redeclaration error.
Error: Invalid redeclaration of type name "Socket" (declared at /extras/mbed-os/mbed-os.lib/features/net/network-socket/Socket.h:28) in "WiflyInterface/Socket/Socket.h", Line: 25, Col: 8

A: The error message indicates that WiflyInterface's Socket class declaration conflicts with OS 5's Socket class declaration.
I believe WiflyInterface is an mbed OS 2 only library and cannot be added to mbed OS 5 (mbed-os.lib) which comes with its own networking libraries.
You can learn about OS 5's networking libraries here:
WiFiInterface:
https://os.mbed.com/docs/v5.9/reference/wi-fi.html
Network Socket: https://os.mbed.com/docs/v5.9/reference/network-socket.html


text:
Q: How to disable Keep alive in SpringBoot application in docker image We have a Web application with following technologies: Java, SpringBoot, Docker, Microservices, Jhipster.
The port number for the frontend container is 80.
I am trying to disable keep alive option for the frontend microservice because SSO Authentication Server requires this parameter set to be false.
I tried to create the front container with maven : mvn -Pqpm,no-liquibase -Dhttp.keepAlive=false clean verify jib:dockerBuild
I also tried to disable in pom.xml of the front container :
<http.keepAlive>false</http.keepAlive>
<https.keepAlive>false</https.keepAlive>

But the keep-alive option remains enabled when I send a http request :
Connecting to qwerty.xyz|10.10.219.200|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Date: Mon, 06 Apr 2020 21:14:50 GMT
  Server: Apache
  Last-Modified: Fri, 21 Oct 2016 08:42:15 GMT
  ETag: "4107-84-53f5c04e1c7c0"
  Accept-Ranges: bytes
  Content-Length: 132
  Cache-Control: max-age=0, no-store
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Content-Type: text/html
Length: 132 [text/html]
Saving to: `/dev/null'

     0K                                                       100% 15.7M=0s

2020-04-06 23:14:50 (15.7 MB/s) - `/dev/null' saved [132/132]

My Springboot config:
<!-- Dependency versions -->
<jhipster-dependencies.version>3.0.1</jhipster-dependencies.version>
<!-- The spring-boot version should match the one managed by
https://mvnrepository.com/artifact/io.github.jhipster/jhipster-dependencies/${jhipster-dependencies.version} -->
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>

Could you please help me to disable it ?

A: I finally found a solution. The way we did this was to implement a filter and add this filter to SecurityConfig.config method.
    KeepAliveFilter.java

    public class KeepAliveFilter implements Filter {
        public void init(final FilterConfig filterConfig) { }

        public void destroy() { }

        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            final HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Connection", "close");
            chain.doFilter(request, response);
        }
    }

    SecurityConfiguration.java

    private final KeepAliveFilter keepAliveFilter;

    public SecurityConfiguration(final KeepAliveFilter keepAliveFilter, ...)
    {
        this.keepAliveFilter = keepAliveFilter;
    ...
    // other property
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .addFilterBefore(keepAliveFilter, CsrfFilter.class)
            ;
    }

A: You can disable it in your spring application.properties file, for my case I'm using a yaml config file, so in my application.yml file I did:
server:
  undertow:
    always-set-keep-alive: false


text:
Q: Using outputs from other tf files in terraform Is there a way of using output values of a module that is located in another folder? Imagine the following environment:
tm-project/
├── lambda
│   └── vpctm-manager.js
├── networking
│   ├── init.tf
│   ├── terraform.tfvars
│   ├── variables.tf
│   └── vpc-tst.tf
├── prd
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
└── security
    └── init.tf

I want to create EC2 instances and place them in a subnet that is declared in networking folder. So, I was wondering if by any chance I could access the outputs of the module I used in networking/vpc-tst.tf as the inputs of my prd/instances.tf.
Thanks in advances.

A: You can use a outputs.tf file to define the outputs of a terraform module. Your output will have the variables name such as the content below.
output "vpc_id" {
  value = "${aws_vpc.default.id}"
}

These can then be referenced within your prd/instances.tf by referencing the resource name combined with the output name you defined in your file.
For example if you have a module named vpc which uses this module you could then use the output similar to below.
module "vpc" {
   ......
}

resource "aws_security_group" "my_sg" {
    vpc_id = module.vpc.vpc_id
}