text:
Q: Why is LuaLaTeX so slow and is there anything I can do about it? A while back I started bumping into issues with LuaLaTex and switched to compiling a project in XeLaTeX. Since then it seems most of my issues have been resolved upstream or are fixable one way on another. It's been suggested that I switch back to avoid some XeLaTeX issues, but speed is one reason that would keep me from doing so. I've gotten almost all the kinks worked out now so my documents compile in either engine, but LuaLaTeX takes over twice as long to do so.
My documents are not long, but they are complicated (example PDF output) involving many rendering passes to fit everything inside of a hard page limit, then doing it all again for other page layouts and content options. A few seconds here and there isn't that big an issue until it adds up to waiting 5 minutes for your documents to be ready for printing instead of 2. I did some testing and it appears this isn't unique to my complicated project. For example this MWE I was using to test ligatures, hyphenation and small-cap font features compiles in 1.29 seconds using XeLaTeX but takes 3.96 seconds in LuaLaTeX!
\documentclass{minimal}
\usepackage{polyglossia}
\usepackage{testhyphens}
\usepackage{libertine}
\setmainlanguage{turkish}
\begin{document}
Uzun---tire. {\scshape Uzun---tire.}
\begin{checkhyphens}{}
İstanbullularınki
İstanbul'lularınki
\end{checkhyphens}
İzmir {\scshape İzmir}
\end{document}

Is this just the way the engine is or am I doing something wrong? If the performance isn't normally so dramatically different, what sort of things might I be looking for to get it setup correctly?
Edit: Based on comments and answers so far it looks like a lot of potentially related issues may be platform specific. I'm particularly interested in problems manifest on and solutions relevant for Linux, although any generally applicable pitfalls or optimizations are welcome.

A: In my case a big reason for slowness in LuaLaTeX is polyglossia. On my (Linux) machine, switching to babel makes compiling up to five times faster for small documents, and generally twice as fast for moderate reports of a few page.
For example the following page :
\documentclass[french,a4paper]{article}
\usepackage{polyglossia}
\begin{document}

\section{Graphe ``temporel'' / d'activation}
On définit le graphe dirigé acyclique $G_a=(V_a,E_a)$.
\begin{itemize}
    \item $V_a$ : points d'interaction.
    \item $E_a$ : écoulement entre les points.
\end{itemize}

\section{Graphe hiérarchique}
Graphe de dépendances de données : une fonction a besoin de l'exécution d'une fonction précédente.

Optimisation : passer directement les valeurs. Mais en attendant, on fait du f1 -> store et read -> f2.

\section{Connection entre nœuds}
\begin{itemize}
\item Cas 1 : "optimiste" : on essaye de toujours envoyer les données
\item Cas 2 : "pessimiste" : on n'envoie les données que lorsque tous les nœuds du graphe sont actifs
\item Cas 3 : "retard" : les données sont bufferisées pour envoyer lorsqu'un objet subséquent devient actif. Note : que se passe-t-il si on a plusieurs utilisateurs subséquents ? Est-ce qu'on reprend du début à chauqe fois (le pointeur est dans l'objet situé au bout de l'arête), ou de là ou on s'est arrêté de lire (le pointeur est dans l'objet situé à l'origine de l'arête).
\item Cas 4 : envoyer en parallèle ?
\item Cas 5 : ce qu'il y a actuellement : les noeuds suivants remplacent les résultats des noeuds précédents.
\end{itemize}

Cas ou on a une variable interne au système : on est toujours soit dans le case 2 ou 3.

Cas ou l'utilisateur doit spécifier explicitement les relations de données : 3, 5

Spécification des sous-graphes

Définir l'interface utilisateur
\end{document}

takes on average (five takes) 0.79 seconds to render, and 0.12 second if I switch to babel and remove \usepackage{polyglossia}.

A: Running some tests and looking at the output of the process monitor I found that on windows with miktex the "feature" of fontspec to load default settings from a file with the ending .fontspec is slowing down the font search considerably as miktex is looking everywhere for the files. Disabling the feature meant for me that this document needed only around 2.5 seconds instead of 12. In texlive the time gain was 3 seconds instead of 4.6.
\documentclass{article}
\usepackage{fontspec}
\ExplSyntaxOn
\cs_set:Nn \__fontspec_load_external_fontoptions:Nn
 {}
\ExplSyntaxOff
\usepackage{libertine}

\begin{document}
abc
\end{document}

Edit
In the case of miktex there is imho a bug in the file search: unlike pdflatex or xelatex lualatex doesn't rely on the FNDB but starts a real file search in the texmf tree. I made a bug report: https://sourceforge.net/p/miktex/bugs/2356/. In the case of texlive I still have to test if I can improve the compilation time by forcing texlive to use only the ls-R-files.
Edit 2
One can improve the compilation time in texlive by creating more ls-R-files (at least on my system with quite a lot of local roots ...), but the effect is not so dramatic as the large texmf-trees like texmf-dist already uses only the ls-R.
Edit 3
Miktex has added a patch to luatex. With todays update it no longers does a slow disk search if a file is not found. The compilation time of a document which loads e.g. libertine dropped from 12 to 3 seconds on my PC ;-).

A: If you have a Windows system for some reason, font packages are way way slower than finding the actual fonts and installing them as native in the Fonts directory. Here, I've downloaded the OTF version from their website and used
\directlua{starttime = os.clock()}
\documentclass{article}
\usepackage[timer=true]{regstats}
\usepackage{polyglossia}
\usepackage{testhyphens}
%\usepackage{libertine}
\setmainlanguage{turkish}
\setmainfont{Linux Libertine O}
\begin{document}
Uzun---tire. {\scshape Uzun---tire.}
\begin{checkhyphens}{}
İstanbullularınki
İstanbul'lularınki
\end{checkhyphens}
İzmir {\scshape İzmir}
İzmirliler ile burada karşılaşmak çok hoş.
\end{document}

