Q: No JWT created from JSON Web Tokens using Spring Security I'm using spring security and JSON Web Tokens for email verification.
I noticed that there is no JWT created when I register a new employee.
I use email for login, not username. I don't know if that problem with the Userdetalis interface.
when I'm trying to login into Postman, I get this error.

My code :
EmployeeController :
@CrossOrigin(origins = {"http://localhost:3000"})
@Tag(name = "Employee", description = "Employee API")
@RestController
@RequestMapping(EmployeeController.BASE_URL)
public class EmployeeController {
    public static final String BASE_URL = "/api/v1/employees";
    private final EmployeeService employeeService;
    private final ConfirmationTokenService confirmationTokenService;

@Autowired
AuthenticationManager authenticationManager;

@Autowired
RoleRepository roleRepository;

@Autowired
PasswordEncoder encoder;

@Autowired
JwtUtils jwtUtils;

public EmployeeController(EmployeeService employeeService, ConfirmationTokenService confirmationTokenService) {
    this.employeeService = employeeService;
    this.confirmationTokenService = confirmationTokenService;
}

@GetMapping
@ResponseStatus(HttpStatus.OK)
public EmployeeListDTO getEmployeeList() {
    return employeeService.getAllEmployees();
}

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody EmployeeDTO loginRequest) {
    System.out.println("Hei");

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));

    System.out.println("Hei2");

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    System.out.println(jwt);

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List<String> roles = userDetails.getAuthorities().stream()
            .map(item -> item.getAuthority())
            .collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getEmail(),
            roles));
}

@GetMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public EmployeeDTO getEmployeeById(@PathVariable Long id) {
    return employeeService.getEmployeeById(id);
}

@PostMapping("/signup")
@ResponseStatus(HttpStatus.CREATED)
public EmployeeDTO createNewEmployee(@RequestBody EmployeeDTO employeeDTO) {
    return employeeService.createNewEmployee(employeeDTO);
}

@PutMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public EmployeeDTO updateEmployee(@PathVariable Long id, @RequestBody EmployeeDTO employeeDTO){
    return employeeService.saveEmployeeByDTO(id, employeeDTO);
}

@DeleteMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public void deleteEmployee(@PathVariable Long id){
    employeeService.deleteEmployeeDTO(id);
}

}
> package com.tietoevry.bookorabackend.security.jwt;
>
> import com.tietoevry.bookorabackend.services.UserDetailsServiceImpl;
> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import
> org.springframework.beans.factory.annotation.Autowired; import
> org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
> import
> org.springframework.security.core.context.SecurityContextHolder;
> import org.springframework.security.core.userdetails.UserDetails;
> import
> org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
> import org.springframework.util.StringUtils; import
> org.springframework.web.filter.OncePerRequestFilter;
>
> import javax.servlet.FilterChain; import
> javax.servlet.ServletException; import
> javax.servlet.http.HttpServletRequest; import
> javax.servlet.http.HttpServletResponse; import java.io.IOException;
>
>
> public class AuthTokenFilter extends OncePerRequestFilter {

@Autowired
private JwtUtils jwtUtils;

@Autowired
private UserDetailsServiceImpl userDetailsService;

private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

        throws ServletException, IOException {

    try {
        String jwt = parseJwt(request);

        if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
            String username = jwtUtils.getUserNameFromJwtToken(jwt);

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            System.out.println("No JWT yet");
        }
    } catch (Exception e) {
        logger.error("Cannot set user authentication: {}", e);
    }

    filterChain.doFilter(request, response);
}

private String parseJwt(HttpServletRequest request) {
    String headerAuth = request.getHeader("Authorization");

    if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer")) {
        return headerAuth.substring(7, headerAuth.length());
    }

    return null;
} }

import java.util.List;

public class JwtResponse {
    private String token;
    private String type = "Bearer";
    private Long id;
    private String email;
    private List<String> roles;

    public JwtResponse(String accessToken, Long id, String email, List<String> roles) {
        this.token = accessToken;
        this.id = id;
        this.email = email;
        this.roles = roles;
    }

    public String getAccessToken() {
        return token;
    }

    public void setAccessToken(String accessToken) {
        this.token = accessToken;
    }

    public String getTokenType() {
        return type;
    }

    public void setTokenType(String tokenType) {
        this.type = tokenType;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<String> getRoles() {
        return roles;
    }
}

//generate Token
@Component
public class JwtUtils {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    @Value("${bezkoder.app.jwtSecret}")
    private String jwtSecret;

    @Value("${bezkoder.app.jwtExpirationMs}")
    private int jwtExpirationMs;

    public String generateJwtToken(Authentication authentication) {

        UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();

        return Jwts.builder()
                .setSubject((userPrincipal.getEmail()))
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
    }

    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.error("Invalid JWT signature: {}", e.getMessage());
        } catch (MalformedJwtException e) {
            logger.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error("JWT token is expired: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims string is empty: {}", e.getMessage());
        }

        return false;
    }
}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/h2-console/**").permitAll();

        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/v1/employees/**").permitAll()
                .antMatchers("/api/test/**").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

and in intellj I get :


Q: Loading array file with other numbering format I am trying to load a file in which the numbers are in the following form:
  0.0000000D+00 -0.1145210D-16  0.1262408D-16
  0.1000000D+00 -0.4697286D-06  0.1055963D-06
  0.2000000D+00 -0.1877806D-05  0.4220493D-06
  0.3000000D+00 -0.4220824D-05  0.9482985D-06

I am trying the numpy.loadtext function, but apparently it's not in its recognized numbering format as I'm getting the following error:
ValueError: could not convert string to float: b'0.0000000D+00'
Any idea?
Thanks

A: You can use a converter with numpy.loadtxt that converts the value to a parsable float. In this case we trivially replace Dwith E;
import numpy as np

numconv = lambda x : str.replace(x.decode('utf-8'), 'D', 'E')
np.loadtxt('test.txt', converters={0:numconv, 1:numconv, 2:numconv}, dtype='double')

# array([[  0.00000000e+00,  -1.14521000e-17,   1.26240800e-17],
#        [  1.00000000e-01,  -4.69728600e-07,   1.05596300e-07],
#        [  2.00000000e-01,  -1.87780600e-06,   4.22049300e-07],
#        [  3.00000000e-01,  -4.22082400e-06,   9.48298500e-07]])


Q: If - Else on Pirates Un-resolved Could you someone show me how to create an if - else statements with two sets of R.drawable.images pirates?
I've tried, but I got an error code saying pirates is un-resolved.
Bitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);
This is what I have in the preferences:

xmlns:android="http://schemas.android.com/apk/res/android"
android:key="wallpaper_settings"
android:title="@string/wallpaper_settings" >  <!--must be the same callout from
values->strings-->

<ListPreference
    android:key="speed"
    android:title="@string/speed_title"
    android:entries="@array/timelist"
    android:entryValues="@array/actualtime"
    android:summary="@string/speed_summary" >
</ListPreference>

  <CheckBoxPreference
    android:key="checkbox"
    android:title="Nature Pictures"
    android:summary="For Nature Pictures Option"
    android:defaultValue="false" />

Main Activity:
     public class main_activity extends WallpaperService {

     public static final String SHARED_PREFS_NAME="settings_menu";

   @Override
  public void onCreate() {
    super.onCreate();
}

   @Override
public void onDestroy() {
    super.onDestroy();
}

   @Override
public Engine onCreateEngine() {
    return new wallpaperEngine();
}

class wallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener{

    private final Handler mhandler = new Handler();

    //defines variables

    private final Runnable drawrunnable = new Runnable()
    {
        public void run() {
            drawFrame();
        }
    };
    private int i = 0;
    private boolean mVisible;
    private SharedPreferences mPrefs;
    private boolean mcheckbox = false;
    public int mSpeed = 10;

         int[] pirates = {
            R.drawable.image_1,
            R.drawable.image_2,
            R.drawable.image_3,
            R.drawable.image_4

    };

       //For Nature Pictures
         int[] pirates = {
            R.drawable.image_a1,
            R.drawable.image_a2,
            R.drawable.image_a3,
            R.drawable.image_a4

    };

  .......
  ......

   Bitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);

        i++;

        if (i == 14) {
            i = 0;

Thank you very much

A: Seems like you are trying to create two arrays of int, holding different set of images. But you are using the same variable name pirates. I would suggest you define two different variables int[] pirates and int[] piratesNatural and then switch between those two arrays when you need one and the other.
Bitmap icon;
if(natural)
  icon = BitmapFactory.decodeResource(getResources(),piratesNatural[i]);
else
  icon = BitmapFactory.decodeResource(getResources(),pirates[i]);

A: you doing animation?
int frame=0;
int frametime=24;

Bitmap icon1 BitmapFactory.decodeResource(getResources(), R.drawable.image_1,);
Bitmap icon2 BitmapFactory.decodeResource(getResources(), R.drawable.image_2,);
Bitmap icon3 BitmapFactory.decodeResource(getResources(), R.drawable.image_3,);
Bitmap icon4 BitmapFactory.decodeResource(getResources(), R.drawable.image_4,);

//in update
frametime--;
if(frametime<=0){
frame++;
frametime=24;
}
if(frame>3){
frame=0;
}

//in onDraw

switch(frame){

case 0:
canvas.drawBitmap(icon1,x,y,null);
break;
case 1:
canvas.drawBitmap(icon2,x,y,null);
break;
case 2:
canvas.drawBitmap(icon3,x,y,null);
break;
case 3:
canvas.drawBitmap(icon4,x,y,null);
break;
default:
canvas.drawBitmap(icon1,x,y,null);
break;}


Q: Method Swizzling - How to assure methods are swizzled before they are called I'm method swizzling a third party applications creation of NSMenuItems with SIMBL, but 50/50 of the time the menu-items are created before my method swizzling is initialized.
What is a clean way to make sure my swizzling always comes first? I guess I could swizzle applicationDidFinishLaunching: and continue my swizzling there. But I'm afraid I'm going to run in to the same error there, where applicationDidFinishLaunching will be called before my actual swizzle is in place.
John

A: You'd want the swizzle to happen as soon as the libraries are loaded.  You can do that via +initialize, +load, or a constructor function.
@bbum's answer to this question has a bit more information, along with one of his blog posts on the caveats of using these special class methods.
(And I'm purposely not questioning the wisdom of what you're doing ;) )

A: You can use constructor functions like this:
__attribute__((constructor)) static void do_the_swizzles()
{
    // Do all your swizzling here.
}

From GCC documentation:

The constructor attribute causes the function to be called
  automatically before execution enters main().

Note: Although this is originally from GCC, it also works in LLVM.


Q: Multiple Timers counting down are not working properly | SwiftUI I have an auction app running. I need several timers counting down in the UI, these timers have different end Dates, and the end seconds can be updated when SignalR receives a new value.
I have implemented running timers in my current solution, but sometimes and suddenly, they start having delays between counting down a second.
The timers are inside these components called LotCard within the ForEach
ForEach($lotService.getLotListDto) { $item in
    LotCard(lotCardViewModel: $item.lotCardViewModel,
            lotDto: item,
            fnStartLotConnection: { value in lotService.initSingleLotCard(uID: value)})

}

This is the necessary code within these components:
//MARK: Timer
@State var timeRemaining = 9999
let timerLotCard = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

HStack(spacing: 3){
    Image(systemName: "stopwatch")
    if(lotCardViewModel.showTimer){
        Text("\(timeRemaining.toTimeString())")
            .font(.subheadline)
            .onReceive(timerLotCard){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1

                    if(self.timeRemaining <= 0){
                        self.timerLotCard.upstream.connect().cancel()
                    }
                }else{
                    self.timerLotCard.upstream.connect().cancel()
                }
            }
    }
}

I guess it's a problem with threads and using many timers simultaneously with the same Instance but I am not an experienced developer using SwiftUI/Swift.
This is how my interface looks like:

Thanks for your help.

A: I came up with this approach thanks to the comments in my question.
I hope it works and suits your problems.
First, I created a Published Timer, meaning every component will run the same Timer.
import Foundation
import Combine

class UIService : ObservableObject {

    static let shared = UIService()

    //MARK: Timer to be used for any interested party
    @Published var generalTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

}

Finally, I am using that Timer wherever I want to use it. In this case, I use it in every LotCard component.
struct LotCard: View {

//MARK: Observable Class
@EnvironmentObject var UISettings: UIService

//MARK: Time for the counting down
@State var timeRemaining = 9999

var body: some View {
    HStack{

        Text(timeRemaining.toTimeString())
            .onReceive(UISettings.generalTimer){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
    }
}
}


Q: Override a method and make it behave static I have an existing framework, which I can't change, it reads 2 properties

*

*ClassA=somepackage.AnImplementationOfInterfaceA

*ClassB=somepackage.AnImplementationOfInterfaceB
Which calls public methodA on a new ClassA(), public methodB on a new ClassB() in that order
I want to make a class C which implements interfaces A, B and provides hooks methodC1, methodC2 for class D to override (methodA & methodB contain a lot of boilerplate and complex to implement - methodC1 & methodC2 would encapsulate the business logic) . Then my properties would be

*

*ClassA=somepackage.classD

*ClassB=somepackage.classD
The problem is that the person who implements class D might be tempted to write something like:
class D extends class C
{
   private int foo; //must be non-static due to multi-threaded new Class D() calls going on
   int methodC1() {this.foo = read number from network}
   methodC2(int x) {y = this.foo;} //methodC2 is always called after methodC1

   //methodA, methodB implementation inherited from C
}

But this wouldn't work as expected since the framework would actually create a new object of class D each time before invoking methodA, methodB and thus can't rely on using the "this" reference.
Defining methodC1, methodC2 as static wouldn't work either because then the call to methodC1 is tied to the implementation in C, not the overriden one in D.
When really what ought to be written is:
class D extends class C
{
   int methodC1() {return number from network;}
   methodC2(int x) {y = x}  //here y is using the return value of methodC1

   //methodA, methodB implementation inherited from C
}

I would also like only methodC1, methodC2 to be overridable i.e. programmers working on D can't mess with methodA
The ideal design would have

*

*the properties refer to one class only

*methodC1, methodC2 to be in that class

Summary of challenges

*

*no this in methodC1, methodC2

*can't make methodC1, methodC2 static

*properies takes only a instantiable class

How do I design this framework? Is this even solvable? You can change the signature of methodC1, methodC2.

A: Composition! Establish an interface that you are okay with people extending.
This class would contain the logic for MethodD1 and D2, and for everything else just a simple call to the other methods in your currently existing class. People won't be able to modify the calls to change the underlying logic.

A: The static methods can not be overridden!
If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.


Q: Set counting javascript program to two decimal places Please see this code:

What it does is take a piece of html like this:

10

And it will count by 10 every second.  How do I make the following code work:

10.02

Basically, I want to have this program count by up to two decimal places.

A: Use parseFloat instead of parseInt. And toFixed(2) for limiting two decimal points.
setInterval(function() {
    var counters = document.getElementsByClassName("count");

    for (var i = 0; i < counters.length; i++) {
        counters[i].innerHTML = parseFloat(counters[i].innerHTML).toFixed(2) + parseFloat(counters[i].dataset.increment).toFixed(2);
    }
}, 1000);

A: JSFIDDLE
 You need to use parseFloat to covert string to float.
  and toFixed on float to truncate extra decimal. toFixed return string you need to use parseFloat again so that it became float addition not string concatenation.

var counters = document.getElementsByClassName("count");

    setInterval(function () {
        for(var i = 0 ; i < counters.length ; i++) {

            counters[i].innerHTML = (parseFloat(parseFloat(counters[i].innerHTML).toFixed(2)) + parseFloat(parseFloat(counters[i].dataset.increment).toFixed(2))).toFixed(2);
        }
    }, 1000);

10

10.02

A: Try wrapping addition within String() , .innerHTML , .dataset within Number() , Number() within expression () chained to .toFixed(2) ; set counters[i].innerHTML to result derived within String((Number(/* innerHTML */) + Number(/* dataset *)).toFixed(2))

var interval = setInterval(function() {
  var counters = document.getElementsByClassName("count");

  for (var i = 0; i < counters.length; i++) {
    counters[i].innerHTML = String((Number(counters[i].innerHTML)
                            + Number(counters[i].dataset.increment)).toFixed(2));

  }
}, 1000);

10.02


Q: How to get the fingers count in the InkCanvas? I am trying to zoom the InkCanvas when the finger counts greater than 1, but I can't get the finger count in the InkCanvas.Anyone Please help me how to get the finger count in InkCanvas.

A: I don't have touch screen to test but maybe this will work:
    int count;

    private void InkCanvas_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        count++;
    }

    private void InkCanvas_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        count--;
    }

If it doesn't help. Try to use PinterPressed and PointerReleased. You may grab point Id from event args and handle them.


Q: React Native init Project which ruby
outputs -> /Users/User/.rbenv/shims/ruby
ruby -v
outputs -> ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21]
which bundle
outputs -> /Users/User/.rbenv/shims/bundle
bundle -v
outputs -> Bundler version 2.1.4
but the problem is that npx react-native init MyProject
outputs -> ✖ Installing Bundler
error Bundler::RubyVersionMismatch: Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5

A: What's likely happening is that npx react-native init MyProject is sub-shelling into Bash where you do not have rbenv configured. When it tries to run ruby from Bash it looks in $PATH and finds the default macOS version of Ruby -- 2.6.10 -- and errors out.
This is discussed thoroughly in the react-native repo where there are many solutions, but what it boils down to is react-native init is not finding the right version of Ruby, for whatever reason. You can bypass that by completing the failing part of the init process yourself with:
cd MyProject
bundle install
cd ios && bundle exec pod install

The longer version of the solution is to configure rbenv for Bash as well, but this isn't necessary as you can likely use just the workaround above:
echo 'eval "$(~/.rbenv/bin/rbenv init - bash)"' >> ~/.bash_profile


Q: Assign  to specific characters within CSS style I am new to CSS and web development in general. Hopefully there is a way to accomplish what I am trying to do. What I am trying to do is simple to explain, but I need to give some background info first, sorry for the length of the post.
I have created a webpage that is in the Tibetan language. Tibetan does not have spaces between words, it only has a character called a "tsheg" (་ - U+0F0B) that is used to separate every syllable. It also has a mark called a "shey" (། - U+0F0D) that comes at the end of phrases and clauses and sentences. Although sometimes it is doubled, after a shey is generally a space before the next line of text. When typing in Tibetan this space is represented not as a normal space (U+0020) but instead U+00A0, however when it comes to browsers and HTML/coding in general these two seem to behave the same.
In any Tibetan writing, the ideal aesthetic is for full justification. Traditionally there would be slight spaces placed between the tsheg marks and the shey marks to achieve a perfectly flush left and right alignment. (The exception would be the last line of a text, or a paragraph in contemporary formatting, does not need to be justified). It is acceptable for lines to break mid-word or mid-sentence, but never mid syllable. So the last character on any line is going to be either a tsheg or a shey. It is also not acceptable to start a line with a shey. In the last few years this has been easy to achieve for desktop publishing using MS Word, using "Thai Justification." However that option is not available even in other Office products, never mind outside of the Office environment. Other work-arounds have been to add invisible width characters after every tsheg and shey, allowing for wrapping at any point.
Now comes the question and difficulty. I am using distributed justification, and that seems to be the best option. It does not break syllables up, which is important. But it only wants to break at those spaces after shey marks, and it breaks elsewhere when there is a long string of text without a space, but if there is a space then it breaks there, sometimes stretch one or two syllables across an entire line, which is obviously not ideal.
Now, when coding the HTML of the text I can use the same work-around that is used for desktop publishing pre "Thai justification," I can add a <wbr> after every single tsheg, and this will not be visible to the end user and should allow cleaner breaking. However, there are two problems with this. But inserting that many <wbr> characters I am essentially doubling, or close to doubling, my character count, which can make the page take twice as long to load, even if half of those characters are invisible. However, more important is that it disrupts search functionality. Although you may see the word that has the syllables "AB" for instance, if you tried searching for AB you wouldn't find it, because the HTML sees "AB". And being able to search is kind of critical. Enough so that an ugly formatting is preferable to losing the ability to search and to be indexed properly. Obviously, since I need the site to be responsive and I do not know what size screens will be used I cannot have forced line breaks, either, another trick used when publishing.
So, finally, my question. Is there a way I can define a style or function or some sort of element that automatically associates a certain character--in my case the tsheg character--as having a <wbr> command after it without actually needing to input that command into my HTML? So when the text is justified it treats every tsheg as a <wbr>? I have a class .Tibetan in my stylesheet that defines the font and the justification and so forth, is there some way I can add some code there that achieves what I am looking for?
The one other thing I tried was replacing all of the spaces with   which gave a beautiful justified appearance but it also caused the browser to disregard the tsheg marks entirely and it allowed for the cutting in half of syllables.
If you want to see an example of what I am talking about you can visit this page of my site: http://publishing.simplebuddhistmonk.net/index.php/downloads/critical-editions/ and next to the word "English" click the Tibetan characters and that will bring up a paragraph of prose, or you can look here: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ (though the formatting on that latter page is less egregious than the former, at least on my screen).
EDIT It looks like the solution this person used might be able to be adapted for my use: Dynamically add <wbr> tag before punctuation however I do not actually understand what I would need to add, and where, to make that work for me. Anyone think that might apply to this scenario? And if so, what code would I add where?
NEW EDIT So, I think the problem might be with the search function that comes from my WordPRess theme. I used my workaround as mentioned above, adding the tag  after every tsheg, on this page: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ and as you can see, it displays perfectly. But if you search for any phrase from that page using the search function that is up in my header, it will not find it. If you do a Ctrl+F and search on the page, though it will find it. Even if you copy the text from the page and paste it into the search box it still does not find it. Copy the text into a word editor doesn't reveal any hidden or invisible characters. However, if you search for a term from this page http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/beautiful-garland-ten-innermost-jewels-tib/ which I have not added the  tags to, you will see that it finds it no problem.
So, that leads me to believe the error is in the search function. Any experience with this? Because search is important but I can quite possibly find alternative earch widgets to replace the one that comes with the theme. What is most important though is if you search for a line of text on Google it needs to be found. My site has not been indexed fully by any search engine so I cannot yet confirm if this does or does not affect them.
So.... At this point I wil take any advice I can get. Any advice regarding the original question (is there a way to tell the style guide "if your are displaying X then treat it like X" ) or any idea about this issue with the search functionality, and how the  tag may or may not affect search, both from within the site and also from search engines.


Q: Trying to add an alert to detection model "ssd_mobilenet_v2", throws an error Using "ssd_mobilenet_v2_fpn_keras" i am trying to add an alert system
The detection model is loaded in to the below function
 def detect_fn(image):
    image, shapes = detection_model.preprocess(image)
    prediction_dict = detection_model.predict(image, shapes)
    detections = detection_model.postprocess(prediction_dict, shapes)
    return detections

The image is converted to a tensor
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)

The the tensor is fead to the detection model
detections = detect_fn(input_tensor)
The output of the detection model is a dictionary, with the following keys:
dict_keys(['detection_boxes', 'detection_scores', 'detection_classes', 'raw_detection_boxes', 'raw_detection_scores', 'detection_multiclass_scores', 'detection_anchor_indices', 'num_detections'])

detections[detection_classes], gives the following output ie 0 is ClassA, 1 is ClassB
[0 1 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 0 1]

detections['detection_scores'] gives the score for each box detected (a few shown below)
[0.988446 0.7998712 0.1579772 0.13801616 0.13227147 0.12731305 0.09515342 0.09203091 0.09191579 0.08860824 0.08313078 0.07684237

I am trying to Print("Attention needed"), if detection classB ie 1 is observed
for key in detections['detection_classes']:
if key==1:
    print('Alert')

When i try to do that i get an error
`ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How do make it work?
I want the code to print "Attention needed" is Class =1 or A and detection_scores >= 14
Code Explained, a bit further

links for the complete code are below :

*

*Tutorial on YouTube

*GitHub sources repository

A: As mentioned in the error message, you should use .any(). like:
if (key == 1).any():
  print('Alert')

As key == 1 will be an array with [False, True, True, False, ...]
You might also want to detect ones that exceeds certain score, say 0.7:
for key, score in zip(
  detections['detection_classes'],
  detections['detection_scores']):
  if score > 0.7 and key == 1:
    print('Alert')
    break


Q: Android - How to open an associated file to an application from main activity
Possible Duplicate:
Android intent filter: associate app with file extension

I've associated an XML file with extensions .x to my application. I would like to click on .x file, my associated application should start, and I would like to open the file, passed in some way, from inside onCreate() of activity. There is a way to do this ?
Thanks in advance.

A: Add this intent filter in your manifest to your activity
<intent-filter>
 <action android:name="android.intent.action.VIEW" />
 <category android:name="android.intent.category.DEFAULT" />
 <data android:mimeType="application/xml" />
 <data android:pathPattern=".*\\.x" />
</intent-filter>

on your onCreate files are passed on as:
Uri uri = this.getIntent().getData();
if(uri!=null){
 Log.v(getClass().getSimpleName(), "importing uri:"+uri.toString());
}


Q: Crop raster plot in r I am trying to read a hospital floor plan map (a higher resolution version than the one here in .PNG form) http://www.alfredicu.org.au/assets/Miscellaneous-Downloads/newicufloorplan.pdf
So that I can then place points onto it representing OHS incidents. My problem is that I need to be able to cut down the map so that I am only looking at a subset of the area so the x-axis (which represents mm of the A2 page) is 10:300 and the y axis is 10:380.
I have read in the array and plot but do not know how to subset this plot. If you can advise how to change the dimensions of the plot so that I can 'zoom in' on the relevant part of the map that would be greatly appreciated.
#Read PNG into raster array
r <- readPNG("ICU-map.png")

#Set up the plot area as A2 with mm as the dimensions
icu <-plot(0, type='n', main="ICU", xlab="x", ylab="y", xlim=c(0, 594), ylim=c(0, 420))

#Get the plot information so the image will fill the plot box, and draw it
lim <- par()
rasterImage(r, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
grid()
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0),     type="b", lwd=5, col="white")


Q: Broken Adobe Air Installers, Do I Need a Certificate This is a multi-part question, but all to resolve the same issue.
I'm trying to publish a project I've been working on but get intermittent problems with .air files that are generated.
I always get the following warning when publishing my project:
"There was an error connecting to the timestamp server. You may not have a connection to the network, or the server itself may have a problem.
If you choose to disable timestamping, the AIR application will fail to install when the digital signature expires."
So I have had no choice but to disable timestamping.
I do have a working internet connection, but I'm working from my company network, could this be an issue, and if so, is there a work around (Opening a specific port or something)? Also, how long do the above-mentioned digital signatures have before expiring?
Also, I am creating my own certificate. Do I need to purchase some kind of certificate/license to install my application on another computer? I've done some research, but the information is hard to find, and what I do find is kind of cryptic at best. Currently, I only need to deploy to machines within the company.
Sometimes the installer works fine and without issue (on the computer that generated it at least), other times I get "The application could not be installed because the installer file is damaged. Try obtaining a new installer file from the application author." as an error message. Other times I get an error stating that certificates or signatures or something do not match (Sorry, I couldn't replicate the error so am paraphrasing).I have yet to get an install to work on a separate machine.
I've tried using Air 2.5 and 2.6.
Also, as an extra while I'm here: Can I embed AIR applications to be run INSIDE a browser like a traditional Flash project?

A: About certificate, you can use a self signed certificate, the only difference is that the users will see a big warning when installing that the publisher is unknown.
About timestamping, I only know that the adt tool that packages the app is attempting to connect to a timestamping server, I am not sure what protocol is used, you will need to check this and unblock this.
If the installer is not timestamped then the issue is that after the certificate expires you can continue using this installer and need to do a new one with a certificate that is not expired.
As an example, if I use a certificate that expires tomorrow today and the installer is not timestamped then it will not work after tomorrow but if it was timestamped then it will continue to work after the certificate expired because it was created  before the expiration
I seen the installer is damaged erors a few times on our customers machine, usually on Windows, sometimes uninstalling and reinstalling AIR helped but not always, the problem is that the error message is not detailled enough to fix this, in rare cases I had to create .exe installers for those customers but I suggest to try the installers on a few machines first and use the native .exe installers if anything else is not working.


Q: Javascript variable inside qoute (double inside single qoute) I am trying to use a variable in nodejs. It giving me errors whatever I try.
How can I use a variable in this string
 let txt= 'some unknown texts'
 "MATCH (productName) AGAINST ('txt')"

Here I need to replace txt.
Note: I cannot use ``
Edit
Here is the query I am using
await Product.query().whereRaw("MATCH (productName) AGAINST ('txt')").select('productName')

Thank you.

A: In ES6 you need to do the following to use a var in string
`MATCH (productName) AGAINST ${txt}`

IF you cannot use ``
Just go for the old way with string concatanation,
"MATCH (productName) AGAINST '" +txt + "'"


Q: How to make past date unselectable in fullcalendar? Problem is, how to disable selectable on PAST DATES in fullcalendar's month/week view.
I want to user not allowed to click/select the on past dates.

Here is some googled code snippet I am trying to implement on event rendering:
selectable: true,
selectHelper: false,
select: function(start, end, allDay) {
        var appdate = jQuery.datepicker.formatDate('<?php echo $DPFormat; ?>', new Date(start));
        jQuery('#appdate').val(appdate);
        jQuery('#AppFirstModal').show();
    },
    eventRender: function(event, element, view)
    {
        var view = 'month' ;
       if(event.start.getMonth() !== view.start.getMonth()) { return false; }
    },

But its not working though.
I tried bellow CSS too and this help me to hide past date text only, but selectable is still working on pastdate box.
.fc-other-month .fc-day-number {
     display:none;
}

I am really stuck with this problem. Please someone help me out.
Thanks...

A: The old answers to this question are ok...
However, the official documentation suggests a new, more concise solution:
First set the day you want to be the lower bound
 var today = new Date().toISOString().slice(0,10);

Then include the range using validRange. Simply omit the end date.
 validRange: {
    start: today
 }

A: In FullCalendar v3.0, there is the property selectAllow:
selectAllow: function(info) {
    if (info.start.isBefore(moment()))
        return false;
    return true;
}

A: In fullcalendar 3.9, you might prefer the validRange function parameter :
validRange: function(nowDate){
    return {start: nowDate} //to prevent anterior dates
},

Drawback: this also hides events before that datetime

A: You can combine:
-hide text by CSS as mentioned in question
-disable PREV button on current month
-check date on dayClick/eventDrop etc:
dayClick: function(date, allDay, jsEvent, view) {
    var now = new Date();
    if (date.setHours(0,0,0,0) < now.setHours(0,0,0,0)){
        alert('test');
    }
    else{
         //do something
    }
}

A: I have done this in my fullcalendar and it's working perfectly.
you can add this code in your select function.
 select: function(start, end, allDay) {
    var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd');
    var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd');
    if(check < today)
    {
        // Previous Day. show message if you want otherwise do nothing.
        // So it will be unselectable
    }
    else
    {
        // Its a right date
        // Do something
    }
  },

I hope it will help you.

A: I like this approach:
select: function(start, end) {
    if(start.isBefore(moment())) {
        $('#calendar').fullCalendar('unselect');
        return false;
    }
}

It will essentially disable selection on times before "now".
Unselect method

A: This is what I am currently using
Also added the .add() function so the user cannot add an event at the same hour
select: function(start, end, jsEvent, view) {
               if(end.isBefore(moment().add(1,'hour').format())) {
               $('#calendar').fullCalendar('unselect');
               return false;
             }

A: You can use this:
var start_date= $.fullCalendar.formatDate(start,'YYYY-MM-DD');

var today_date = moment().format('YYYY-MM-DD');

if(check < today)
{
    alert("Back date event not allowed ");
    $('#calendar').fullCalendar('unselect');
    return false
}

A: Thanks to this answer, I've found the solution below:
$('#full-calendar').fullCalendar({
    selectable: true,
    selectConstraint: {
        start: $.fullCalendar.moment().subtract(1, 'days'),
        end: $.fullCalendar.moment().startOf('month').add(1, 'month')
    }
});

A: I have tried this approach, works well.
$('#calendar').fullCalendar({
   defaultView: 'month',
   selectable: true,
   selectAllow: function(select) {
      return moment().diff(select.start, 'days') <= 0
   }
})

Enjoy!

A: below is the solution i'm using now:
        select: function(start, end, jsEvent, view) {
            if (moment().diff(start, 'days') > 0) {
                $('#calendar').fullCalendar('unselect');
                // or display some sort of alert
                return false;
            }

A: No need for a long program, just try this.
checkout.setMinSelectableDate(Calendar.getInstance().getTime());
Calendar.getInstance().getTime()

Gives us the current date.

A: I have been using validRange option.
validRange: {
  start: Date.now(),
  end: Date.now() + (7776000) // sets end dynamically to 90 days after now (86400*90)
}

A: In Fullcalendar i achieved it by dayClick event. I thought it is the simple way to do it.
Here is my code..
 dayClick: function (date, cell) {
              var current_date = moment().format('YYYY-MM-DD')
              // date.format() returns selected date from fullcalendar
              if(current_date <= date.format()) {
                //your code
              }
            }

Hope it helps past and future dates will be unselectable..

A: if any one of answer is not work for you please try this i hope its work for you.
 select: function(start, end, allDay) {

              var check = formatDate(start.startStr);
              var today = formatDate(new Date());

              if(check < today)
              {
                 console.log('past');
              }
              else
              {
                console.log('future');
              }
}

and also create function for date format as below
function formatDate(date) {
      var d = new Date(date),
          month = '' + (d.getMonth() + 1),
          day = '' + d.getDate(),
          year = d.getFullYear();

      if (month.length < 2) month = '0' + month;
      if (day.length < 2) day = '0' + day;

      return [year, month, day].join('-');
  }

i have tried all above question but not work for me
you can try this if any other answer work for you.
thanks

A: just add this if statement

 select(info) {
      if (moment(info.start).format() > moment().format()) {
       //your code here
      } else {
        toast.error("Please select valid date");
      }
    },

A: For FullCalendar React (Disable past day completely):
selectAllow={c => (moment().diff(c.start, 'hours') <= 0)}


Q: How to catch when user close a console application via “X” button I have to write data in memory to in a file to close my console application. How can i detect console closing event ?

A: When the terminal is closed, your program will get a SIGHUP, which kill it by default. add a signal handler to handle the SIGHUP do whatever you want. and if you program write to the console after it has been close, you may also get SIGPIPE, handle it properly


Q: How will you design memory for 1GB memory with each page size being 4K I was asked this question in a job interview recently. I answered that I wud use a hash data structure to begin with designing the system. But couldn't answer that well. I think the interviewer was looking for answers like how will i design a page table for this.
I would like to know how to answer this question. Like for each page size being 4K how many pages would be needed for 1Gb? Also, what other considerations I should keep in my mind to design it efficiently.

A: This question makes sense in the context of CPUs where the TLBs are
"manually" loaded and there are no predetermined page table
structures, like some models of MIPS, ARM, PowerPC.
So, some rough thoughts:
1G is 2^30 bytes or 2^18 = 256K 4K pages
Say, 4-byte entry per page, that's 1M for a single level page
table. Fast, but a bit wasteful on memory.
What can we do to reduce memory and still make it reasonably fast.
We need 18 bits per page frame number, cannot squeeze it in 2 bytes,
but can use 3-bytes per PTE, with 6 bits to spare to encode - access
rights, presence, COW, etc. That's 768K.
Instead of the whole page frame number we can keep only 16-bits of it,
with the remaining two determined by a 4-entry upper level page table
with a format like this:

*

*2 MSB of the physical page number

*21 bits for second level page table (30 bit address, aligned on 512K
boundary)

*spare bits

No place for per-page bits though, so lets move a few more address
bits to the upper level table to obtain
Second level page table entry (4K 2-byte entries = 8K)

*

*4 bits for random flags

*12 LSB of the page frame address

First level page table entry format (64 4-byte entries = 256 bytes):

*

*6 MSB of the page frame address

*17 bits for second level page table address (30-bit address aligned
at 8K)

*spare bits

A: Looks like an open end question to me. The main idea may be to know how much you know about memory and how much deep you can think of the cases to handle. Some of them could be:

*

*Pagination - How many pages you want to keep in memory for a process and how many on disk to optimize paging.

*Page Tables

*Security

*Others, if you can relate and think Of


Q: How to override span-columns at different breakpoint in SUSY I think I must be missing something fundamental with how susy works, and the documentation has too few examples to understand how this works.
I want different layouts at different breakpoints.  I can make it that far, but I want my elements to span different number of columns depending on what breakpoint is triggered.  So if I have a general stylesheet for mobile ('mobile-first') like:
 .wrapper{
        .element1{
            @include span-columns(4);
        }

        .element2{
            @include span-columns(2 omega);
        }
}

But once the width changes to my 'tablet' and it changes to an 8 column layout, I want to be able to change this to:
     @include at-breakpoint($tablet-break $tablet-layout){
         .wrapper{
        @include set-container-width;
            .element1{
                @include span-columns(5);
            }

            .element2{
                @include span-columns(3 omega);
            }
    }
}

It seems like this not only doesn't 'overwrite' the mobile settings, but it appears, upon firebug inspection, that the elements do not match up with my new tablet columns.  I think it is still using a 6 column layout.  Adding @include set-container-width doesn't seem to fix the problem; however, if I comment out the mobile layout it works.  So it's almost as if these include statements don't overwrite, so I think I'm not understanding how susy works.  Here's an example of firebug showing the element not matching the layout:

(Also I'm not sure of any SUSY best practices (except for don't nest more than 4 deep).  I could define all my sass with nested @at-breakpoint statements for all my changes, or I could define my default (mobile) css and then create a separate sass block all nested within at-breakpoint.  I don't know if this is causing a problem.)
UPDATE
It appears, that if I include at-breakpoint includes after the original (mobile) declaration, it seems to work.  Though it does seem to require code repetition:
        .element1{
        @include span-columns(2 omega);
        text-indent: -1em;
        text-align: center;
        @include at-breakpoint($tablet-break $tablet-layout){
            @include span-columns(3 omega);
            text-indent: 0;
            text-align: left;
        }
        @include at-breakpoint($desktop-break $desktop-layout){
            @include span-columns(3 omega);
            text-indent: 0;
            text-align: left;
        }
    }


Q: fftw shift zero-frequency to image center I am struggling on the result of FFTW applied on image.
I can do the Fourier transform and inverse Fourier transform on image, I am sure the two functions are working. Now I am trying to analyze the result of Fourier transform and try to apply a filter on it, etc.
Currently I am confusing on the FT result. As I know the the zero-frequency should be on the top-left corner. I should shift it to the image center if I want to check frequency friendly. There are at least two way I have tested. one method is described on the FFTW FAQ webpage, all the pixels in the image were multiplied by (-1)^(i + j) before Fourier transform, where i, and j are the pixel's index.
image was multiplied by (-1)^(i+j), then its magnitude is

but actually ,it should be like this (which I did in imagej) Fourier transform in imagej:

I also tried using my code to switch them after calculating its magnitude, but got the similar wrong result.
void ftShift2D(double * d, int w, int h)
{

    int nw = w/2;
    int nh = h/2;
    if ( w%2 != 0) {nw++;}
    if ( h%2 != 0) {nh++;}

        printf("%d, %d\n", nw, nh);
        for (int i = 0; i < nh ; i++)
        {
                for(int j = 0; j < nw; j++)
                {
                        int t1 = i * w + j;
                        int t2 = (i + nh + 1) * w + j + nw;
                        swapXY<double>(d[t1], d[t2]);
                }

                for (int k = nw; k < w; k++)
                {
                        int t1 = i  * w + k;
                        int t2 = (i + nh　＋ 1 ) * w + k - nw;
                        swapXY<double>(d[t1], d[t2]);
                }
        }
}

I understood the layout of FT result in FFTW, as is described in their website.
I also checked the output, this layout can be confirmed, only top half have data, the rest is 0. therefore, it seems explain why the two methods used above cannot work. I am trying to design new method to shift the zero-frequency to image center. could you give me a better way to do it?
I insist on this, aim to use the filter, it will be easier to understand. if the zero-frequency did not be shifted to center, could you guys give me another suggestion that I can, for example, apply a high Gaussian filter on it in frequency domain.
thanks a lot.
the input image is:

The FT and IFT code are
    void Imgr2c(double * d, fftw_complex * df, int w, int h)
{
        fftw_plan p = fftw_plan_dft_r2c_2d(h, w, d, df, FFTW_ESTIMATE);
        fftw_execute(p);

        fftw_destroy_plan(p);

}

void Imgc2r(fftw_complex * in, double * ftReverse, int w, int h)
{
        fftw_plan p = fftw_plan_dft_c2r_2d(h, w, in, ftReverse, FFTW_ESTIMATE);
        fftw_execute(p);

        int l = w * h;
        for (int i = 0; i < l; i++)
        {
                ftReverse[i] /= l;
        }

        fftw_destroy_plan(p);
}

[Edit by Spektre]
This is how it should more or less look like:

A: You may want to check out how I did it here:
https://github.com/kvahed/codeare/blob/master/src/matrix/ft/DFT.hpp
The functions doing the job are at the bottom. If there are any issues, feel free to contact me personally.

A: I found what is my problem! I did not understand the output layout of DFT in FFTW deeply. After some tests, I found the the dimension in width should w/2 +　1, and the dimension in height did not changed. the code to do FT, IFT, and shift the origin have no problem. what I need to do is changing the dimension when try to access it.
magnitude after DFT
magnitude after shifting the origin
Cheers,
Yaowang


Q: Is it possible to show blog view counter with information Google Analytics I have a static blog using Jekyll hosted on GitHub. I have set up Google Analytics for it and works well enough.
Now I want to show how many people viewed each post in my blog. I found Google Analytics JavaScript API to get the information. But it seems that this API uses OAuth for data access. So I think this might not be the API I needed.
Is it possible to do so with Google Analytics? I don't have any server since it's hosted on GitHub.

A: I finally solved this problem by Google Analytics superProxy as suggested in the comment of @EikePierstorff.
I wrote a blog on it.
Here's the main idea.
I first build a project on Google App Engile, with which I authenticate for the access of my Google Analytics. Then a URL of query (which can be pageview of certain pages) is generated in JSON format. I can set the refresh rate on this GAE project so that the JSON file can be updated from Google Analytic.
Sounds almost perfect to me. Thank you all guys for help!

A: You can't query the Google Analytics API without authorization by someone, that's the most important thing to remember.
It's certainly possible to display Google Analytics data on your website to users who don't have access to your account, but in order to do that, someone with access to the account needs to authorize and get an access token in order to run queries.
Normally this is done server side, and once you have a valid access token you can query the API client side (to display charts and graph, etc.). Access tokens are typically valid for 1 hour, so if you want to have your website up all the time, you'll also have to deal with refreshing the access token once it expires.
Now, since you're using Github Pages and don't have a back end, which means all the authorization will need to happen client side. While it's technically possible to do the same thing client side as server side, it's generally not a good idea because private data like your client secret, refresh token, etc. will be visible in the source code.
Applications that do auth client side typically don't authorize on behalf of a user. They require the users themselves to go through an auth flow for security reasons (as I just explained), but that would mean those users 1) have to log in, and 2) can only see the analytics data they have access to, which probably isn't what you want.
--
What you can do is run reports periodically yourself and export that data to a Google Spreadsheet. Google Spreadsheets allow you to embed charts and graphs of data as an <iframe> in external pages, so that might be an option.
At the end of the day, if you can't authorize server side you'll have to come up with some kind of workaround to make this happen.
Here are a few possibly helpful links that might point you in the right direction:
https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on
https://developers.google.com/analytics/devguides/reporting/embed
https://developers.google.com/analytics/solutions/report-automation-magic


Q: Not able to invoke a spark application using a java class on cluster Below is my project's structure:
spark-application:

scala1.scala // I am calling the java class from this class.
java.java // this will submit another spark application to the yarn cluster.

The spark-application that is being triggered by java class:

scala2.scala

My reference tutorial is here
When I run my java class from scala1.scala via spark-submit in the local mode the second spark application scala2.scala is getting triggered and working as expected.
But, when I run the same application via spark-submit in yarn cluster it is showing the below error!
Error: Could not find or load main class
org.apache.spark.deploy.yarn.ApplicationMaster

 Application application_1493671618562_0072 failed 5 times due to AM Container for appattempt_1493671618562_0072_000005 exited with exitCode: 1
 For more detailed output, check the application tracking page: http://headnode.internal.cloudapp.net:8088/cluster/app/application_1493671618562_0072 Then click on links to logs of each attempt.
 Diagnostics: Exception from container-launch.
 Container id: container_e02_1493671618562_0072_05_000001
 Exit code: 1
 Exception message: /mnt/resource/hadoop/yarn/local/usercache/helixuser/appcache/application_1493671618562_0072/container_e02_1493671618562_0072_05_000001/launch_container.sh: line 26: $PWD:$PWD/spark_conf:$PWD/spark.jar:$HADOOP_CONF_DIR:/usr/hdp/current/hadoop-client/:/usr/hdp/current/hadoop-client/lib/:/usr/hdp/current/hadoop-hdfs-client/:/usr/hdp/current/hadoop-hdfs-client/lib/:/usr/hdp/current/hadoop-yarn-client/:/usr/hdp/current/hadoop-yarn-client/lib/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/:$PWD/mr-framework/hadoop/share/hadoop/common/:$PWD/mr-framework/hadoop/share/hadoop/common/lib/:$PWD/mr-framework/hadoop/share/hadoop/yarn/:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/:/usr/hdp/${hdp.version}/hadoop/lib/hadoop-lzo-0.6.0.${hdp.version}.jar:/etc/hadoop/conf/secure: bad substitution
 Stack trace: ExitCodeException exitCode=1: /mnt/resource/hadoop/yarn/local/usercache/helixuser/appcache/application_1493671618562_0072/container_e02_1493671618562_0072_05_000001/launch_container.sh: line 26: $PWD:$PWD/spark_conf:$PWD/spark.jar:$HADOOP_CONF_DIR:/usr/hdp/current/hadoop-client/:/usr/hdp/current/hadoop-client/lib/:/usr/hdp/current/hadoop-hdfs-client/:/usr/hdp/current/hadoop-hdfs-client/lib/:/usr/hdp/current/hadoop-yarn-client/:/usr/hdp/current/hadoop-yarn-client/lib/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/:$PWD/mr-framework/hadoop/share/hadoop/common/:$PWD/mr-framework/hadoop/share/hadoop/common/lib/:$PWD/mr-framework/hadoop/share/hadoop/yarn/:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/:/usr/hdp/${hdp.version}/hadoop/lib/hadoop-lzo-0.6.0.${hdp.version}.jar:/etc/hadoop/conf/secure: bad substitution
 at org.apache.hadoop.util.Shell.runCommand(Shell.java:933)
 at org.apache.hadoop.util.Shell.run(Shell.java:844)
 at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:1123)
 at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:225)
 at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:317)
 at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:83)
 at java.util.concurrent.FutureTask.run(FutureTask.java:266)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 at java.lang.Thread.run(Thread.java:745)
 Container exited with a non-zero exit code 1
 Failing this attempt. Failing the application.

My project's directory structure is given below:
lrwxrwxrwx 1 yarn hadoop   95 May  5 06:03 __app__.jar -> /mnt/resource/hadoop/yarn/local/filecache/10/sparkfiller-1.0-SNAPSHOT-jar-with-dependencies.jar
-rw-r--r-- 1 yarn hadoop   74 May  5 06:03 container_tokens
-rwx------ 1 yarn hadoop  710 May  5 06:03 default_container_executor_session.sh
-rwx------ 1 yarn hadoop  764 May  5 06:03 default_container_executor.sh
-rwx------ 1 yarn hadoop 6433 May  5 06:03 launch_container.sh
lrwxrwxrwx 1 yarn hadoop  102 May  5 06:03 __spark_conf__ -> /mnt/resource/hadoop/yarn/local/usercache/helixuser/filecache/80/__spark_conf__6125877397366945561.zip
lrwxrwxrwx 1 yarn hadoop  125 May  5 06:03 __spark__.jar -> /mnt/resource/hadoop/yarn/local/usercache/helixuser/filecache/81/spark-assembly-1.6.3.2.5.4.0-121-hadoop2.7.3.2.5.4.0-121.jar
drwx--x--- 2 yarn hadoop 4096 May  5 06:03 tmp
find -L . -maxdepth 5 -ls:
3933556      4 drwx--x---   3 yarn     hadoop       4096 May  5 06:03 .
3933558      4 drwx--x---   2 yarn     hadoop       4096 May  5 06:03 ./tmp
3933562      4 -rw-r--r--   1 yarn     hadoop         60 May  5 06:03 ./.launch_container.sh.crc
3933517 185944 -r-x------   1 yarn     hadoop   190402950 May  5 06:03 ./__spark__.jar
3933564      4 -rw-r--r--   1 yarn     hadoop          16 May  5 06:03 ./.default_container_executor_session.sh.crc
3933518      4 drwx------   2 yarn     hadoop        4096 May  5 06:03 ./__spark_conf__
3933548      4 -r-x------   1 yarn     hadoop         945 May  5 06:03 ./__spark_conf__/taskcontroller.cfg
3933543      4 -r-x------   1 yarn     hadoop         249 May  5 06:03 ./__spark_conf__/slaves
3933541      4 -r-x------   1 yarn     hadoop        2316 May  5 06:03 ./__spark_conf__/ssl-client.xml.example
3933520      4 -r-x------   1 yarn     hadoop        1734 May  5 06:03 ./__spark_conf__/log4j.properties
3933526      4 -r-x------   1 yarn     hadoop         265 May  5 06:03 ./__spark_conf__/hadoop-metrics2-azure-file-system.properties
3933536      4 -r-x------   1 yarn     hadoop        1045 May  5 06:03 ./__spark_conf__/container-executor.cfg
3933519      8 -r-x------   1 yarn     hadoop        5685 May  5 06:03 ./__spark_conf__/hadoop-env.sh
3933531      4 -r-x------   1 yarn     hadoop        2358 May  5 06:03 ./__spark_conf__/topology_script.py
3933547      8 -r-x------   1 yarn     hadoop        4113 May  5 06:03 ./__spark_conf__/mapred-queues.xml.template
3933528      4 -r-x------   1 yarn     hadoop         744 May  5 06:03 ./__spark_conf__/ssl-client.xml
3933544      4 -r-x------   1 yarn     hadoop         417 May  5 06:03 ./__spark_conf__/topology_mappings.data
3933549      4 -r-x------   1 yarn     hadoop         342 May  5 06:03 ./__spark_conf__/__spark_conf__.properties
3933523      4 -r-x------   1 yarn     hadoop         247 May  5 06:03 ./__spark_conf__/hadoop-metrics2-adl-file-system.properties
3933535      4 -r-x------   1 yarn     hadoop        1020 May  5 06:03 ./__spark_conf__/commons-logging.properties
3933525     24 -r-x------   1 yarn     hadoop       22138 May  5 06:03 ./__spark_conf__/yarn-site.xml
3933529      4 -r-x------   1 yarn     hadoop        2450 May  5 06:03 ./__spark_conf__/capacity-scheduler.xml
3933538      4 -r-x------   1 yarn     hadoop        2490 May  5 06:03 ./__spark_conf__/hadoop-metrics.properties
 3933534     12 -r-x------   1 yarn     hadoop        8754 May  5 06:03 ./__spark_conf__/hdfs-site.xml
 3933533      8 -r-x------   1 yarn     hadoop        4261 May  5 06:03 ./__spark_conf__/yarn-env.sh
 3933532      4 -r-x------   1 yarn     hadoop        1335 May  5 06:03 ./__spark_conf__/configuration.xsl
 3933530      4 -r-x------   1 yarn     hadoop         758 May  5 06:03 ./__spark_conf__/mapred-site.xml.template
 3933545      4 -r-x------   1 yarn     hadoop        1000 May  5 06:03 ./__spark_conf__/ssl-server.xml
 3933527      8 -r-x------   1 yarn     hadoop        4680 May  5 06:03 ./__spark_conf__/core-site.xml
 3933522      8 -r-x------   1 yarn     hadoop        5783 May  5 06:03 ./__spark_conf__/hadoop-metrics2.properties
 3933542      4 -r-x------   1 yarn     hadoop        1308 May  5 06:03 ./__spark_conf__/hadoop-policy.xml
 3933540      4 -r-x------   1 yarn     hadoop        1602 May  5 06:03 ./__spark_conf__/health_check
 3933537      8 -r-x------   1 yarn     hadoop        4221 May  5 06:03 ./__spark_conf__/task-log4j.properties
 3933521      8 -r-x------   1 yarn     hadoop        7596 May  5 06:03 ./__spark_conf__/mapred-site.xml
 3933546      4 -r-x------   1 yarn     hadoop        2697 May  5 06:03 ./__spark_conf__/ssl-server.xml.example
 3933539      4 -r-x------   1 yarn     hadoop         752 May  5 06:03 ./__spark_conf__/mapred-env.sh
 3932820 135852 -r-xr-xr-x   1 yarn     hadoop   139105807 May  4 22:53 ./__app__.jar
 3933566      4 -rw-r--r--   1 yarn     hadoop          16 May  5 06:03 ./.default_container_executor.sh.crc
 3933563      4 -rwx------   1 yarn     hadoop         710 May  5 06:03 ./default_container_executor_session.sh
 3933559      4 -rw-r--r--   1 yarn     hadoop          74 May  5 06:03 ./container_tokens
3933565      4 -rwx------   1 yarn     hadoop         764 May  5 06:03 ./default_container_executor.sh
3933560      4 -rw-r--r--   1 yarn     hadoop          12 May  5 06:03 ./.container_tokens.crc
3933561      8 -rwx------   1 yarn     hadoop        6433 May  5 06:03 ./launch_container.sh
broken symlinks(find -L . -maxdepth 5 -type l -ls):

Below is the java code that invokes the second Spark application:
import org.apache.spark.deploy.yarn.Client;
import org.apache.spark.deploy.yarn.ClientArguments;
import org.apache.hadoop.conf.Configuration;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkException;

public class CallingSparkJob {

        public void submitJob(String latestreceivedpitrL,String newPtr) throws Exception {
           System.out.println("In submit job method");
            try{
            System.out.println("Building a spark command");

   // prepare arguments to be passed to
   // org.apache.spark.deploy.yarn.Client object
   String[] args = new String[] {
       // the name of your application
"--name",
"name",
// "--master",
    // "yarn",
      //    "--deploy-mode",
    //  "cluster",

          //       "--conf", "spark.yarn.executor.memoryOverhead=600", "--conf",
        "spark.yarn.submit.waitAppCompletion=false",

       // memory for driver (optional)
       "--driver-memory",
       "1000M",

       "--num-executors",
       "2",
       "--executor-cores",
       "2",

       // path to your application's JAR file
       // required in yarn-cluster mode
       "--jar",
   "wasb://storage_account_container@storageaccount.blob.core.windows.net/user/ankushuser/sparkfiller/sparkfiller-1.0-SNAPSHOT-jar-with-dependencies.jar",
       // name of your application's main class (required)
       "--class",
       "com.test.SparkFiller",

       // comma separated list of local jars that want
       // SparkContext.addJar to work with
      // "--addJars",
      // "/Users/mparsian/zmp/github/data-algorithms-book/lib/spark-assembly-1.5.2-hadoop2.6.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/log4j-1.2.17.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/junit-4.12-beta-2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jsch-0.1.42.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/JeraAntTasks.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jedis-2.5.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jblas-1.2.3.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/hamcrest-all-1.3.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/guava-18.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-math3-3.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-math-2.2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-logging-1.1.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-lang3-3.4.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-lang-2.6.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-io-2.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-httpclient-3.0.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-daemon-1.0.5.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-configuration-1.6.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-collections-3.2.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-cli-1.2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/cloud9-1.3.2.jar",

       // argument 1 for latestreceivedpitrL
    "--arg",
       latestreceivedpitrL,

       // argument 2 for newPtr
     "--arg",
       newPtr,

"--arg",
"yarn-cluster"

   };

  System.out.println("create a Hadoop Configuration object");

// create a Hadoop Configuration object
   Configuration config = new Configuration();

   // identify that you will be using Spark as YARN mode
  System.setProperty("SPARK_YARN_MODE", "true");

   // create an instance of SparkConf object
   SparkConf sparkConf = new SparkConf();
sparkConf.setSparkHome("/usr/hdp/current/spark-client");
    // sparkConf.setMaster("yarn");
    sparkConf.setMaster("yarn-cluster");

   // sparkConf.setAppName("spark-yarn");
   //  sparkConf.set("master", "yarn");

    // sparkConf.set("spark.submit.deployMode", "cluster"); // worked

   // create ClientArguments, which will be passed to Client
   // ClientArguments cArgs = new ClientArguments(args);
   ClientArguments cArgs = new ClientArguments(args, sparkConf);

   // create an instance of yarn Client client
   Client client = new Client(cArgs, config, sparkConf);

   // submit Spark job to YARN
   client.run();
   }catch(Exception e){

       System.out.println("Error submitting spark Job");

       System.out.println(e.getMessage());
   }

  }

 }

The spark-submit command used to run the first spark application locally:

spark-submit --class scala1 --master yarn --deploy-mode cluster --num-executors 2 --executor-cores 2 --conf spark.yarn.executor.memoryOverhead=600 --conf spark.yarn.submit.waitAppCompletion=false /home/ankushuser/kafka_retry/kafka_retry_test/sparkflightaware/target/sparkflightaware-0.0.1-SNAPSHOT-jar-with-dependencies.jar

If I run this spark-submit command locally it is invoking the java class and the spark-submit command for the second scala2 application is working fine.
If I run it in yarn mode, then I am facing the issue.
Thank you for your help.

A: Since there's a bounty, I'll repost this as a reply as well -- but in reality I would like to flag this as a duplicate, since the actual Exception is the one covered in another question, and answered:
It is caused by hdp.version not getting substituted correctly. You have to set hdp.version in the file java-opts under $SPARK_HOME/conf.
Alternatively, use
--driver-java-options="-Dhdp.version=INSERT_VERSION_STRING_HERE"  --conf "spark.executor.extraJavaOptions=-Dhdp.version=INSERT_VERSION_STRING_HERE" in your spark-submit and make sure to use the correct version string, as in the subdirectory of /usr/hdp.
If you want to stick with calling client.submit from your code, then you need to put those lines into the --arg you build in your code.


Q: Why there is no output to the framebuffer's textures? Here is the code:
int main(){
    //init gl environment
    //...

    //create textures for pass 1

    GLuint normal_color_output;
    glCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &normal_color_output);
    glTextureStorage2DMultisample(normal_color_output, 8, GL_RGBA32F, 1000, 800, GL_TRUE);
    GLuint high_color_output;
    glCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &high_color_output);
    glTextureStorage2DMultisample(high_color_output,8, GL_R11F_G11F_B10F, 1000, 800,GL_TRUE);

    //init framebuffer

    GLuint render_buffer;
    glCreateRenderbuffers(1, &render_buffer);
    glNamedRenderbufferStorageMultisample(render_buffer, 8, GL_DEPTH24_STENCIL8, 1000, 800);
    GLuint framebuffer;
    glCreateFramebuffers(1, &framebuffer);
    glNamedFramebufferTexture(framebuffer, GL_COLOR_ATTACHMENT0, normal_color_output,0);
    glNamedFramebufferTexture(framebuffer, GL_COLOR_ATTACHMENT1, high_color_output, 0);
    glNamedFramebufferRenderbuffer(framebuffer, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, render_buffer);
    const GLenum drawbuffers[] = {GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1};
    glNamedFramebufferDrawBuffers(framebuffer, 2, drawbuffers);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

    //init another framebuffer
    //What I want to do is trying to achieve implementing my own msaa color resolve solution.

    GLuint mix_framebuffer;
    glCreateFramebuffers(1, &mix_framebuffer);
    GLuint mix_renderbuffer;
    glCreateRenderbuffers(1, &mix_renderbuffer);
    glNamedRenderbufferStorage(mix_renderbuffer, GL_DEPTH24_STENCIL8, 1000, 800);
    GLuint normal_antialiasing_texture, hdr_antialiasing_texture;
    glCreateTextures(GL_TEXTURE_2D, 1, &normal_antialiasing_texture);
    glTextureStorage2D(normal_antialiasing_texture, 1, GL_RGBA32F, 1000, 800);
    glCreateTextures(GL_TEXTURE_2D, 1, &hdr_antialiasing_texture);
    glTextureStorage2D(hdr_antialiasing_texture, 1, GL_RGBA32F, 1000, 800);
    glNamedFramebufferTexture(mix_framebuffer, GL_COLOR_ATTACHMENT0, normal_antialiasing_texture, 0);
    glNamedFramebufferTexture(mix_framebuffer, GL_COLOR_ATTACHMENT1, hdr_antialiasing_texture, 0);
    glNamedFramebufferDrawBuffers(mix_framebuffer,2, drawbuffers);
    glNamedFramebufferRenderbuffer(mix_framebuffer, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mix_renderbuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, mix_framebuffer);

    //....
    //draw commands
    while (!glfwWindowShouldClose(window)) {
        // pass 1
        glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        glUseProgram(program);
        glUniformMatrix4fv(3, 1, GL_FALSE, glm::value_ptr(camera.GetViewMat()));
        model.Render(program);
        glPointSize(20.f);
        glUseProgram(light_shader);// I draw a point to show the light's position
        glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(camera.GetViewMat()));
        glDrawArrays(GL_POINTS, 0, 1);

        //pass 2
        glBindFramebuffer(GL_FRAMEBUFFER, mix_framebuffer);
        glUseProgram(mix_program);
        glBindTextureUnit(0, normal_color_output);
        glBindTextureUnit(1, high_color_output);
        glClear(GL_COLOR_BUFFER_BIT);
        glNamedFramebufferDrawBuffers(mix_framebuffer, 2, drawbuffers);
        glDrawArrays(GL_POINTS, 0, 1);
        //...
    }
}

I use geometry shader to model a square, here is the code:
//mix_gs.glsl
#version 450 core

layout(points) in;
layout(triangle_strip) out;
layout(max_vertices = 4) out;

void main(){
    gl_Position = vec4(-1,1,-1,1);
    EmitVertex();
    gl_Position = vec4(-1,-1,-1,1);
    EmitVertex();
    gl_Position = vec4(1,1,-1,1);
    EmitVertex();
    gl_Position = vec4(1,-1,-1,1);
    EmitVertex();
    EndPrimitive();
}

here is the mix_fs.glsl:
#version 450 core

layout(location = 0)out vec4 color;
layout(location = 1)out vec4 hdr_color;
layout(binding = 0) uniform sampler2DMS color_sdms;
layout(binding = 1) uniform sampler2DMS hdr_sdms;
void main(){
/*
    for(int i=0;i<8;i++){
        color += texelFetch(color_sdms,ivec2(gl_FragCoord.xy),i);
        hdr_color += vec4(texelFetch(hdr_sdms,ivec2(gl_FragCoord.xy),i).xyz,1);
    }
    */
    color = vec4(1,0,0,1);//I just output a color
    hdr_color = vec4(0,1,0,1);
}