The compilation speeds up  3-5 times depending on the document. As a bonus you get the small caps i (maybe faked from the normal version, I'm not sure).
That probably comes with the price of loosing font properties but check it for yourself if there is any quality change. However in general you can switch back to the original package when you are satisfied with the layout anyways.
I also would like to know why Windows systems has this problem in general.


text:
Q: NodeJS and Socket.IO to keep track of user visit time High performance I've built an application with node and socket.io to keep track when a visitor visits a page, and leaves. When the visitor leaves I store the time the visitor was on the page to redis. That's all the application has to do.
Here's the thing, the application needs to support ~15k concurrent connections, but I'm getting a lot of handshake errors when the benchmark hits around 10.000 conc. visitors. I don't know why exactly. Does anyone have any experience with these kind of problems?
I also tried scaling the application in multiple processes, using the RedisStore backend for node but haven't had much success.

A: There are a number of things which could be causing this. You should check your system error logs and see if there are any errors there which may indicate where the problem actually is.
This question has some good information and the limit they were hitting is close to what you are hitting as well. It's worth a look.
https://serverfault.com/questions/10852/what-limits-the-maximum-number-of-connections-on-a-linux-server

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does the word "lines" mean in the phrase "tenure track lines"?
The resources in the language department of most major research universities were assigned to different languages a very long time ago; resources such as budget, space, and tenure track lines.

My guess is that, there are several candidates for a tenure, and they have to reach all sorts of required standards, so the lines refer to the standards of all aspects the candidates must reach. Is my guess right?

A: At many American universities, every department is allotted a fixed number of slots for professors on the tenure track (assistant professors without tenure, associate professors, full professors with tenure). Each of these slots is called a tenure track line.
We can also say a department has 20 tenure track positions or 20 tenure track slots instead of 20 tenure track lines. We would not say that the department has 20 tenure tracks.
I believe the word line refers to the progression from assistant professor without tenure to (eventually) full professor with tenure. This is also exactly what track in tenure track refers to, but they are used differently, as described above.

A: In the US, it has long been the case that each language group has its own department within the university.
Department of Romance Languages
Department of Germanic Languages
Department of Slavic Languages
Candidates are awarded or denied tenure by the university. It is quite common for a department to put forward a candidate and yet the candidate will be denied tenure. A department (but sometimes more than one department acting in concert) initiates the procedure and the university makes the decision based on various criteria.
We say that a person "is in line for tenure" or "on tenure track". Each department typically has its own line to tenure.
But promotion via the tenure line is just one path to promotion within a university. If the university has a medical school and teaching hospital, it will have a "medical center line" in addition to the tenure line.
The line is the path to promotion.


text:
Q: Only partial data was loaded from EXCEL source to OLEDB destination I was loading data from EXCEL source to OLEDB destination and put a Data Conversion in between.
My source include column like this
ROOM_NO
B2
B2
101
102
103
101
I didn't get the right result, so I checked my data viewer. It's like this
ROOM_NO
NULL
NULL
101
102
103
101
I was told that the reason is I only have two row in nvarchar type, but 4 rows in float, so EXCEL source consider it as float.
So I went to the advance editor and found the Input and Output Property tab and changed the external columns and Output columns to nvarchar 255. I still got NULLs. Then I changed ValidateExternalMetadata to false under Component Property tab. Again, NULLs - -! Could anyone help me out here?
Thank you.
Eddie

A: Thank you everyone. Problem solved. Many thanks to Lydia, who helped me out. Just want to share the answer to anyone who might got into the same trouble like I did.
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/e1c43fdc-c3a1-4a6c-8026-4d18440acceb/only-partial-data-was-loaded-from-excel-source-to-oledb-destination?forum=sqlintegrationservices&prof=required


text:
Q: How many derangements are there of the word MATHEMATICAL? I know how to get the number of derangements for a word that has no repeating letters for example "guitar":
$$6!\left(\frac{1}{0!}-\frac{1}{1!}+\frac{1}{2!}-\frac{1}{3!}+\frac{1}{4!}-\frac{1}{5!}+\frac{1}{6!}\right)$$
I also know how to get the number of derangements of a word with one set of repeating letters, such as "bottle", as this has been answered in another post.
However, when there are MULTIPLE sets of repeating letters, as in "MATHEMATICAL" (2 M's, 2 T's, and 3 A's), it becomes a bit more complicated considering if the first M is in the second M's place, according to the formula it's a derangement, but it actually is not. Could anyone help me out with this? Thanks!


text:
Q: Subset function to study gender difference in R I want to study the gender difference and so I am attempting to use the R function but I don't know how to use it.
This is my script.
data<-read.csv(file.choose())
attach(data)
data

Subset
newdata <- subset(data, Gender=="1","2", select=Total)

A: data1 <- data[data$Gender=="1",] # data for gender "1"
data2 <- data[data$Gender=="2",] # data for gender "2"

For number of records in different gender:
data.gender <- data %>% group_by(Gender) %>% summarise(Count=n())


text:
Q: How can I get facebook photo like count in iPhone SDK? How can I get the count of facebook photo likes and dislikes in an iPhone application using graph api?
Thanks in advance.

A: Just call a new request with the FB object:
[facebook requestWithGraphPath:@"PHOTO_ID/likes"];

Replace PHOTO_ID with the Facebook ID of the photo you're interested in.  This call will return an array with all like information for that photo.
In the -facebook requestDidLoad: method, just get the count of that array to return the number of likes.
NSInteger likeCount = [result count];


text:
Q: Rails default routes through resources implementation resources :photos
Creates seven different routes, all mapping to the Photos controller.
GET       /photos
GET       /photos/new
POST      /photos
GET       /photos/:id
GET       /photos/:id/edit
PATCH/PUT  /photos/:id
DELETE    /photos/:id
But where is it defined in the rails application, from where it is picked automatically.
If we need to implement some routes the same way resources does, how can we do it?

A: To answer this question: If we need to implement some routes the same way resources does, how can we do it?:
From resources :photos, the following is how you can create individual routes:
get 'photos', to: 'photos#index'
post 'photos', to: 'photos#create'
get 'photos/new', to: 'photos#new'
get 'photos/:id/edit', to: 'photos#edit'
get 'photos/:id', to: 'photos#show'
patch 'photos/:id', to: 'photos#update'
put 'photos/:id', to: 'photos#update'
delete 'photos/:id', to: 'photos#destroy'

It's as simple as that. if you don't want all the routes that comes with resources, you can simply implement the ones you need.

A: When you use

resource :photos

rails generates automatically the CRUD routes that allow you to Create, Read, Update and Destroy photos.
Rails uses here a number of conventions for mapping those basic CRUD routes to the controller actions. For example, POST methods are associated to create() actions of your controllers.
This behavior is implemented in the module ActionDispatch::Routing::Mapper::Resources.
If you need to add a new route (for a new controller action) which is not part of the conventional CRUD set of actions, you need to specify it in the routes.rb file of your rails application.
You have two options:
a. The action affects a collection of Photo objects (similar to the index action). For this you need to add the route within the 'collection' block. This translates into a route without any :id parameter in the URL of the route.

resources :photos
  collection do
    get 'thumbnail'
  end
end

b. The action affect only Photo object (similar to edit and destroy actions). For this you need to add the route within the 'member' block and will make you available the :id param in the controller. The resulting URL of the route will need to specify the it in
/photos/:id/my_action

resources :photos
  member do
    get 'gallery'
  end
end

Please also have a look at http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions


text:
Q: Class inheriting from itself in python I am fairly new to object oriented programming and I am learning neural networks with pytorch.
I have seen some examples where the class in python will inherit from itself (sub and super class will have the same name). Can someone please explain to me how does it work? I have put a small code as an example below.
import torch.nn as nn

class LR(nn.module):
  def __init__(self, in_size, out_size):
    super(LR, self).__init__()
    self.linear = nn.Linear(in_size, out_size)

  def forward(self, x):
    out = self.linear(x)
    return out

I am auditing a pytorch course on coursera. The example is from the course. Here I am confused with the line super(LR, self)

A: You might be mistaken in your assumption that you're seeing classes inherit from themselves. In the example you've posted LR inherits from nn.module, and super(LR, self).__init__() will be calling nn.module's __init__ method.


text:
Q: How to keep widget at bottom of frame? My main window launches a top-level window with a sub-frame (to browse/select a directory) along with 'load' and 'add directory' buttons at the bottom. The 'add directory' button deletes all the directory entry subframes (but leaves the buttons), checks that there are no duplicates directories entered or empty strings, and recreates subframes for valid entries and creates another one left blank.
The problem is that when I click the 'add directory' button, the buttons end up on top. Is there a way to fix the buttons to the bottom of the window?
In Main class:
def add_directory
  dir_window = TkToplevel.new(@root) {title 'Directories'}
  dir_frame = Tk::Tile::Frame.new(dir_window) {padding "3 3 12 12"}.grid(:sticky => 'nsew')
  DirectoryFrame.show(dir_frame)
  loadDirectoriesButtonClicked = proc {load_files}
  Tk::Tile::Button.new(dir_frame) {text 'Load directories'; command loadDirectoriesButtonClicked}.grid(:column=>0, :sticky=>'s')
  addDirButtonClicked = proc {DirectoryFrame.show(dir_frame)}
  Tk::Tile::Button.new(dir_frame) {text '+'; width 2; command addDirButtonClicked}.grid(:column=>1, :sticky=>'sw')
end

In directory frame class:
class DirectoryFrame  < Tk::Tile::Frame
  @@directory_frames = []
  @@directories = []

    def self.show(parent_frame)
      if !(@@directory_frames.nil? || @@directory_frames.empty?)
      directories
      remove_frames(parent_frame)
    end
    @@directories.delete("")
    if !(@@directories.nil? || @@directories.empty?)
      @@directories.each do |dir|
        dir_frame = DirectoryFrame.new(parent_frame)
        dir_frame.directory = dir
        @@directory_frames << dir_frame
      end
    end
    @@directory_frames << DirectoryFrame.new(parent_frame)
    refresh
  end

  def self.refresh
    @@directory_frames.each_with_index do |dir_frame, index|
      dir_frame.grid(:row=>index, :sticky=>'ew')
    end
  end

A: If you don't specify which row to put a widget on when you grid it in, Tk picks the row with number one larger than the current largest used row number. This is often just fine, but is wrong for you. Instead, you should explicitly put your buttons in a row with a large number (e.g., 1000), and then have a counter of inserted rows that you use to decide which new explicit row to do the insertion on.

+--------------------+
| row 1              |
+--------------------+
| row 2              |
+--------------------+
| row 3              |
+--------------------+
| ... empty ...      |
+--------------------+
| row 1000           |
+--------------------+

The other alternative is to put the buttons in a frame with another inner frame that holds the gridded space that you are adding rows into.

+----------------------+
|+--------------------+|
|| row 1              ||
|+--------------------+|
|| row 2              ||
|+--------------------+|
|| row 3              ||
|+--------------------+|
+----------------------+
| buttons              |
+----------------------+

Either technique will work.


text:
Q: How can I create a associated token address in solana from connected wallet address? I want to create an associated token address in Solana from a connected wallet address. This is my code currently:
import { useWallet, useConnection } from "@solana/wallet-adapter-react";

 ...

  const wallet = useWallet();

  const { publicKey, sendTransaction } = wallet;

const associatedAccount = await getAssociatedTokenAddress(
            mintPubkey,
            wallet.publicKey
          );
          const transaction = new Transaction().add(
            createAssociatedTokenAccountInstruction(
              wallet.publicKey,
              associatedAccount,
              wallet.publicKey,
              mintPubkey,
              TOKEN_2022_PROGRAM_ID,
              ASSOCIATED_TOKEN_PROGRAM_ID
            )
          );
       signature = await sendTransaction(transaction, connection, {
          skipPreflight: true,
        });

        await connection.confirmTransaction(signature, "confirmed");

...

But the tx is keep failing like this:
https://solscan.io/tx/ZaQtfVkNkkAweGug2JfDYz8hcFXh4jDUEJoz2Lik6jPv8huFgzpMXMwui51VJsk8yHmpcWUD6UgnqdmRhu4Covh?cluster=devnet
How can I achieve this?

A: Because you use Token-2022, you need to specify it when generating the associatedAccount address. Otherwise it uses the default Token Program.
Documentation: getAssociatedTokenAddress()
const associatedAccount = await getAssociatedTokenAddress(
   mintPubkey,
   wallet.publicKey,
   false,
   TOKEN_2022_PROGRAM_ID,
);


text:
Q: shell script: can't cd to i need an help, i want to make a webpage that allow to start/stop/restart a program on the server where there is the website.
my html:

  JTS

   <form action="JTSstart.php">
   <input type="submit" value="START">
   </form>

   <form action="JTSres.php">
   <input type="submit" value="RESTART">
   </form>

   <form action="JTSstop.php">
   <input type="submit" value="STOP">
   </form>

my php:

<?php
echo shell_exec('sh JTSres.sh');
sleep(5);
header("Location: 5ondimba.html");
?>

and my sh:

#!/bin/bash
cd ~/home/otaku/JTS_HostingEdition
./jts_startscript.sh restart

now.. when i click on one of all button's nothing happens and on the error.log in /var/log/apache2, it say:
JTSres.sh: 2: cd: can't cd to /home/otaku/JTS_HostingEdition

i try to search something on stackoverflow but nothing can help me.
what i can try to do?
thanks for all!

A: You need to change the permissions on all the directories, and the script, so that the webserver can access them.
chmod a+rx /home/otaku /home/otaku/JTS_HostingEdition /home/otaku/JTS_HostingEdition/jts_startscript

BTW, using ~ in a script that can be run by different users doesn't make much sense, since that expands to the user's own home directory. You should use the absolute path of the directory you want to change to. It seems like this is only finding the correct path because the webserver's home directory is the root directory, so ~/home is the same as /home.
Also, if the JTSres.sh is a bash script, you should run it with bash, not sh.
echo shell_exec('bash JTSres.sh');

Or make the script executable and use:
echo shell_exec("./JTSres.sh");


text:
Q: displaying markers on a google map in javascript I am a Javascript beginner and I am trying to create markers on a google map. So first of all I am getting GPS co-ordinates from a database which I am splitting apart to get the lattitude and longlitude values, then I am adding them to 2 separate listboxes called lstBoxLatGPS and lstBoxLongGPS in c#
foreach (string item in GPSLatList)
    {
        lstBoxLatGPS.Items.Add(item);
    }
foreach (string item in GPSLongList)
    {
        lstBoxLongGPS.Items.Add(item);
    }

Now in Javascript I want to take the items in the listboxes and create markers on the map I have 2 functions:
        function GetLatValues()
        {
            var arrValues= new Array();
            var listBox = document.getElementById("<%=lstBoxLatGPS.ClientID%>");
            for (var i = 0; i < listBox.options.length; i++)
            {arrValues[i]= listbox.options[i].text }
            return (arrValues);
        }
        function GetLongValues()
        {
            var arrValues= new Array();
            var listBox = document.getElementById("%=lstBoxLongGPS.ClientID%>");
            for (var i = 0; i < listBox.options.length; i++)
            {arrValues[i]= listbox.options[i].text }
            return (arrValues);
        }

then to add the arrays to made the markers:
        function initialize()
        {
            var mapCanvas = document.getElementById('map-canvas');
            var mapOptions =
            {
                center: new google.maps.LatLng(-28.4792811, 24.6722268),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(mapCanvas, mapOptions);
            map.set('styles', [
  {
      "featureType": "landscape",
      "stylers": [
        { "color": "#c9d7bb" }
      ]
  }, {
      "featureType": "administrative.province",
      "elementType": "labels.text",
      "stylers": [
        { "visibility": "on" },
        { "color": "#ffc23d" }
      ]
  }, {
      "featureType": "poi.attraction",
      "stylers": [
        { "visibility": "on" },
        { "color": "#9be586" }
      ]
  }, {
      "featureType": "administrative.province",
      "elementType": "geometry",
      "stylers": [
        { "visibility": "on" },
        { "color": "#000000" },
        { "weight": 3.2 }
      ]
  }
            ]);

            var GPSLatArray = new Array();
            var GPSLongArray = new Array();
            GPSLatArray = GetLatValues();
            GPSLongArray = GetLongValues();

            for (var i = 0; i < GPSLatArray.length; i++)
            {
                var marker = new google.maps.Marker({position: GPSLatArray[i],GPSLongArray[i] });
                marker.setMap(map);
            }
        }
        google.maps.event.addDomListener(window, 'load', initialize);

When the map is supposed to be displayed, it is just blank, not showing the map at all.

A: You need to add a div in your aspx page to display the map.

A: I used Artem.Google package to create the map and now it's working.


text:
Q: Java EE inter-application communication We are developing several separate applications/modules, that we deploy onto Glassfish 3.1.1 application server. There are cases where these applications need to call each others methods, through a remote interface. What is the best practice when it comes to packaging these remote interfaces? E.g. if A needs to call B's remote interface, would you extract B's remote interface in a separate JAR file and package it together with module A? What if this remote interface references an entity class. Would you package this entity class together with the interface in this JAR file?
If you have any feedback on this topic, feel free to suggest how you think this should be done.

A: I spent my last job solving this exact problem.
This is what EJBs are designed to do. An EJB has both an implementation and an interface. The interface goes into a client jar that is used by your applications:
@EJB
MyService myService;

The implementation is packaged separately and installed somewhere else your server:
@Stateless
@Remote({MyService.class})
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class MyServiceBean implements MyService {
...
}

You should not have applications calling each other directly in Java EE! (But you can, in some cases) Think of EJBs as extremely lightweight, single purpose services, where you extract common business logic between your apps.
Your question sounds like a circular dependency situation where AppA calls AppB and AppB calls AppA. Extract the business logic AppA and AppB are using from AppA and put it into and EJB. Do the same for AppB. Now you have 2 apps and 2 EJBs, where common business logic can be called from either app.
Easy, right? Let me know how to explain this better!


text:
Q: Is scaffolding only used to create a CRUD? In ASP.NET MVC is scaffolding only ever used to create a CRUD view based off an existing model?

A: By default, yes.

You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.

However:

Visual Studio 2013 Update 2 (currently RC) provides the ability to extend ASP.NET Scaffolding to meet the requirements of your scenario.

A: To some extent it is customizable.
Creating a Custom Scaffolder for Visual Studio
How to customize the generated files from the New Scaffolded Item dialog


text:
Q: How do I send key events to a Flash movie in WebKit? I am trying to create a site-specific browser application. I've created a new Cocoa app, added a WebView to my window, and am loading up the page. The page contains a Flash movie, which can be controlled via the keyboard. I'd like to wire up some menu commands to trigger the actions, presumably by simulating the keystrokes.
I've traversed the view hierarchy and have found the NSView that contains the movie (with class name "WebHostedNetscapePluginView"). But I'm stuck at the point of sending it keys. I tried using CGEventCreateKeyboardEvent() but the input keeps going to the top-level WebView rather than the subview containing the movie.
I tried [[webView window] makeFirstResponder: _myView] to set the target for the input.
Is CGEventCreateKeyboardEvent() the right function here and, if so, how do I get it to my target NSView?
Many thanks in advance.

A: My original answer would only work if the window was active. I also wanted it to work when the window was hidden, and came up with the code below.
This works for ordinary keys (Enter, Space, arrow keys, etc.). It uses keycodes so it won't work for letters and symbols that might move around based on the user's language and region.
And it doesn't handle modifier keys like Command. If someone can figure that out I will gladly give them credit for the answer to this question.
// For Safari 4.x+
if ([[flashView className] isEqual:@"WebHostedNetscapePluginView"])
{
    CGEventRef event = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keycode, true);
    [flashView keyDown:[NSEvent eventWithCGEvent:event]];
    CFRelease(event);
}
else
{
    EventRecord event;
    event.what      = keyDown;
    event.message   = keycode << 8;
    event.modifiers = 0;

     // For Safari 3.x
    if ([flashView respondsToSelector:@selector(sendEvent:)]) {
        [(id)flashView sendEvent:(NSEvent*)&event];
        event.what = keyUp;
        [(id)flashView sendEvent:(NSEvent*)&event];
    }

    // For Safari 4.x
    else if ([(id)flashView respondsToSelector:@selector(sendEvent:isDrawRect:)]) {
        [(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
        event.what = keyUp;
        [(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
    }
    else
    {
        NSLog(@"ERROR: unable to locate event selector for Flash plugin");
    }
}

You must first locate the Flash widget in the browser; pass your WebView to this.
- (NSView*)_findFlashViewInView:(NSView*)view
{
    NSString* className = [view className];

    // WebHostedNetscapePluginView showed up in Safari 4.x,
    // WebNetscapePluginDocumentView is Safari 3.x.
    if ([className isEqual:@"WebHostedNetscapePluginView"] ||
        [className isEqual:@"WebNetscapePluginDocumentView"])
    {
        // Do any checks to make sure you've got the right player
        return view;
    }

    // Okay, this view isn't a plugin, keep going
    for (NSView* subview in [view subviews])
    {
        NSView* result = [self _findFlashViewInView:subview];
        if (result) return result;
    }

    return nil;
}

A: Did you make sure that the Flash element has (HTML) keyboard focus?

A: I managed to figure it out. Here's the code:
[[self window] makeFirstResponder:_tunerView];

CGEventRef e1 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)49, true);
CGEventPost(kCGSessionEventTap, e1);
CFRelease(e1);

CGEventRef e2 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)49, false);
CGEventPost(kCGSessionEventTap, e2);
CFRelease(e2);

window is the main application window. _tunerView is the WebHostedNetscapePluginView. I was setting the first responder when the window first opened, that didn't work. I have to set it right before I send the keys.


text:
Q: libvirt Apparmor permission denied when accessing qemu socket I was trying to use ivshmem device of qemu, after running the server, I can succesfully create a vm with command:
sudo qemu-system-x86_64 -m 1024 -hda testvm01.img -enable-kvm \
-device ivshmem-doorbell,vectors=1,chardev=ivshmem \
-chardev socket,path=/tmp/ivshmem_socket,id=ivshmem

Then I want to use libvirt to boot the vm, and my configuration file as follows:
<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
  <name>testlinux1</name>
  <memory unit='KiB'>1048576</memory>
  <currentMemory unit='KiB'>1048576</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-bionic'>hvm</type>
  </os>
  <devices>
    <emulator>/usr/bin/qemu-system-x86_64</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw'/>
      <source file='/home/gavin/vms/testvm01.img'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
  </devices>
  <qemu:commandline>
    <qemu:arg value='-device'/>
    <qemu:arg value='ivshmem-doorbell,vectors=2,chardev=ivshmem'/>
    <qemu:arg value='-chardev'/>
    <qemu:arg value='socket,path=/tmp/ivshmem_socket,id=ivshmem'/>
  </qemu:commandline>
</domain>

When I try to create the vm with command virsh create testlinux1.xml, I get the error:
error: Failed to start domain testlinux1
error: internal error: process exited while connecting to monitor: 2018-07-19T22:12:52.443682Z qemu-system-x86_64: -chardev socket,path=/tmp/ivshmem_socket,id=ivshmem: Failed to connect socket /tmp/ivshmem_socket: Permission denied

I have seen the same question at: Using IVSHMEM with libvirt virt-manager
I can not follow the solution there since I failed to create the vm, there is no  libvirt-<uuid> file under /etc/apparmor.d/libvirt, and I have no way to change AppArmor mode to complain with sudo aa-complain libvirt-<uuid> //replace <uuid> with uuid of vm.
Can anyone helps me figure out how to change the mode to complain before creating the file? Thank you very much!

A: You can put AppArmor in complain mode for libvirt:
aa-complain /usr/sbin/libvirtd

This disables the security, so may not be the best solution.


text:
Q: Cannot get the expected target shape in keras I am new to sequential models. I am working on an image caption generator with attention model in Keras.
I keep getting an error with the expected target shape in Keras. I have worked on basic models before. And for this kind of error, usually there's a mistake with the way I process my dataset.
However, in this case, I have tried adjusting the shape of my 'y' array by unpacking it, or by trying to pack my 'outputs' list. But it doesn't change the error message.
def model(photo_shape, max_len, n_s, vocab_size):
  outputs=list()
  seq=Input(shape=(max_len,), name='inseq')#max_len is 33.
  x = Embedding(vocab_size, 300,mask_zero=True)(seq)

  p=Input(shape=(photo_shape[0],photo_shape[1]),name='picture')
  s,_,c=LSTM(n_s,return_state = True)(p)
  for t in range(max_len):
    context = attention(p,s)
    word=Lambda(lambda x: x[:,t,:])(x)
    context = concat([word,context])
    context=reshape(context)
    s,_,c = lstm(context)
    out = den2(s) #return a dense layer with vocab_size units(none, 2791).
    outputs.append(out)
    #print(np.array(outputs).shape) => returns (33,)
  model = Model(inputs=[seq,p],outputs=outputs)
  return model

#the following method goes to a generator function.
def build_sequences(tokenizer, max_length, desc_list, photo):
  X1, X2, y = list(), list(), list()
  desc = desc_list[0]
  seq = tokenizer.texts_to_sequences([desc])[0]
  l=len(seq)
  in_seq, out_seq = seq[:l-1], seq[1:l]
  in_seq = pad_sequences([in_seq],padding='post', maxlen=max_length)[0]
  out_seq =[to_categorical([w], num_classes=vocab_size)[0] for w in out_seq]
  out_seq = pad_sequences([out_seq],padding='post', maxlen=max_length)[0]
  X1.append(in_seq)
  X2.append(photo)
  y.append(out_seq)
  return np.array(X1), np.array(X2), np.array(y)

The error I get is this.
ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 33 array(s), but instead got the following list of 1 arrays: [array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0,...

The debug messages show the following shapes for my inputs and outputs.
in_seq: (1, 33)
photo: (1, 196, 512)
out_seq: (1, 33, 2971)

The first is the batch size, which should not be taken into consideration. So, I do not know why the 33 is not visible to keras. I have tried modifying this shape. But logically, should this not work?
Please let me know if this is a data processing error or a problem with my model structure!
Let me know if more code is required


text:
Q: Intuition: expected value formula of a continuous random variable and Riemann sums In my introductory probability class the expected value was given just by definition as
$$E[X] = \int_{-\infty}^{+\infty} xf(x) dx$$
with $f(x)$ representing the probability density function of the distribution.
But I was thinking about a way to correlate the idea in the discrete case with the one in the continuous case as follows (consider that I haven't studied measure theory yet) :
Form a partition of a interval $[a,b]$  so that $a=x_0 < x_1 < ... < x_n = b$ then we write the Riemann sum
$$\sum_{i=0}^{n-1} (x_{i+1}-x_{i}) x^* f(x^*)$$
with every $x^* \in [x_{i},x_{i+1}]$.
But now since $(x_{i+1}-x_{i}) f(x^*) \approx P(x_i<x<x_{i+1})$ and this approximation will improve more the points are close, we have something like the discrete case because
$$\sum_{i=0}^{n-1} (x_{i+1}-x_{i}) x^* f(x^*) \approx \sum_{i=0}^{n-1} x^*P(x_i<x<x_{i+1}) $$
More the points of the partition increase more a single point $x^*$ becomes the ''right'' value to multiply with $P(x_i<x<x_{i+1}) $ to obtain the expected value , and it's known that the left hand side becomes $\int_{a}^{b} xf(x) dx$, then letting $a \rightarrow -\infty$ and $b \rightarrow +\infty$ we are done.
I think the main problem with this reasoning is the interpretation of $x^*$ to become eventually the ''right'' value.
Do you consider this reasoning a valid intuition for the expected value?Thanks in advance


text:
Q: Select / Deselect All Checkboxes not working in dynamic table row with this code below I just trying to select/deselect all check boxes in table row, normally with this jquery code working fine in static table but not working in dynamic table where row generate with foreach. I really didn't find out that what I missed actually as I'm new with this.
jquery:
 $('#chkall').click(function(event) {  //on click
                if(this.checked) { // check select status
                    $('.TID').each(function() { //loop through each checkbox
                        this.checked = true;  //select all checkboxes with class "checkbox1"
                    });
                }else{
                    $('.TID').each(function() { //loop through each checkbox
                        this.checked = false; //deselect all checkboxes with class "checkbox1"
                    });
                }
            });

View page:
<form role="form" action="<?php echo base_url(); ?>attendance/statusUpdate/" method="post" name="attendance" id="attendance">

                        Sl#
                        Trainee ID
                        Trainee Name
                        Date
                        In Time
                        Out Time
                        Status
                        Withdraw
                        <?php
                        if (isset($userinfo) and ( $userinfo->Role == 1)) {
                        ?>
                        Allow <input type='checkbox' name='chkall' id='chkall'>
                        Remarks
                        <?php
                        }
                        ?>

                        Session #

                        Faculty:

                        <?php
                        if (isset($userinfo) and ( $userinfo->Role == 1)) {
                        ?>

                        <?php
                        }
                        ?>

                <?php
                $i = 0;
                foreach($attendance as $row){
                    $i++;
                    if ($row->Status=='Late-In' or $row->attnDate == null) {
                        $style='red';
                    }else{
                        $style='black';
                    }
                ?>
                    <tr style="color:<?php echo $style?>"><?=$i?>
                        <?=str_pad($row->TraineeID, 7, "0", STR_PAD_LEFT)?>
                        <?=$row->Name?>
                        <?=$row->attnDate?>
                        <?=$row->inTime?>
                        <?=$row->outTime?>
                        <?=$row->Status?>
                        <?=$row->Reason?>
                        <?php
                        if (isset($userinfo) and ( $userinfo->Role == 1)) {
                        ?>

                            <input type='checkbox' name='TraineeID[]' class="TID" id="TID" value="<?=$row->TraineeID ?>"
                            <?php if($row->Status==='Late-In')
                                {
                            ?>
                                unchecked>
                            <?php
                                }else if($row->Status==='Present'){
                            ?>
                               checked>
                            <?php
                                }
                            ?>

                            <input type="text" name="remarks[]" id="remarks">

                        <?php
                        }
                        ?>
                <?php
                }
                ?>

    <?php
    }
    ?>

        </form>

A: $('#chkall').click(function(event) {  //on click
     if(this.checked) { // check select status
          $('#tabledata .TID').each(function() { //loop through each checkbox
               this.checked = true;  //select all checkboxes with class "checkbox1"
          });
     }else{
          $('#tabledata .TID').each(function() { //loop through each checkbox
               this.checked = false; //deselect all checkboxes with class "checkbox1"
          });
     }
});

I think you need to bind the event to a static object in the page for example: #tabledata

A: Try $("input.TID").prop('checked', true); and $("input.TID").prop('checked', false);
Remove
$('#tabledata .TID').each(function() {});


text:
Q: Como posso fazer uma div desaparecer quando clico num botão Então eu tenho um pagina e queria fazer um daqueles menus tops que quando clico ele faz aparecer o menu mas não sei como fazer com que a minha div all que inclui quase tudo do html desapareça!
Meu código:

body{
  margin-left: 0px;
  margin-right: 0px;
  margin-top: 0px;
  margin-bottom: 0px;
  background: #252C35;
  color: white;
}

#UpperBar{
  height: 45px;
}

.MASlime{
  position: absolute;
  font-size: 30px;
  top: 1px;
  left: 40px;
}

#Totals{
  position: absolute;
  font-size: 30px;
}

.Total{
  position: absolute;
  top: 80px;
  left: 140px;
}

.TotalEarnings{
  position: absolute;
  top: 80px;
  left: 200px;
}

.TotalO{
  position: absolute;
  top: 150px;
  left: 140px;
}

.TotalOrders{
  position: absolute;
  top: 150px;
  left: 200px;
}

#Earnings{
  position: absolute;
  top: 80px;
  left: 350px;
}

#Orders{
  position: absolute;
  top: 150px;
  left: 350px;
}

.NewOrder{
  position: absolute;
  top: 250px;
  left: 200px;
  font-size: 30px;
}

.OrderName{
  position: absolute;
  top: 350px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.OrderDate{
  position: absolute;
  top: 400px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SKU{
  position: absolute;
  top: 450px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SUBMIT{
  position: absolute;
  top: 500px;
  left: 220px;
  width: 100px;
  height: 40px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.Menu{
  position: absolute;
  top: 25px;
  left: 480px;
  font-size: 30px;
  cursor: pointer;
}

.menu{
  text-align: center;
  width: 100%;
  display: none;
}

.menu a{
  display: block;
  border-bottom: 1px solid #EAEAED;
  text-decoration: none;
  color: white;
  margin-top: 70px;
  padding-bottom: 10px;
  font-size: 30px;
  background: #252C35;
}

.All{
  display: block;
}

#toggle{
  display: none;
}

#toggle:checked + .menu{
  display: block;
}

#toggle:checked ~ .All{
  display: none;
}
    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>EComerce App Slime</title>
        <link rel="stylesheet" href="css/index.css">

          ☰
          <input type="checkbox" id="toggle"/>

              Slime Recipe

MASlime

Total

Earnings

Total

Orders

100€

1

New Order

              <form id="OrderForm">
                <input class="OrderName" type="text" name="OrderName" placeholder="Buyer Name" required>
                <input class="OrderDate" type="text" name="OrderDate" placeholder="Date of Order" required>
                <input class="SKU" type="text" name="ProductSKU" placeholder="Product SKU" required>
                <input class="SUBMIT" type="button" name="Submit" value="SUBMIT">
              </form>

Print do problema:

A: No seu HTML:
<input type="checkbox" id="toggle"/>

Altera para:
<input type="checkbox" id="toggle" onclick="meuMenuToggle()"/>

E no HTML

Altera para:

E insere o código do javascript abaixo do seu conteúdo HTML antes de

Assim quando você clicar no menu, o conteúdo será oculto, e ao clicar no menu para fechar, o conteúdo será descoberto.
Entendendo: a função javascript meuMenuToggle(); verifica se não existe e é verdadeiro o estilo display='none'; se é TRUE, a função insere o estilo na DIV que foi identificada na variável 'x' através do ID do elemento pego ("divAll"), na alteração sugerida acima (
).
O evento de abrir o mouse alterna a DIV para display none, e alterna para display block quando clica novamente no menu.

A: Segue a opção apenas como CSS como vc queria.

Eu fiz como comentei, coloquei uma div a mais que fica oculta, chamei ela de .backdrop, assim quando a label ativa o checkbox eu mostro essa div e ela encobre todo o conteúdo que vem abaixo, dando a impressão que ele sumiu.

    body {
      margin-left: 0px;
      margin-right: 0px;
      margin-top: 0px;
      margin-bottom: 0px;
      background: #252C35;
      color: white;
    }

    #UpperBar {
      height: 45px;
      top: 1px;
      left: 40px;
      position: absolute;
      z-index: 2;
    }

    .MASlime {
      position: absolute;
      font-size: 30px;
    }

    #Totals {
      position: absolute;
      font-size: 30px;
    }

    .Total {
      position: absolute;
      top: 80px;
      left: 140px;
    }

    .TotalEarnings {
      position: absolute;
      top: 80px;
      left: 200px;
    }

    .TotalO {
      position: absolute;
      top: 150px;
      left: 140px;
    }

    .TotalOrders {
      position: absolute;
      top: 150px;
      left: 200px;
    }

    #Earnings {
      position: absolute;
      top: 80px;
      left: 350px;
    }

    #Orders {
      position: absolute;
      top: 150px;
      left: 350px;
    }

    .NewOrder {
      position: absolute;
      top: 250px;
      left: 200px;
      font-size: 30px;
    }

    .OrderName {
      position: absolute;
      top: 350px;
      left: 140px;
      width: 250px;
      height: 25px;
      background-color: #252C35;
      color: white;
      border: 1px;
      border-style: solid;
      border-radius: 5px;
      border-color: white;
      padding: 5px;
    }

    .OrderDate {
      position: absolute;
      top: 400px;
      left: 140px;
      width: 250px;
      height: 25px;
      background-color: #252C35;
      color: white;
      border: 1px;
      border-style: solid;
      border-radius: 5px;
      border-color: white;
      padding: 5px;
    }

    .SKU {
      position: absolute;
      top: 450px;
      left: 140px;
      width: 250px;
      height: 25px;
      background-color: #252C35;
      color: white;
      border: 1px;
      border-style: solid;
      border-radius: 5px;
      border-color: white;
      padding: 5px;
    }

    .SUBMIT {
      position: absolute;
      top: 500px;
      left: 220px;
      width: 100px;
      height: 40px;
      background-color: #252C35;
      color: white;
      border: 1px;
      border-style: solid;
      border-radius: 5px;
      border-color: white;
      padding: 5px;
    }

    .Menu {
      position: absolute;
      top: 25px;
      left: 480px;
      font-size: 30px;
      cursor: pointer;
      z-index: 3;
    }

    .menu {
      text-align: center;
      width: 100%;
      display: none;
    }

    .menu a {
      display: block;
      border-bottom: 1px solid #EAEAED;
      text-decoration: none;
      color: white;
      margin-top: 70px;
      padding-bottom: 10px;
      font-size: 30px;
      background: #252C35;

      z-index: 3;
      position: relative;
    }

    .All {
      display: block;
    }

    #toggle {
      display: none;
    }

    #toggle:checked+.menu,
    #toggle:checked~.backdrop {
      display: block;
    }

    #toggle:checked~.All {
      /* display: none; */
    }

    .backdrop {
      position: fixed;
      width: 100%;
      height: 100%;
      background-color: #252C35;
      top: 0;
      left: 0;
      z-index: 1;
      display: none;
    }

    #menu {
      /* position: relative; */
      z-index: 2
    }

    ☰
    <input type="checkbox" id="toggle" />

        Slime Recipe