I encount a problem that I find during the draw pass 2, gl cannot outout any color to textures bind to mix_framebuffer.
Here is the debugging info in RenderDoc:
draw pass 1 texture output:

draw pass 2's geometry output:

draw pass 2 texture input:

draw pass 2 texture output:

You can see, draw-pass 1's output was passed to draw-pass2's pipeline successfully, but there is no output to draw-pass2's textures. I don't know why.

A: If you don't see even the plain color, the first I'd recommend to check how it was discarded. There are no so many options:

*

*glColorMask. Highly likely it's not your case, since pass 1 works;

*Wrong face culling and polygon winding order (CW, CCW). By your geometry shader, it looks like CW;

*Blending options;

*Depth-stencil state. I see you use glNamedRenderbufferStorage(mix_renderbuffer, GL_DEPTH24_STENCIL8, 1000, 800); What are depth-stencil settings?

If everything above looks good, any glGetError messages? If it's ok, try to remove MRT for a debugging purposes and output the only color in the second pass. If it would work, probably some error in MRT + Depth buffer setup.


Q: how to draw a line in html 30pt from either side I have a footer div that is 100% wide and 200pt high.  I want to draw a white line that starts 30pt in from both the left and the right 25pt from the bottom.
I have playing about with a div 1px high and positioning it with the following but to now avail.
    #HPFooterlinebreak{
    position:absolute;
    bottom:25pt;
    right:30pt;
    left:30pt;
    background-color:#EFF1EF;
    height:1px;
    width:100%;
}