MASlime

Total

Earnings

Total

Orders

100€

1

New Order

            <form id="OrderForm">
                <input class="OrderName" type="text" name="OrderName" placeholder="Buyer Name" required>
                <input class="OrderDate" type="text" name="OrderDate" placeholder="Date of Order" required>
                <input class="SKU" type="text" name="ProductSKU" placeholder="Product SKU" required>
                <input class="SUBMIT" type="button" name="Submit" value="SUBMIT">
            </form>

A:

 var display = document.getElementById("aqui vai o id da div").style.display;
        if(display == "none")
            document.getElementById("aqui vai o id da div").style.display = 'block';
        else
            document.getElementById("aqui vai o id da div").style.display = 'none';


text:
Q: How to get all pages and fans count from user facebook account throght facebook graph api? I want to get all the Facebook pages and their fan count of user accounts using Facebook graph API, I also create one app in Facebook developer account, but then after don't know what to do to get page list?
So, can someone help me to write the correct PHP code to retrieve the page list?
I had some code as below :
     $json_url ='https://graph.facebook.com/'.$page_id.'?access_token='.$fb_api_key.'|'.$fb_api_secret.'&fields=fan_count';
$json = @file_get_contents($json_url);

    $json_output = json_decode($json);

    //Extract the likes count from the JSON object
    if($json_output->fan_count){
      echo $fan_count = $json_output->fan_count;
    }else{
      echo 0;
    }`


text:
Q: Typescript unable to import fileReader How do i import FileReader in typescript. I tried this:
var reader:FileReader = new FileReader();

my tsconfig.json
{
"compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "outDir": "out",
    "lib": [
        "es6"
    ],
    "sourceMap": true,
    "rootDir": "."
},
"exclude": [
    "node_modules",
    ".vscode-test"
]
}

My error is cannot find name 'FileReader' I am unable to do this too:
import FileReader;

A: I ran into this issue as I forgot to add "dom" to the "lib" node in the tsconfig.json.
Fix:
In your tsconfig.json ensure under "lib" you have "dom". Here is my current tsconfig.json
{
   "compilerOptions": {
      "lib": [
         "dom",
         "dom.iterable",
         "esnext",
         "es5",
         "es6"
      ],
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   }
}

See the below ugly themed VS code the lib.dom.d.ts is where the FileReader interface lives which made me realise I was missing "dom"


text:
Q: Accessing the subscription/num_oustanding_messages metric in Google PubSub from Python Is it possible to access the subscription/num_outstanding_messages metric listed https://cloud.google.com/monitoring/api/metrics#gcp-pubsub from google-cloud-python? I've used similar code to successfully access the num_undelivered_messages metric, but iterating over the results of the following query (which succeeds) always yields an empty list.
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from google.cloud import monitoring
>>> client = monitoring.Client()
>>> q = client.query(
...     "pubsub.googleapis.com/subscription/num_undelivered_messages",
...     minutes=90
... )
>>> len(list(q)) > 0
True
>>> q = client.query(
...     "pubsub.googleapis.com/subscription/num_outstanding_messages",
...     minutes=90
... )
>>> len(list(q)) > 0
False

Relevant google-cloud-python library versions:
~:pip freeze | grep google
gapic-google-logging-v2==0.10.1
gapic-google-pubsub-v1==0.10.1
google-cloud==0.21.0
google-cloud-bigquery==0.21.0
google-cloud-bigtable==0.21.0
google-cloud-core==0.21.0
google-cloud-datastore==0.21.0
google-cloud-dns==0.21.0
google-cloud-error-reporting==0.21.0
google-cloud-happybase==0.20.0
google-cloud-language==0.21.0
google-cloud-logging==0.21.0
google-cloud-monitoring==0.21.0
google-cloud-pubsub==0.21.0
google-cloud-resource-manager==0.21.0
google-cloud-runtimeconfig==0.21.0
google-cloud-storage==0.21.0
google-cloud-translate==0.21.0
google-cloud-vision==0.21.0
google-gax==0.14.1
googleapis-common-protos==1.5.0
grpc-google-iam-v1==0.10.1
grpc-google-logging-v2==0.10.1
grpc-google-pubsub-v1==0.10.1

A: The num_outstanding_messages, which represents the number of messages sent to a subscriber that have not yet been acknowledged, is only available for push subscribers. Note that although the API does not make this distinction explicit, in Stackdriver, the metric shows up as "push outstanding messages." The Subscriber Guide talks about the difference between a push subscriber and a pull subscriber.


text:
Q: list starts loading from the beginning after screen rotation In my fragment I have list. This list is is constantly filling. But after screen rotation list starts loading from the beginning. And the data that was in the vertical orientation is lost because in the horizontal orientation the list starts to load again. So, I added all what I could read in the internet:
in my Manifest file:
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"

in Activity class:
if (savedInstanceState == null) {
            firstFragment = FirstFragment()
            supportFragmentManager
                .beginTransaction()
                .add(R.id.frameLayout, firstFragment!!, "firstFragment")
                .commit()
        } else {
            firstFragment = supportFragmentManager
                .findFragmentByTag("firstFragment") as? FirstFragment
        }

but it did not help.

A: Please set setRetainInstance(true); in fragment code.
It will prevent recreating fragment instance.


text:
Q: Is there an autoincrement-per-user field in Django? I was wondering if there is already a way to create a separate autoincrement-ID-per-user field in Django?
Basically, I'm storing many related models and I need the IDs generated to be autoincrement per user.
I don't want to change how id works, just need a new field that I can add which is unique=True per user.
Any suggestions (other than overriding save and implementing it myself)?

A: No, there's no such field, but I wonder why you think you need it. The ID is really just for the model's internal use, you shouldn't ever care what it is.
For example, if you want to know how many related items there are for a user then you would just use the count() method on the related queryset. If you want something to be unique per user, you can use the unique_together meta property.
Can you given an example of a use case for a per-user unique id?
Edited in response to comments: to get the object from a URL as you mention, you just need to do:
myuser.myobject_set.all()[7]


text:
Q: How to Send a MultipartForm Request I have constructed a multipart form with this type:
 val formData = MultipartFormData[TemporaryFile]

I want use WSClient to post this form data but the type that the post method takes is:
  def post(body: Source[MultipartFormData.Part[Source[ByteString, _]], _]): Future[Response]

How do I convert my formdata to match this type so I can use this post method?


text:
Q: Not able to get value from select list in change event I have an array of select lists (dropdown boxes) in which i am using knockouts event binding to trigger a change event.  I have a function where I am trying to grab the value when a different option is selected from the drop down list, however it is always returning the first value in my observablearray.  Here is a walk thru of what I am doing-
Here is the select list in my view:

          <select id="ddlLCLoans" tabindex="4" style="width: 120px" data-bind=" optionsCaption: 'Choose...', options: $data.FilteredLCLoans,
optionsValue: 'LoanNum', optionsText: 'LoanNumCurrency', validationOptions: { insertMessages: false }, event: { change: $parent.LCLoanSelectionChanged }, value: $data.LCLoan, disable: $parent.disableButtons">
           </select>

In my viewmodel, I have the following variable used to generate the observables:
         var buildRow = function (LCLoans) {
        var self = this;
        var obj = {
            LCLoan: ko.observable(LCLoan).extend({ insertMessages: false, messagesOnModified: false, required: { onlyIf: validate, message: '
 LC Loans is Required' } }),

            FilteredABLoans: ko.observableArray(ABLoans())
        };

            // Add to object after obj is created so we can use that instance
            // using "this" to read the items DocStandby value
            obj.FilteredLCLoans = ko.computed(function () {

                return LCLoans().filter(function (item) {
                    return item.LoanSubType() === obj.DocStandby();
                });
            }, obj);

        obj.errors = ko.validation.group(obj);
        return obj;
    };

The select list in the view uses fields from the filteredLCLoans observable for optionsValue (LoanNum) and optionsText (LoanNumCurrency).  Here is the model that populates filteredLCLoans:
         var ClientsModel = function (clientID, LoanNum, LoanSubType, LoanNumCurrency, CurrType) {
        var self = this;

        self.clientID = ko.observable(clientID);
        self.LoanNum = ko.observable(LoanNum);
        self.LoanSubType = ko.observable(LoanSubType);
        self.LoanNumCurrency = ko.observable(LoanNumCurrency);
        self.CurrType = ko.observable(CurrType);
    };

The select list also refers to the function called LCLoanSelectionChanged.  This is where I am trying to grab the NEW selected value when the user selects a different option from the select list.  Here is that function:
 var vm = {
        activate: activate,
        LCLoanSelectionChanged: function (row) {

            var newValue = row.FilteredLCLoans.LoanNum;
        }
  };

    return vm;

How do I get the newly selected value?  If i put a breakpoint and use jQuery (var newValue = $('#ddlLCLoans option:selected').val())  I always get the first instances value of the ddlLCLoans in my view.  I know the "var newValue = row.FilteredLCLoans.LoanNum" above does not work, just not sure how to code it correctly.

A: subscribing was definately the way to go.  Here is code-
                    var currtype = '';
                    ko.utils.arrayForEach(LoanDetails(), function (itemLoan) {
                        itemLoan.LCLoan.subscribe(function (newLoan) {
                           alert(newLoan);
                        });
                 });

Compare that to the html in my view above and you can see this really simplified things.
Thanks Patrick Steele!


text:
Q: How can I check if a txt file only contains whitespaces with open('save.txt', 'r') as fname:
    data = fname.readlines()
    print(data)
    x = str(data)
    if x.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

I have tried this but it seems it doesnt work. I want to detect if a txt file only contains whitespaces and also /n if it is possible.

A: The method readlines() returns a list with every single line.
What you want is the read() method, which returns a single string for the whole file. The code would look like this:
with open('save.txt', 'r') as fname:
    data = fname.read()
    print(data)
    if data.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

Also, isspace() already considers \n and \t as whitespace.

A: readlines() returns a list of strings. You need to check the element of data, not simply convert the list to str.
with open('save.txt', 'r') as fname:
    data = fname.readlines()
    only_whitespace = all(line.isspace() for line in data)
    if only_whitespace:
        print("only whitespaces")
    else:
        print("not only whitespaces")

A: If you want to detect all whitespace characters (space, newline, tab, vertical space, carriage return...), then isspace might work for you, just read the file as a single string:
with open('save.txt', 'r') as fname:
    data = fname.read()
    print(data)
    if data.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

If you really only want space and newline, you could use a set operation:
with open('save.txt', 'r') as fname:
    data = set(fname.read())
    print(data)
    if data.issubset({' ', '\n'}):
        print("only whitespaces")
    else:
        print("not only whitespaces")


text:
Q: implecations of fetching and decoding two instructions simultaniously Instruction is fetched and decoded one at a time usually per cycle.
I was wondering what are the implications if we fetch and decode 2 instructions simultaneously. What would be the changes in the architecture that needs to be changed?

A: The idea that instructions are fetched and decoded one at a time per cycle is generally not true.
Let's get some simple things out of the way.  You can have multiple cores, and those cores each run independently.  That's the primary way that Intel, etc. are increasing the number of instructions per cycle (IPC).  You also have simultaneous multithreading (hyperthreading in intel speak) where you have two independent threads running on the same core.  This is another way that has been common to increase the IPC over the last decade (Sun's Niagara chip had lots of threads.)
Ok, now for the answer you probably really want.  Within a single thread of execution, most modern processors can fetch and decode multiple instructions per cycle (this is usually called super-scalar).  Pretty much all modern high-performance processors do this.  The exception is very low power processors and those that explicitly sacrifice single thread performance for throughput (Niagara, which uses lots of threads)
Now for the architectural changes (there are zillions of options).  The biggest breakdown is whether you have a fixed length instruction (ARM) or a variable length one (x86).
With fixed length instructions, you know what the instruction boundaries are, so it's relatively easy to build a system that can fetch say 8 instructions per clock and decode all of them.  Usually, your fetch width is bigger than your execution width because you're going to have branch instructions and the fetch is likely to be aligned whereas the branch can land you anywhere.  In these systems, the biggest challenge is really getting the branch predictor (really it's a next block of instructions predictor) working well.
With variable length instructions, it's simply a world of pain.  In the x86 world, these days, they translate those variable length "macro" instructions into (mostly) fixed width "micro" instructions.  Then you can store those micro instructions in a special cache (often called a trace cache).  If for a particular address, you get a hit in the trace cache, then you don't have to decode the macro instruction and you can simply deal with micro instructions.  (Trace caches can do a lot more and can be used on fixed width machines too since you can play tricks like realign blocks or even put together sequential sequences of instructions that include taken branches, hence the name "trace").  Even with this trace cache approach, you still need to try to fetch more than one macro instruction per cycle if you want to get high performance.  Usually systems can do a few and they essentially use predictors to indicate what the instruction boundaries are likely to be.
Most of the really complicated stuff is only found on out-of-order processors since it generally doesn't make much sense to try to do more than two instructions in parallel in an in-order machine since hazards and dependencies just happen too often to make anything more practical.


text:
Q: How to use StreamBuilder to print images from Firebase Storage inside a pdf I'm trying to print images from a Firebase Storage inside a pdf, using the widgets library.
So I have a code like this
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

          pdf.addPage(pw.Page(
              pageFormat: PdfPageFormat.a4,
              build: (pw.Context context) {
                return pw.Column(
                  crossAxisAlignment: pw.CrossAxisAlignment.start,
                  children: <pw.Widget>[
                    pw.Column(
                      crossAxisAlignment: pw.CrossAxisAlignment.center,
                      children: <pw.Widget>[
                        pw.Text(
                          dettagliUtente[0],
                          style: pw.TextStyle(
                              fontSize: 13, fontWeight: pw.FontWeight.bold),
                        ),
                        pw.Text(
                          dettagliUtente[1],
                          style: pw.TextStyle(
                            fontSize: 13,
                          ),
                        ),
                        pw.Divider(color: PdfColors.blueGrey),
                        pw.Padding(
                          padding: pw.EdgeInsets.all(10),
                        ),
                        pw.Text(
                          "Referto: ",
                          style:
                              pw.TextStyle(fontWeight: pw.FontWeight.bold),
                        ),
                        pw.Text(
                          _miosnap['referto'],
                          style: pw.TextStyle(),
                        ),
                            pw.Container(
                              height: 1000.0,
                              child: pw.StreamBuilder<QuerySnapshot>(
                                  stream: Firestore.instance
                                      .collection('visite')
                                      .where(
                                        "paziente",
                                        isEqualTo: idPaziente,
                                      )
                                      .where("visita",
                                          isEqualTo: dataVisitadbFormat)
                                      .snapshots(),
                                  builder: (BuildContext context,
                                      AsyncSnapshot<QuerySnapshot>
                                          snapshot) {
                                    if (snapshot.hasError)
                                      return Text(
                                          'Error: ${snapshot.error}');
                                    switch (snapshot.connectionState) {
                                      case ConnectionState.waiting:
                                        return Center(
                                            child:
                                                CircularProgressIndicator());
                                      default:
                                        return GridView.builder(
                                            physics: ScrollPhysics(),
                                            gridDelegate:
                                                SliverGridDelegateWithFixedCrossAxisCount(
                                              crossAxisCount: 2,
                                            ),
                                            itemCount: snapshot
                                                .data.documents.length,
                                            itemBuilder: (context, index) {
                                              DocumentSnapshot ds = snapshot
                                                  .data.documents[index];

                                              return Card(
                                                child:
                                                    ImageItem(ds['file']),
                                                elevation: 10.0,
                                                shape:
                                                    RoundedRectangleBorder(
                                                        side: BorderSide(
                                                            width: 2,
                                                            color: Colors
                                                                .blueGrey)),
                                              );
                                            });
                                    }
                                  }),
                            )

But inside the last container I have an error with the StreamBuilder like undefined function.
I cannot use Streambuilder inside the pdf.
How can I do to do the same thing to print images inside a pdf loading from a Firestore query and Firebase Storage?
Many thanks


text:
Q: How to make a SwiftUI Foreach shows only items that has an extra parameter I am trying to show only users that have featuredact and cant seem to get it to work.
I can show all users but i only need to get show users that have featuredact
This is my Model
struct User: Identifiable, Decodable {
    @DocumentID var id: String?
    let username: String
    let fullname: String
    var profileImageUrl: String
    let email: String
    var bio: String? //
    var location: String? //
    var website: String? //
    var verified: String?
    var featuredact: String?
}

This works to get all users
ForEach(peoplesViewModel.users) { users in
PeepsGridView(userInfo: users)
}

I tried using this
 ForEach(Array(peoplesViewModel.users), id:\.featuredact) {users in
                    FeaturedActsItemView(user: users)
                }

But with no luck.

A: The id parameter is for identifying structs, but since your User already conforms to Identifiable, you can omit it.
To only show the users that have a featuredact, you could just use an if block:
ForEach(peoplesViewModel.users) { user in

    /// unwrap `featuredact` to show the view only if it exists
    if let featuredact = user.featuredact {
        PeepsGridView(userInfo: user)
    }
}

Or maybe consider making a new array and filtering that.

A: It can be also done with filtered array
ForEach(peoplesViewModel.users.filter { $0.featuredact != nil }) { users in
   PeepsGridView(userInfo: users)
}


text:
Q: Do 'inq' and 'ink' sound similar? Do 'inq' and 'ink' sound similar?
I want to register a domain name which is related to data (writing stuff). Is it okay to use 'inq' rather than 'ink'?

A: Yes, the pronunciation of the word ink and the fanciful term inq would be identical.
There are several words and business trademarks which use a final Q to produce a K sound: umiaq, tranq (slang), and Compaq, to name a few.


text:
Q: Create Aspose.Email attachment from contentBytes in Java I know that we can create an aspose email attachment using the below code:
//Create an instance of Attachment class
Attachment attachment;

//Load an attachment
attachment = new Attachment("1.txt");

My question is if I don't have the attachment path or URL but only the name of the file and the content body bytes, how to create the attachment in this case?

A: You can pass file name and stream of your file content in Attachment class.  For more detail, please read following article.
Working with Message Attachments
I work with Aspose as Developer Evangelist.


text:
Q: String to Text - Line Break instead of comma I need help before I'm totally despaired :D
As you will see I tried it in different ways even if there are just a really few differences. My problem is that I have a string which I want (or have) to output. This means I need it in a text file. Not that big problem, eh? But the actual problem is that I want line breaks instead of commas. I know I could just replace them after the file is written but it's just unnecessary when there is another way.
The Output looks like this

[/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus,
  /rechtschreibung/_Ndrangheta, ....]

I want it to look like this
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta

Anyway even when I don't need this method later because I will store this and some other information into a database like sql. It will help me to build up the program step by step and learn some more Java ;)
So here is my code snippet
BufferedWriter bw = null;

//PrintWriter out
//= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

try {
    bw = new BufferedWriter(new FileWriter("bfwr.txt"));
    bw.write(test5.getWoerterListe().toString());
    bw.newLine();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

/*
try {
PrintWriter out = new PrintWriter(new FileWriter("prwr.txt"));
out.print(test5.getWoerterListe());
out.close();
System.out.printf("Testing String");
} catch (IOException e) {
    e.printStackTrace();
}
*/

/*
try {
    FileWriter test10 = new FileWriter("test.txt");
    test10.write(test5.getWoerterListe().toString());
    test10.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
*/

Please be nice to me :D
Assistance appreciated =)
EDIT #1
Code directly before first one.
Oberordner test2 = new Oberordner("http://www.duden.de/definition");
Unterordner test3 = new Unterordner(test2.getOberOrdner());
WoerterListe test5 = new WoerterListe(test3.getUnterOrdnerURL());
test5.setWoerterListe();

and from WoerterListe.java the really end part
public ArrayList<String> getWoerterListe(){
    return WoerterListe;
}

Additional Information: the string is not stored in the code because there are tenthousands of words like '/rechtschreibung/*'
By the way the language here is german unfortunately I have to use german words =(

A: I'm not a Java developer and you didn't state what getWoerterListe() returns, but here's my guess.
getWoerterListe() probably return a list of strings, and the default behaviour of toString() in this case is to convert the list to comma seperated values. So instead of calling toString() on the list, loop through it and write out each line followed by a carriage return (or whatever Java uses to end lines).

A: Code:
   String s = "[/rechtschreibung/_n, /rechtschreibung/_nauf, "
           + "/rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....]";

   String srp = s.replaceAll("\\[|\\]|\\.+" ,"");
   String[] sp = srp.split(",");

    for (int i = 0; i < sp.length; i++) {
        System.out.println(sp[i].trim());
    }

Output:
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta

Explanation:
I assumed [/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....] is a String. I removed all uncessary character like [ , ] , and any number of . form it. After that, I splited by , and print each element of splited string on the output.


text:
Q: Git diff for copied files Say I have a file, myfile.txt. It has a paragraph of text in it, and I copy it to a new file, myfile2.txt.
If I git diff, it will show myfile2.txt as a new file. Okay. Now I replace every occurrence of "the" with "hello" and commit.
The problem I'm having is that after the commit happens, git diff will show all of myfile2.txt as a new file and it will not show me that "the" has been replaced by "hello" everywhere (because as far as it's concerned everything is a new change).
Even if I first commit and push myfile2.txt prior to editing so that the changes are evident, that's not a good solution. It is a problem because if I squash commits down to a feature and commit it, myfile2.txt shows up as a brand new file, whereas I would like to see that those replacements have been made.
Does git have a feature that allows me to track changes in a file that was copied from another, such that a git diff will show me only those modifications and not the added file as a whole?

A: try git diff -M / git diff -C

A: I had a similar question recently about the issue of directory renames with similar advice.
There is also the --patience option to have a look at git-diff-patience.


text:
Q: Is it possible to use dynamic types base on URLSearchParams value in typescript is it possible change my type dynamically based on a function call, like the URLSearchParams has?
here's what i am triyng to:
interface X<T> {
  get: (Uparams?: URLSearchParams) => Promise<
    Uparams.has('page') extends true ? T[] : PaginatedReturn<T>
  >;
}


text:
Q: SQL login failes when using Impersonation inside a WCF service I have a WCF service being hosted in a Windows Service and is being called from a Windows Forms application. I'm using Windows Authentication and impersonation. Impersonation is working; however, when I attempt to access SQL server using Integrated Security I get "Login failed for user ''. ". I also get the same results when hosting the service inside a console application.  If I use SQL security everything works as it should.
Here is my config file for the service.
<system.serviceModel>
<bindings>
  <wsHttpBinding>
    <binding name="WSHttpBinding_IService">
      <security mode="Message">
        <transport clientCredentialType="Windows"
                   proxyCredentialType="None" realm="" />
        <message clientCredentialType="Windows"
                 negotiateServiceCredential="true"
                 algorithmSuite="Default"
                 establishSecurityContext="true" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
  <behavior name="ServiceBehavior">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
    <serviceAuthorization impersonateCallerForAllOperations="true" />
  </behavior>
  </serviceBehaviors>
  <serviceBehaviors>
    <behavior name="DefaultBehavior">
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="AfsNetService">
    <endpoint address="" binding="wsHttpBinding" contract="IAfsNetService">
      <identity>
        <userPrincipalName value="user@doman.com" />
        <servicePrincipalName value="localhost" />
        <!--<dns value="" />-->
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>

Any help with this is appreciated.

A: This is not a WCF issue but a fundamental consequence of how authentication between machines on a network happens. It is the classic "double hop" authentication issue. Delegated authentication of the second hop between the server hosting the service and the database server is usually not possible, unless all authentication is using Kerberos, and delegation is specifically configured.
This scenario can only work at all if all the computers involved (i.e. workstation where the WinForms app is running, server hosting the Service, and the database server) are all supporting Kerberos authentication and not falling back to NTLM.
If you are sure that all authentication is using Kerberos, then you have to ensure that delegation is correctly configured. This checklist may help, though some of it relates to IIS being the middle tier server, rather than a custom service as you have.

A: I am not sure if this will solve your problem or not but it seems that your xml configuration is missing bindingConfiguration tag. I think it should be like :
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"/>


text:
Q: Jquery ajax request on IOS using Phonegap - Ajax not working I have a simple html login form, deployed on Xcode using phonegap framework.
When the submitLogin button is clicked, I then sent the login credentials using ajax request to verify the login.
This is my javascript function to handle the login:
function submitLoginForm (login_id, login_pass){
    //here we need to communicate with the php files in the server
    console.log ("debug 1 ");
    $.ajax({
        type: "POST",
        url: "http://192.168.1.9/serverapp/loginHandler.php",
        data: "login_id=" + login_id + "&login_password=" + login_pass,
        success: function(loginStatus){
              navigator.notification.alert ("login request successfully sent");
              console.log ("debug 2");
              if (loginStatus == "success"){
                console.log ("debug 3 ");
                location.href = "main.html";
              }
              else{
                console.log ("debug 4 ");
                location.href="index.html?errcode=1";
              }

        }
    });

   console.log ("debug 5 ");
}

After submitting the login form, I could see that the console only printed "debug 1" message. What could be wrong in this case? If the ajax request fails, it is still supposed to print the "debug 5" message, but it did not print anything and just skip the whole thing, except the first debug message.
I could access the php url from my browser, so I am sure that the problem is not with the php code. I have been trying to spend several hours with no result. Do you have any similar problem with  Phonegap IOS framework, and how did you fix it?

A: Problem solved.
I was using an external jquery file from http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
And it appeared that the external jquery url is blocked by the ios simulator, so I have to put that url in the whitelist.
Steps:

*

*In your XCode phonegap project, browse into Resources folder.

*Go to Supporting Files directory, and edit the PhoneGap.plist file.

*In the External Host list, add any external URLs that you want to
access (including the external jquery url, and any other url that you
would use in your ajax request).

I hope this will be useful for other developers who encounter the same issue as mine.


text:
Q: Can't get the height of my nav/div to offset during scroll animation to div I am unable to get the height of my navigation.
Attempt #1:
$("#process-link").click(function() {
    $('html, body, #project-container').animate({
        scrollTop: $("#process-work").offset().top
    }, 2000 + $("nav#primary").height());
});

Attempt #2:
var headerHeight = $("nav#primary").height();

    $.address.change(function(evt) {
    var target = "#" + evt["pathNames"][0]; //Get the target from the event data

    // If there's been some content requested go to it…else go to the top
    if(evt["pathNames"][0]) {
        var scrollToPosition = $(target).offset().top - headerHeight;
        $('html, body, #project-container').animate({ 'scrollTop': scrollToPosition }, 600);
    } else {
        $('html, body, #project-container').animate({ 'scrollTop': '0' }, 600);
    }

    return false;
});

Attempt #3
$(function() {

        $('#process-link').click(function() {
            $("html, body, #project-container").animate({
                scrollTop: $( "#process-work" ).offset().top + $('nav#primary').height()
            }, 2000);

            return false;
        });
    });

HTML
Content

Content

Client:

                    View Process

Process Work

I'm trying to make it so once #process-link is clicked it slides you to #process-work and calculates the height of nav#primary and #arrow-nav and offsets accordingly.

A: This javascript currently achieved what I wanted to do. I grouped all div elements into one called #project-content and calculated the height of that plus the nav. Because the page is fixed it was causing issues.
HTML

Client:

   View Website
   View Process

Javascript
$('#process-link').click(function() {
        $("html, body, #project-container").animate({
            scrollTop: $('nav#primary').height() + $("#arrow-nav").height() + $("#project-content").height() + 30
        }, 2000);

        return false;
    });

Look at the OP to see the divs that also exist in the document and what I am calculating. #project-container has padding-top:60px; which I think also affected the offset, which is why I added 30.


text:
Q: Defensive programming in node.js using asserts Considering that sometimes error messages in node are particularly unhelpful I like to liberally use asserts in my functions so that programming errors are caught asap and I can get a message which in general pinpoints the problem.
function doSomething(arg1, arg2){
  assert(!arg1, "arg1 is undefined");
  assert(!arg2, "arg2 is undefined");
  assert(!arg1.expectedFn, "arg1 does not have expectedFn");

  arg1.expectedFn(function(blah){
    ...
  }
}

Is this a particularly bad thing to do in node/javascript programs? Does this have an impact on performance?

A: (this is more of an opinion than fact post, so take it for what it's worth)
Asserts definitely do nothing good for performance, but used in moderation I doubt they have a serious enough of an impact to matter. That said, generally speaking good test coverage is preferable to asserts whenever possible. Also, what asserts you do write should not be redundant to what errors will naturally be thrown at runtime, unless they are particularly opaque.
Let's consider a modified (and somewhat contrived) version of doSomething -
function doSomething(arg1, arg2){
  var res = arg1.expectedFn(function(blah){
    ...
  }
  return res + arg2;
}

I would argue there's no point in checking arg1 for existence or it contains a function name expectedFn. If either are undefined, the javascript runtime will throw a fairly understandable TypeError that will say exactly what happened; the asserts are redundant.
However, you may find it desirable to test arg2 here. Suppose it's undefined, and res is a string or number - you'd then end up with "undefined" appended to the string, or NaN returned. Both are fairly subtle errors that can exist for a long time without anyone noticing - if you want it to fail sooner rather than later for debugging purposes, then you may want to add a few asserts to ensure it's the correct type.
In general, if you're concerned about rigor, I believe that energy would be better put to use in writing comprehensive tests: writing tests that fully cover the cases when doSomething is called will likely lead to a better, more robust development process than asserts. There are a few cases where asserts are appropriate, but they're limited to cases where malformed results can exist for a long time without any direct errors, but still able to cause undesirable side effects.


text:
Q: creating a drop down multi level menu I wanted to create a multi level menu. I have seen yesterday the following page that I would love to do:
https://sbaueraz.github.io/
So I have been watching yesterday some tutorial and tried to create a test drop down menu with Atom (just made a search on the web and found that App, guess it's enough for what I try to do) ,
but does not seem to work properly. At least the css integration.
As I am a real beginner, I copied more or less the code from what I was watching, and tweaking a few things, trying to understand the code of course.
If someone could help me that would be great.
What I have so far (with lots of mistakes):

html,
body {
  width: 100%;
  margin: 0;
  padding: 0;
  font-family: helvetica, sans-serif;
}

.multi-level,
.item ul,
.nav input[type="checkbox"] {
  display: none;
}

#menu:checked~.multi-level,
.item:checked~ul {
  display: block;
}

  <input type="checkbox" id="menu">
  ☰

      <input type="checkbox" id="A">
      Coupant

<a href="#" Tête

<a href="#" corps

<a href="#" bras gauche

<a href="#" bras droit

      <input type="checkbox" id="B">
      Armes à feu

            <input type="checkbox" id="B-A">
            Tête

                <input type="checkbox" id="B-A-A">
                1

blablablablabla
        blablablablabla


text:
Q: ios amazon s3 uploading video file SOS, i need help. I did image uploading on to Amazon S3, and it's working fine, but when I rewrite this code for uploading video it's somethink wrong. Is uploading MOV file, but when i try to play it on browser from url, it's telling me: The image https... cannot be displayed because it contains error.
Here is my code:
- (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller
                           usingDelegate: (id <UIImagePickerControllerDelegate,
                                           UINavigationControllerDelegate>) delegate{
// Get image picker
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
mediaUI.allowsEditing = YES;
mediaUI.delegate = delegate;

// Display movie files
[controller presentModalViewController:mediaUI animated:YES ];

- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {

[self dismissModalViewControllerAnimated:YES];
UIImage *image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];

fileName = "anyName.MOV";
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

@try {
    S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:fileName inBucket:MY_BUCKET];
    por.contentType = @"movie/mov";
    por.cannedACL   = [S3CannedACL publicRead];
    por.data        = imageData;
    [s3 putObject:por];
}

@catch (AmazonClientException *exception) {
    NSLog(@"exception %@", exception);
}
}

Pleas point me on my mistake.
Many thanks!!!

A: Sorted. Problem was with Image object. So I just did get video URL by :
NSURL *image = [info objectForKey:UIImagePickerControllerMediaURL];

Instead
UIImage *image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];

And then pass NSData from url, so I did replace line
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

to:
NSData *imageData = [NSData dataWithContentsOfURL:image];

And tataaaaaaaa, problem sorted.


text:
Q: Native unit test code coverage for c++ static lib not detected I have a static lib for which I have written Native Unit tests . I have followed the link and done all steps in https://devblogs.microsoft.com/cppblog/cpp-testing-in-visual-studio/
But when I run the Code coverage for tests . It doesnt show the code coverage for the lib at all. I have configured Linker > Debugging > Generate Debug Info =/DEBUG:FULL for unit test project and also Linker-> Advanced->Profile = Yes(Profile).
Can anyone please help me with this I m not able to understand what am I missing.


text:
Q: Detect type of JSON attribute JSON:
{"attribute1":11, "attribute2":"string atribute"}

I want to detect what kind of type are attribute1 and attribute2:

*

*attribute1 is integer

*attribute2 is string

jsonObject.getAttributeType("attribute2"); // should output: string/integer/boolean.
It was very easy to achieve in PHP or OBJC. Suggestions?

A: (I'm assuming that the Android for the org.json package is that same as you can find on the json.org site ... here.)
The only method on a JSONObject that will give you the underlying value ... without coercing it ... is JSONObject.get(name).  If name is known, the result is the object that represents the value internally.  I haven't done a comprehensive trawl of the code, but I think it can only be one of the following types:
  Boolean, Long, Double, String, JSONArray, JSONObject

You should be able to discriminate these using instanceof.

But should be asking yourself if this is the right thing to do.  The normal way to deal with JSON object attributes via the JSONObject API is to use the methods that coerce them into the type that you expect.  In most cases, it doesn't matter if a number is sent as 42 or 42.0 or "42" ... and it is best not to be picky if the intent is easy to determine.

A: Another solution you can use the jackson library to do this,
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;

//Defining the JSON object
JSON json = {"attribute1":11, "attribute2":"string atribute"};

//Get the needed attribute
String value = json.get("attribute1");

//Convert the attribute to JsonNode
JsonNode value = JsonLoader.fromString(value);

//Then you can check type as below
value.isObject();
value.isArray();
value.isDouble();
value.isTextual();
value.isInt()


text:
Q: How to hide back button on ios with wix react native navigation I have been stuck on this problem all morning. I have read multiple GitHub issues and StackOverflow posts and nothing has worked.
I want to remove the blue back button in the top left of the below pic.

I have noticed I am having trouble customizing the top bar altogether. I cannot add a title to the back button etc (this hint might indicate what is wrong).
Navigation.setRoot
Navigation.events().registerAppLaunchedListener(() => {
  Reactotron.log('5');
  Navigation.setRoot({
    root: {
      stack: {
        children: [{
          component: {
            id: STARTING_SCREEN,
            name: STARTING_SCREEN
          }
        }],
      }
    },
    layout: {
      orientation: 'portrait',
    },
  }).then(()=>Reactotron.log('7'));

Navigation.push
SplashScreen (root screen) -> AccessScreen (next screen).
Navigation.push(this.props.componentId, {
  component: {
    name: screen
  },
  options: {
    topBar: {
      backButton: {
        visible: false,
      }
    }
  }

It's almost as if I am specifying the backButton options in the wrong place.

A: A tricky workaround
 leftButtons: [
      {
        id: 'something',
        text: '',
      },
    ],

the text: '' will keep a empty space, so will hide the button.
Actually not hide, but yea you can say that too.
You're good to go!!

A: Use it but only working for ios
Navigation.setDefaultOptions({
    topBar: {
      backButton: {
        visible: false
      }
    },
})

or you can customize topBar
Navigation.push(this.props.componentId, {
  component: {
    name: screen
  },
  options: {
    topBar: {
      backButton: {
        background: YourComponent
      }
    }
  }


text:
Q: Codename One (or ParparVM) how to compile Java library into iOS library By checking the Codename One website and ParparVM Github, its guide only show how to build the Java (with Java Main function entry point) into the native executable/app (iOS), but I can't find any guide to build/compile Java into iOS share library (either in C source or binary, as long as can be reused by swift/objective-C from iOS app).
So are we able to do so? is there any guide for that?

A: It wasn't designed for that purpose so it probably won't work well for it. There are some inherent design decisions that would make it very difficult to get ParparVM to work with a library. Two big ones:

*

*The GC needs to work with roots and would have a hard time collecting without full control of the app

*The code generated looks "awful". Method names translate to very long function names in C with a very convoluted syntax to allow all sort of VM edge cases such as covariance
I suggest you look at J2ObjC. I haven't checked it out in ages but it was designed exactly with this use case in mind. It doesn't have a "real" GC but that might be OK with ARC. It works with your sources and produces libraries that look a bit more "natural" on iOS.


text:
Q: Java Sun HttpServer not serving data The following should serve some text at localhost:8080/
However, nothing seems to happen. It doesn't trigger any exceptions, compiles fine, doesn't crash, etc... But the handler is never called. I'm using mint Linux.
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.*;

public class MyServer {
    @SuppressWarnings("restriction")
    public class MyHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("Request received.");
            String response = "Hello world!";
            exchange.sendResponseHeaders(200, response.length());
            exchange.getResponseBody().write(response.getBytes());
            exchange.close();
        }

    }

    @SuppressWarnings("restriction")
    private HttpServer server;

    @SuppressWarnings("restriction")
    public MyServer() throws IOException {
        server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 100);
        server.createContext("/", new MyHandler());
        server.setExecutor(null);
    }

    @SuppressWarnings("restriction")
    public void start() {
        server.start();
    }

    public static void main(String args[]) {
        try {
            System.out.println("Starting...");
            MyServer ms = new MyServer();
            ms.start();
            System.out.println("Started.");
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}


text:
Q: Simular erro de saldo insuficiente no PayPal Estou desenvolvendo um aplicativo para Android no qual eu preciso integrar o PayPal na parte de compra, estou usando o PayPal Sandbox para testar, parecia estar funcionando perfeitamente. Crio minha conta pessoal e a conta business e as transações fakes estão funcionando, pois estou checando no site do PayPal Developer.
Ao desenvolver a parte de tratamento de erros o primeiro erro que eu pretendia tratar era a questão de fundos insuficientes... mas o problema é que mesmo a minha conta de teste pessoal estando com fundos de R$0,00 as transações fakes continuam a ser confirmadas e o dinheiro é repassado.
O que eu posso estar errando ou o que posso fazer para simular esses erros no Android?