Just to be clear the div above is not the one 200pt high.
Thanks

A: Why not use a positioned pseudo element with a suitably applied border?

pseudo-elements are added to selectors but instead of describing a
  special state, they allow you to style certain parts of a document

You may also want to use the semantic footer element (if appropriate)

footer {
  background: black;
  height: 200pt;
  position: relative;
}
footer:after {
  content: '';
  position: absolute;
  left: 30pt;
  right: 30pt;
  bottom: 25pt;
  border-top: 1px solid white;
}

A: You're almost there. You don't need the width. Also, if you use position: absolute to position the element inside its parent, then you must also add position: relative or position: absolute to the parent itself.
By the way, if this white line is just for show, you might as well use a pseudo-element for it and keep the HTML simple. But if you like to, you might as well change .footer:before back to #HPFooterlinebreak.

.footer {
    background-color: blue;
    position: relative;
    height: 200px;
}
.footer:before{
    content: "";
    position:absolute;
    bottom:25pt;
    right:30pt;
    left:30pt;
    background-color:#EFF1EF;
    height:1px;
}

  Yo


Q: How to prevent Mocha from preserving require cache between test files? I am running my integration test cases in separate files for each API.
Before it begins I start the server along with all services, like databases. When it ends, I close all connections. I use Before and After hooks for that purpose. It is important to know that my application depends on an enterprise framework where most "core work" is written and I install it as a dependency of my application.
I run the tests with Mocha.
When the first file runs, I see no problems. When the second file runs I get a lot of errors related to database connections. I tried to fix it in many different ways, most of them failed because of the limitations the Framework imposed me.
Debugging I found out that Mocha actually loads all files first, that means that all code written before the hooks and the describe calls is executed. So when the second file is loaded, the require.cache is already full of modules. Only after that the suite executes the tests sequentially.
That has a huge impact in this Framework because many objects are actually Singletons, so if in a after hook it closes a connection with a database, it closes the connection inside the Singleton. The way the Framework was built makes it very hard to give a workaround to this problem, like reconnecting to all services in the before hook.
I wrote a very ugly code that helps me before I can refactor the Framework. This goes in each test file I want to invalidate the cache.
function clearRequireCache() {
    Object.keys(require.cache).forEach(function (key) {
        delete require.cache[key];
    });
}

before(() => {
    clearRequireCache();
})

It is working, but seems to be very bad practice. And I don`t want this in the code.
As a second idea I was thinking about running Mocha multiple times, one for each "module" (as of my Framework) or file.
"scripts": {
   "test-integration" : "./node_modules/mocha/bin/mocha ./api/modules/module1/test/integration/*.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file1.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file2.integration.js"
}

I was wondering if Mocha provides a solution for this problem so I can get rid of that code and delay the code refacting a bit.