text:
Q: lightning out not working with login flow I've a login flow which uses flow and lightning component to present few screens. Issue with flow screens is these screens are not wide enough. I tried to use login flow with VF to get better control on UI. I'm creating lightning:flow component in lightning out script but its not working. When I preview the same VF from dev console, it works fine.
VF with lightning out is used to get lightning runtime experience for flow. Otherwise, it can render flow but in old classic experience.
VF Page:
<html>
  <head>
     <apex:includeLightning />

  </head>
  <body class="slds-scope">
      Text Message
     <div id="flowContainer" />
     <script>
        var statusChange = function (event) {
           if(event.getParam("status") === "FINISHED") {
              // Control what happens when the interview finishes

              var outputVariables = event.getParam("outputVariables");
              var key;
              for(key in outputVariables) {
                 if(outputVariables[key].name === "myOutput") {
                    // Do something with an output variable
                 }
              }
           }
        };
        console.log('right before calling use function');
        $Lightning.use("c:lightningOutApp", function() {
           console.log('in the callback of use function');
           // Create the flow component and set the onstatuschange attribute
           $Lightning.createComponent("lightning:flow", {"onstatuschange":statusChange},
              "flowContainer",
              function (component) {

                 // Start an interview in the flowContainer div, and
                 // initializes the input variables.
                 component.startFlow("User_Provisioning_Flow");
              }
           );
        });
     </script>
  </body>

Lightning App:
<aura:application access="global" extends="ltng:outApp">
   <aura:dependency resource="lightning:flow"/>
</aura:application>

Error coming in console:

I'm not able to understand the error but this is causing the issue. I don't get this error if page previewed from developer console. My assumption is that due to restricted session in login flow, this is happening. If this is right then is there any way to increase the width of login flow screens which are rendered by flow screen components.


text:
Q: Теория графов. Поиск циклов длины 3 и 4 Задан граф матрицей смежности. Необходимо найти циклы длины 3 и 4.
Матрица смежности возводится в степень 3 или 4... дальнейший алгоритм мне известен.
Однако препод в универе задаёт один вопрос: почему мы именно умножаем матрицы (возводим в степень), а не, к примеру, складываем их или умножаем на 3 или 4.
Буду признателен, если кто-нибудь объяснит этот момент

A: По индукции можно доказать.
Для самой матрицы смежности единицы стоят в ячейках, соответствующих путям длиной 1. Значит, свойство для степени 1 выполняется.
Пусть ячейки  матрица B=A^n содержат количества путей, т.е. Bik - количество путей из вершины i в вершину k длиной n. По определению при умножении матрицы B на A элемент матрицы С=A^(n+1)
 Сij = sum[k=1..size] Bik*Akj

а это сумма количеств путей длиной n+1, состоящих из путей длиной nиз i в k, плюс количество путей длиной 1 из k в конечную вершину j. Итак, свойство сохраняется при увеличении степени матрицы.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dosen't work hover over element and click (python selenium) I'm running into an issue with my Selenium script on Python.
Here is the code I am currently working with. The test opens the page and did nothing: there is no hover and click.
I'm new with Python and with programming in general, I can't figure out how to sequence this correctly.
Any help would be greatly appreciated.
Thanks in advance.
Python 3.9.0
selenium==3.141.0
seleniumbase==1.50.14
from selenium.webdriver.common.by import By
from seleniumbase import BaseCase

class NavigationTest(BaseCase):

    def setup_class(self):
        self.base_url = "https://www.babyshop.com/"

    def test_basket(self):
        # go to the goods page
        self.get(self.base_url + 'edushape/s/2003')
        # hover and click on the 1st position
        self.hover_and_click('//article[1]', '//article[1]//div[@class="quickshop-btn__holder"]',
                             By.XPATH, By.XPATH)
        self.sleep(3)


text:
Q: Sentence converter not working in the presence of new line I'm trying to write a program that asks the user for two file names. The first file will be opened for input and the second file will be opened for output. (It will be assumed that the first file contains sentences that end with a period.) The program will read the contents of the first file and change all the letters to lowercase except the first letter of each sentence, which should be made uppercase. The revised contents should be stored in the second file.
I'm able to get the code to work but it outputs with a large break between lines:
MY INPUT:
https://imgur.com/a/pfFemjJ
Here's the text for input.txt

c++ is a "High-Level Programming Language" developed by Bjarne Stroustrup at Bell Labs.
it helps in optimizing resources AND supports multiplayer options with networking.
google's homepage includes a button labeled I'm Feeling Lucky.
When a user types in a search AND clicks on the button the user will be taken directly to the first search result, bypassing the search engine results page.

You'll notice the unnecessary spaces between lines in output.txt. I have no clue why it outputs like that.
I've tried to mess around with the while loop I have but I can't seem to debug this issue
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    char ch;
    string inputNAME, outputNAME;
    string line;

    cout << "Please enter the filename for INPUT file: ";
    cin >> inputNAME;

    cout << "Please enter the filename for OUTPUT file: ";
    cin >> outputNAME;

    fstream inFile, outFile;

My code works when "input.txt" has no breaks between sentences as in each sentence is not separated.
However, when there are breaks between the sentences it no longer converts properly.
The end goal is to get my output file to look like this: (notice how there are no breaks between converted sentences)

A: getline(inFile, string, '.')

will read all text up to the first '.'. Given the input, string will contain

c++ is a "High-Level Programming Language" developed by Bjarne Stroustrup at Bell Labs

and

it helps in optimizing resources AND supports multiplayer options with networking.
google's homepage includes a button labeled I'm Feeling Lucky.
When a user types in a search AND clicks on the button the user will be taken directly to the first search result, bypassing the search engine results page.

will remain in the stream. Note the end of line that begins the data left in the stream. This is part of your bug.
string will be written to the file along with a '.' and an end of line.
The next call to getline will read

it helps in optimizing resources AND supports multiplayer options with networking.

into string. See the end of line character? It's going to be writen to the file. Now you have TWO end of lines. Oops.
Solution:
Don't manually add the end of line. Change
outFile << line << "." << endl;

to
outFile << line << ".";

Manually add a flush if you feel you need to complete the endl.

A: Extract entire line from file first and then in the next loop, parse for the delimiter '.', like so
while (getline(inFile, string))
{
    stringstream sstream{ string };
    while (getline(sstream, string, '.')) {

        transform(string.begin(), string.end(), string.begin(), ::tolower);

        int i = 0;
        bool contains_alpha
            = std::find_if(string.begin(), string.end(), [&i](char c) { i++; return std::isalpha(c); }) != string.end();

        if (!contains_alpha) continue;
        string[i - 1] = toupper(string[i - 1]);

        cout << string << ".";
        outFile << string << ".";
    }
    cout << endl;
    outFile << endl;
}


text:
Q: In an NxN matrix give value "True" to pairs from data frame I have created a 5x5 matrix where rows and columns have the same names and a data frame with name pairs:
N <- 5
Names <- letters[1:N]

mat <- matrix(rep(0, N*N), nrow = N, ncol = N, dimnames = list(Names, Names))

  a b c d e
a 0 0 0 0 0
b 0 0 0 0 0
c 0 0 0 0 0
d 0 0 0 0 0
e 0 0 0 0 0

The data frame then consist of different pairs:
  col1 col2
1    a    c
2    c    b
3    d    b
4    d    e

How can I match these in so that col1 only refers to rows in my matrix and col2 only to columns? The above should compute to the following result:
  a b c d e
a 0 0 1 0 0
b 0 0 0 0 0
c 0 1 0 0 0
d 0 1 0 0 1
e 0 0 0 0 0

A: You can use match to create a "key" of which combinations need to be replaced with 1, like this:
key <- vapply(seq_along(mydf),
              function(x) match(mydf[[x]],
                                dimnames(mat)[[x]]),
              numeric(nrow(mydf)))

Then, use matrix indexing to replace the relevant values.
mat[key] <- 1
mat
  a b c d e
a 0 0 1 0 0
b 0 0 0 0 0
c 0 1 0 0 0
d 0 1 0 0 1
e 0 0 0 0 0

A: You could also do:
 mat[as.matrix(d1)] <- 1
 mat
 #  a b c d e
 #a 0 0 1 0 0
 #b 0 0 0 0 0
 #c 0 1 0 0 0
 #d 0 1 0 0 1
 #e 0 0 0 0 0

data
 d1 <- structure(list(col1 = c("a", "c", "d", "d"), col2 = c("c", "b",
  "b", "e")), .Names = c("col1", "col2"), class = "data.frame",
  row.names = c("1", "2", "3", "4"))


text:
Q: Is it possible to eager load a tree with Entity Framework levelwise? I'm using Entity Framework 6 to load a tree structure. Due to the number of levels in the tree, I don't want to use a lot of includes, as the cross-product would be too big. I'm using a smaller example here for explanation.
public class Hospital
{
    public virtual List<Station> Stations {get;set;}
    public virtual Contact Contact {get;set;}
    public virtual string Uid {get;set;}
}

public class Station
{
    public virtual List<Patient> Patients {get;set;}
    public virtual Contact Contact {get;set;}
}

public class Patient
{
    public virtual List<Medication> Medications{get;set;}
    public virtual string Name {get;set;}
}

I tried to do something like this:
var hospital = context.Hospitals
                      .Include(h => h.Contact)
                      .Where(h => h.Uid == myUid);
var stations = hospital.SelectMany(h => h.Stations).Include(s => s.Contact);
var patients = stations.SelectMany(s => s.Patients);
var medications = patients.SelectMany(p => p.Medications);

var myHospital = hospital.Single();
stations.ToList();
patients.ToList();
medications.ToList();

In my understanding this should issue 4 queries, and entity framework should fix up the associations in memory. Although the 4 queries are issued, I noticed that Entity Framework is still lazy loading, when I tried to navigate through the tree in memory. this does not seem to apply for the List of stations, but for the leaf levels (e.g.patient, medications,..)
Also I noticed, that if I disable lazy loading, I can easily navigate through the tree already, so the data should be loaded already. However I would prefer not to disable lazy loading.
Can someone explain to me why EF lazy loads already loaded properties?


text:
Q: Session scoped bean behaves as Request scope bean I have Session scope bean which behaves as request scope bean.
I'm using it in Singleton bean, and maybe that's why with second request is has null values?
Code which I used to setup the bean:
In singleton:
@Autowired
private MyBean myBean;

MyBean class:
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public class MyBeanImpl implements MyBean, Serializable {

Configuration:
@Configuration
@ComponentScan(scopedProxy = ScopedProxyMode.INTERFACES, value = {  "my.package.with.bean" })
public class ComponentsConfig {
}

MyBean is simple pojo. with getters and setters.
With first request I set values on that bean, with second request in the same class (singleton) I want to read those values, but all values are null. There is no way that something has overrdiden those values.
EDIT
How I make requests - It's just simple browser request, and code which read/writes to my session bean lays in filters.
This is singleton:
@Service
public class SingletonBean {

    @Autowired
    private MyBean myBean;
// here I save the data to session scoped bean
    private void saveUser(LdapContext ctx, String principal) throws NamingException {
        Attributes attributes = getAttributes();
        myBean.setId("id");
        myBean.setName("name");
        myBean.setEmail("email");
        myBean.setTelNum("123");
        myBean.setGroups(Lists.newArrayList("one", "two"));
        myBean.setAddress("address");
    }
// here I try to read data from session scoped bean:
    @Override
    protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
            LdapContextFactory ldapContextFactory) throws NamingException {
       // here userInfo will be null
        List<String> userInfo =  myBean.getGroups();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        for (String role : userInfo ) {
            authorizationInfo.addRole(role);
        }
        return authorizationInfo;
}

}
When user logs in, and he is authenticated, I save his details in session bean. When he tries to open any page method queryForAuthorizationInfo is executed (after chain of filters) and values are null in that object.


text:
Q: Prove that $S^k$ is a subgroup of $G$
For a non empty set $S$ of a group $G$,define $$S^k=\{\Pi_{i=1} ^{n} s_i |  s_i \in S\}$$ for any positive integer $k$. Prove that, if $G$ has $n$ elements, then $S^n$ is a subgroup of $G$.

I am a beginner in abstract algebra so couldn't achieve something that I could discuss


text: Q: C# script changes take 30+ seconds to import into Unity When I make a small script change in a C# script in MonoDevelop when working in Unity- even if all I do is add a space- the "Importing Assets" window appears when I return to the editor and takes between 30 seconds to a full minute to import that one tiny script change. Has anyone else had similar problems or does anyone know what could cause this?


text:
Q: Have we directly observed the electric component to EM waves? For example, has anyone has directly observed charges oscillating due to standing EM waves? I am particularly interested because it'd demonstrate that radiation has a transverse electric component to it. Anything else (historical or modern) that shows that light has a transverse electric component would also be gladly invited.

A: Oscillating charges themselves produce radiation, but not along their axis of oscillation.
It is straightforward to show, with linearly polarised laser light, that no scattered light is received from a material in the direction(s) of laser polarisation, but is a maximum in a plane at right angles to these directions.
This demonstrates that the electrons have been made to accelerate in a particular direction -- the direction of E-field polarisation of the wave.

A: A waveguide slotline with a probe and a detector diode connected to an oscilloscope, a so-called Standing Wave Ratio (SWR) meter: https://en.wikipedia.org/wiki/SWR_meter

A: Yes, we have. As other answers have explained, this is easy to do in the radio regime, but over the past fifteen years or so we've been able to do it for light too.
The landmark publication here is

Direct measurement of light waves. E. Goulielmakis et al. Science 305, 1267 (2004); author eprint.

which broke new ground on a method called attosecond streaking that lets us see things like this:
$\qquad$

On the left you've got the (mildly processed) raw data, and on the right you've got the reconstruction of the electric field of an infrared pulse that lasts about four cycles.
To measure this, you start with a gas of neon atoms, and you ionize them with a single ultrashort burst of UV radiation that lasts about a tenth of the period of the infrared. (For comparison, the pulse length, $250\:\mathrm{as}$, is to one second as one second is to $125$ million years.) This releases the electron out of the atom, and it does so at some precisely controlled point within the infrared pulse. The electric field of the infrared can then have a strong influence on the motion of the electron: it will be forced up and down as the field oscillates, but depending on when the electron is released this will accumulate to a different impulse, and therefore a different final energy. The final measurement of the electron's energy, as a function of the relative delay between the two pulses (top left) clearly shows the traces of the electric field of the infrared pulse.

A: Yes. Radio waves are low frequency, long wavelength light waves. They drive electrons up and down an antenna. The radio detects the voltage changes this induces, amplifies them, and produces sound to match.

A: It depends on what you mean by "directly observed charges oscillating" and whether the formation of a standing wave is essential.
Using microwaves to demonstrate that they can be polarised you can infer the direction of oscillation of the electric vector in an electromagnetic wave.

If there is a horn receiver as well as a horn transmitter then just rotating one relative to the other produce a variation the amplitude of the received signal to show that the transmitted microwaves are polarised.
This can lead on to demonstrating polarisation of light using a Polaroid which on a molecular scale has crystals orientated in parallel which can form a conducting path just like the rods for microwaves.
If you do need the condition that the demonstration has to be for standing waves then a pair of Letcher lines might be of use?

Microwaves (or UHF waves) from a transmitter $b$ are guided along a pair of parallel uninsulated conducting rods with a spacing less than that of the wavelength of the microwaves and if shorted ($c$ in the diagram) produce a standing wave pattern which can be investigated by either observing the voltage nodes and antinodes or current nodes and antinodes.
Leybold produce an excellent leaflet describing the sort of experiments which can be performed with such an apparatus.
At radio frequencies the rotation of an fm dipole aerial showing the variation in signal strength will illustrate polarisation.
In this case unlike the microwave demonstration with the parallel metal rods the response is a maximum when the dipole is orientated parallel to the electric field.

A: Yes, we have observed, but not for all em waves.  Detailed answer follows from "Planets and electromagnetic waves".
Light waves or rays interact with electric fields of electrons in a solar cell to produce a disturbance in electrons so that electricity is produced.  In a tungsten bulb, electrons try to move with very close distance because of a voltage, and at the same time the electric fields of these electrons repel them. So, light energy is released.  Light energy is associated only with electric fields.
Moving electrons have magnetic fields.  Radio waves interact with magnetic fields of moving electrons, and disturb the moving electrons to make variations in current. Radio waves are associated only with magnetic fields.
No one practically observed combined form of magnetic field type and electric field type of waves with common wavelength.  In Hertz's experiment, it happens that both light waves and radio waves are released but not with common wavelength.   Some researchers do not consider microwaves as electromagnetic waves, because their velocity in vacuum is less than the velocity of light in vacuum.


text:
Q: Continue sleeping for remaining time when thread is interrupted I have network requirement who forces me to idle request sending for 2 seconds
requester = new Thread(){
        @Override
        public void run(){
                  buildRequest();
                  Thread.sleep(requestDelay);
                } catch( InterruptedException e){
                   // keep idle for the remaining time still
                   // interrupted at 1s need to sleep 1 second more
                   e.printStackTrace();
                }
                sendRequest();
            }
        }

Is it possible to still sleep for remaining time with consuming CPU with a loop? If yes is the best way ?

A: If I understood correctly you want to handle the InterruptedException in such way to unsure a delay before executing sendRequest. Well, since the InterruptedException happens when something calls interrupt() on the thread, that catch block doesn't get executed so you don't have to worry about.
Your approach is not quite right, a reactive approach would be better. Even a basic Timer is better.


text:
Q: Self removable resource from flyweight I'm working on application with different resources which I need to close, while working with reactive streams.
I've got factory based on flyweight pattern which keeps references to objects, and they implements AutoCloseable interface. Problem is i'm using close() inside Autocloseable class,
and here is my question: what is best solution to remove reference to closed resource inside factory? Can I throw some kind of event and catch it in factory, or after every action that can close resource should I iterate through references map and remove closed resources?
For better context:
I'm using reactivex Observable which emits directory event (create, remove file/directory), and after every subscriber unsubscribed to it i'm closing WatchService which i'm using.
edit #1
Here how my factory class looks like:
public final class Factory {

    private final ConcurrentHashMap<String, ReactiveStream> reactiveStreams = new ConcurrentHashMap<>();

    public ReactiveStream getReactiveStream(Path path) throws IOException {

        ReactiveStream stream = reactiveStreams.get(path.toString());

        if (stream != null) return stream;

        stream = new ReactiveStream(path);
        reactiveStreams.put(path.toString(), stream);

        return stream;

    }

}

And here is how my ReactiveStream class look like:
public class ReactiveStream implements AutoCloseable {

    (...)
    private WatchService service;
    private Observable<Event> observable;

    public Observable<Event> getObservable() throws IOException {

        (...) // where i create observable

        return observable;
    }

    (...)

    @Override
    public void close() throws IOException {
        service.close();
    }
}

As you can see i've got factory which keeps references to ReactiveStream class, which close itself after it's observable will not be subscribed anymore (i did it in a way that i use doOnUnsubscribe(() -> close()) before using share() on observable, so when there will be no subscribers, doOnUnsubscribe will be invoked).
My question is, how can i remove reference from Factory to closed ReactiveStream after it will be closed?
edit #2
observable = Observable.fromCallable(new EventObtainer()).flatMap(Observable::from).subscribeOn(Schedulers.io()).repeat().doOnUnsubscribe(() -> {
                try {
                    close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).share();

Here is how i create my observable. EventObtainer is nested class in ReactiveStream which uses WatchService which need to be closed after every subscriber stops subscribing.

A: Today my colleague told me best solution to resolve this problem. So i've created interface:
@FunctionalInterface
public interface CustomClosable {

    void onClosing();

}

And add reference of this interface to ReactiveStream in Constructor.
Also now i'm invoking onClosing.onClosing() where i need to close resources.
Thanks to that the factory class is responsible for declaring actions what should be done after its resources will be closed, and also i don't have circular dependency, so my ReactiveStream class can be reused many times.


text:
Q: How can I duplicate my existing software packages on a new system? I installed 12.04 in a separate partition. Right now, I would like to install the software that I have installed on my 10.04 in my 12.04 too. I was hoping there would be a workaround for this using aptonCD. But I figured out 'restoring' using apt on cd only copies the .debs into the cache file and that might mess things up for me considerably.
The rough idea that I have is :

*

*Run an 'apt' command on 10.04 that will give me all the package names that I have currently installed on my 10.04.

*Bring those names to 12.04 and tell apt to fetch the same softwares, but the versions of them that belong to 12.04.

*Install them.

Is there anyway to do the above steps or is there a totally different way in which I can achieve this?

A: this is one common way to duplicate a package set. On the old machine:
sudo dpkg --get-selections "*" > packages

Copy the file packages to the new machine (a pen drive is a good option. Then run this:
sudo apt-get update
sudo dpkg --set-selections < packages
sudo apt-get -u dselect-upgrade

This doesn't get you only the packages you installed. It also gets their dependencies, etc.
SOURCE


text:
Q: To create a Graph OrientDB with a csv file I'm new to the orientdb, I want to create a graph from a csv file. the csv file defines the connections of my vertices. This is my code but I have an error java.lang.NullPointerException.
the format of my csv file is:
source, weight, dest
Can someone help me?
package OrientDB;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

A: When you read the lines of Libro1.cvs you need to skip the first line (source, weight, dest) , otherwise v1 and v2 will be null and you will get NullPointerException when Edge eLives = orientDBGraph.addEdge(null, v1, v2, "connected");is executed
UPDATE
I created the database with the class connected (extends E).
I used  this csv
source, weight, dest
1,10,2
2,30,4

with this code
public class CSVReader {

private static final String ORIENT_DB_PATH = "localhost/40005113";
static OrientGraphNoTx orientDBGraph;
static OrientGraphFactory factory;

public static void main(String[] args) {

    factory = new OrientGraphFactory("remote:"+ORIENT_DB_PATH);
    orientDBGraph = factory.getNoTx();

    HashMap<String, Vertex> nodes = new HashMap<String, Vertex>();

    for(int i = 1; i <= 10; i++)
    {
        Vertex v = orientDBGraph.addVertex("class:V");
        v.setProperty("vertexID", i+"");
        nodes.put(i+"", v);
    }

    try(BufferedReader br = new BufferedReader(new FileReader("myPath/Libro.csv"))) {
        int i=0;
        for(String line; (line = br.readLine()) !=null ; ) {
            if(i==0){
                i++;
            }
            else{
            String[] vertices = line.split(",");
            String vertex1 = vertices[0];
            String vertex2 = vertices[2];
            String weight= vertices[1];
            vertex2 = vertex2.replaceAll(" ", "");

            Vertex v1 = nodes.get(vertex1);
            Vertex v2 = nodes.get(vertex2);

            System.out.println("vertex v1 = " + v1);
            System.out.println("vertex v2 = " + v2);

            Edge eLives = orientDBGraph.addEdge(null, v1, v2, "connected");
            eLives.setProperty("weight", weight);
            }
        }

    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

and I got

Hope it helps.


text:
Q: Geocoder gem not displaying proper distance users are away from address I am using the geocoder gem to implement geolocation in my rails app.  I am geolocating by address.   The users are displayed properly according to location on the map but the distance away is incorrect.  When the user index is displayed following the search the users are all set to 250.00 to 253 miles away even though they should all be 1 or 3 miles away from the address I have saved as a user.  Any reason why this would be the case and how I can fix it? Also, when I attempt to search for the users nearby, all the users are being picked up, I have 100 miles declared in the index controller and if I put a user 1000 miles away they are picked up as well. How would you set it so that only users within the 100 miles radius are picked up? Any help would be greatly appreciated, thanks!
schema.rb
  create_table "users", force: true do |t|
    t.string   "address"
    t.string   "city"
    t.string   "state_province"
    t.float    "latitude"
    t.float    "longitude"
    t.string   "country"

user.rb
geocoded_by :full_address
after_validation :geocode

def full_address
    "#{self.address}, #{self.city}, #{self.state_province}, #{self.country}"
end

user_controller.rb
  def index
    if  params[:city_search]
      @users = User.near(params[:city_search],100)
      @users = User.all_except(current_user)

index.html.erb
<% if @users.count > 1 %>

     <%= "is #{user.distance_to(params[:city_search]).round(2)} miles away." %>

<% end %>

<%= javascript_tag do %>

<% if params[:city_search] != "" %>

  var latitude = <%= @users.first.latitude %>;
  var longitude = <%= @users.first.longitude %>;
  var showMarker = false;

  var coords = <%= raw @users.map{|user| {latitude: user.latitude, longitude: user.longitude, id: user.id}}.to_json %>;

<% end %>

<% end %>


text:
Q: Is there a way to simplify this reverse-enumerator? We have a case where we have a hierarchical tree structure and we need to get the 'branch' of any particular node. The structure is a one-way linked-list from the child to the parent, but we want to define the branch in the direction from parent to child.
Here's an over-simplified example of the implementation we came up with.  Just wondering if there's a better/more effective way to achieve this given those constraints. Just feels verbose to me to do it this way.
#nullable enable

public class Node {

    public Node(String name, Node? parent)
        => (Name, Parent) = (name, parent);

    public string Name   { get; set; }
    public Node?  Parent { get; init; }

    IEnumerable<Node> GetBranch(){

        static IEnumerable<Node> getBranchReversed(Node? node) {

            while (node is not null) {
                yield return node;
                node = node.Parent;
            }
        }

        return getBranchReversed(this).Reverse();
    }
}

Only other way I can think of is to accumulate into a list where I insert into the first position, then just return the list (typing this from my memory so it may not compile...)
ReadOnlyCollection<Node> GetBranch(){

    Node? node = this;
    var branch = new List<Node>();

    while (node is not null) {
        branch.insert(0, node);
        node = node.Parent;
    }

    return branch.AsReadOnly();
}

Again, just wondering if there's any other way to achieve this.

A: To summarize the comments
IEnumerable.Reverse more or less does the following
var buffer = new List<int>(ienumerableToReverse);
for (int i = buffer.count - 1; i >= 0; --i)
    yield return buffer.items[i];

Something to note about this is that it will do the buffering each time the iterator is used. It has to do this since IEnumerable is lazy. If you want to keep the lazy behavior this is just about as good as you can do, whatever solution you want to use, you will need a buffer.
If you do not want the lazy behavior I would probably do the buffering myself:
var branch = new List<Node>();

while (node is not null) {
    branch.Add(node);
    node = node.Parent;
}
branch.Reverse();
return branch;

This should be better than your example since Insert will need to move items around for each insert causing quadratic scaling, while .Reverse is linear.


text:
Q: React Native Expo iOS app - trying to modify info.plist I have a React Native app set up in Expo.
I need to modify the info.plist, but am having problems doing so.
First, I can't find info.plist anywhere.
Based on the Expo docs and this other SO question, the workaround is to add an "infoPlist" key into my app.json file. I have done so, and it looks like this:
"infoPlist": {
      "NSAppTransportSecurity": {
        "blah.s3.amazonaws.com": {
          "NSExceptionAllowsInsecureHTTPLoads": true,
          "NSRequiresCertificateTransparency": false,
          "NSIncludesSubdomains": true
        }
      }
    }

However when I attempt to compile the app (either by running "expo start" or "expo publish") I get the following error:
Error: Problem validating fields in app.json. See https://docs.expo.io/versions/v30.0.0/guides/configuration.html
Should NOT have additional property 'infoPlist'.
Any ideas on how I can get around this?

A: The infoPlist property needs to be added inside ios section (as it has no effect on Android).


text:
Q: Pass multiple elements using forwardRef How to pass multiple elements from a component using forwardRef
I have this component and I want to pass separately loader--holder and loader--holder__logo to parent function component
const Loader = forwardRef((props, ref) => {
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  return (

  );
});

Parent component
export default function HomePage() {
  const ref = React.createRef();
  return (

      <Loader ref={ref} />

)
}

A: Just assign to the forwarded ref what you need:
const Loader = forwardRef((props, ref) => {
  const ref1 = useRef(null);
  const ref2 = useRef(null);

  useEffect(() => {
    if (ref) {
      ref.current = {
        ref1,
        ref2,
      };
    }
  }, [ref]);

  return (

Hello

  );
});

// Usage
export default function HomePage() {
  const ref = useRef();

  useEffect(() => {
    console.log('in parent', ref);
  }, []);

  return <Loader ref={ref} />;
}


text:
Q: Date format in ajax What the best way represent date format in ajax, javascript and MVC 3, when server and users has different format. How synchronize it's all?

A: When you are sending date information to the client as a response to an AJAX request, make sure that it's serialized to JSON, as that is an agreed upon format to exchange messages between server and client, and works very well in JavaScript. Unfortunately, JSON does not provide us with any rules for formatting dates.
In .NET you can serialize an object to JSON using the JavaScriptSerializer class. If you decide to use that, it will take care of serializing DateTime structures for you. What it will do is described in much more detail on MSDN, see: Stand-Alone JSON Serialization.

When not using ASP.NET, a DateTime type is represented in JSON as a
  string with a special format...

What it comes down to is this: "\/Date(700000+0500)\/"

DateTime values appear as JSON strings in the form of
  "/Date(700000+0500)/", where the first number (700000 in the example
  provided) is the number of milliseconds in the GMT time zone, regular
  (non-daylight savings) time since midnight, January 1, 1970. The
  number may be negative to represent earlier times. The part that
  consists of "+0500" in the example is optional and indicates that the
  time is of the Local kind - that is, should be converted to the local
  time zone on deserialization. If it is absent, the time is
  deserialized as Utc.

Note that the forward slashes are both escaped. Only in that case should the string be interpreted as a date. If not, it should just be interpreted as a string, although a rather strange one...
So how do we 'deserialize' this in JavaScript? If there is no timezone component, it can be as simple as:
var date = new Date(parseInt(value.substr(6)));
// parseInt will pick up the integer value
// The Date constructor understands the value as milliseconds from 1/1/1970

Or you can use eval (considered 'evil' by some) and inject some JavaScript into the value:
var date = eval("new " + value.slice(1, -1));
// effectively eval("new Date(1234567)")

There's lots of questions on StackOverflow about this as well:

*

*Deserializing Client-Side AJAX JSON Dates (great answers here!)

*Parsing JSON DateTime from Newtonsoft's JSON Serializer

*Deserializing Client-Side AJAX JSON Dates
And finally a good blog post from Microsoft's Betrand Leroy which explains the rationale for .NET:
Dates and JSON
So my advice is to stick with the format that .NET will use by default and you always be able to find the correct way to handle it, even if you must handle timezones as well. Whatever you do, do not invent your own format!
PS. From ASP.NET MVC 3 you can model bind to JSON as well, so you can send JSON to controller actions as well.


text:
Q: Unable to create Easy Tables in Azure I have created a Mobile App and Database in Microsoft Azure. Now I am trying to create Easy Tables from Mobile App but I am getting error message "You need database to use East Tables. Click here to create one.
Even though I have  existing database Easy Tables doesn't list it.
Below is the screenshot.

I have mapped Data Connection with mobile app, below is the screenshot

It would be great if anyone can help, I am new to azure.

A: Your connection string must be created with name: MS_TableConnectionString

A: Just because you have a database doesn't mean it is linked.  Click on Data Connections, then Add, then add your existing SQL database.
Note that Easy Tables won't recognize the existing tables unless you add them through Easy Tables.  There are notes around the format of Id (it needs to be
a string) and other fields.

A: When you created your Database Server did you check "Allow azure services to access server"? That could be why you cannot see the Database listed.


text:
Q: Polymorphic Deserialization Issue with Jackson I have the following classes that I want to deserialize a JSON string to using Jackson.
PushNotificationMessage.java
public class PushNotificationMessage {
    @JsonProperty("device_info")
    private DeviceInfo deviceInfo;
    private String content;

    //getters & setters
}

DeviceInfo.java
public class DeviceInfo {

    @JsonProperty(value = "device_type")
    private String deviceType;

    //getters & setters
}

IOSDeviceInfo.java
public class IOSDeviceInfo extends DeviceInfo {

    @JsonProperty(value = "device_id")
    private String deviceId;
    private String arn;
    @JsonProperty(value = "user_data")
    private String userData;

    //getters & setters
}

WebDeviceInfo.java
public class WebDeviceInfo extends DeviceInfo {
    private String endpoint;
    private String key;
    private String auth;

    //getters & setters
}

I have the following JSON content that I want to deserialize:
{
    "device_info": {
        "endpoint": "https://android.googleapis.com/gcm/send/blah",
        "key": "blahkey",
        "auth": "blahauth",
        "device_type": "web"
    },
    "content": "Notification content"
}

I simply use ObjectMapper to try to perform the deserialization as such.
final ObjectMapper objectMapper = new ObjectMapper();
final PushNotificationMessage message = objectMapper.readValue(jsonString, PushNotifictionMessage.class);

When I do this I get:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "endpoint" (class com.blah.DeviceInfo), not marked as ignorable (one known property: "device_type"])

How can I get Jackson to recognize that it needs to be mapped to a WebDeviceInfo instance, instead of trying to map it to the DeviceInfo superclass, which does not have the endpoint field?
I've tried playing with @JsonTypeInfo and @JsonSubTypes annotations in my different classes, but I can find no good examples of how to use them.
EDIT: I added the @JsonDeserialize(using = DeviceInfoDeserializer.class) annotation to my DeviceInfo class, and created the following DeviceInfoDeserializer.
public class DeviceInfoDeserializer extends JsonDeserializer<DeviceInfo> {

    private static final String DEVICE_TYPE = "device_type";
    private static final String WEB = "web";
    private static final String IOS = "ios";

    @Override
    public DeviceInfo deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException {
        final ObjectMapper objectMapper = (ObjectMapper) jsonParser.getCodec();
        final ObjectNode root = objectMapper.readTree(jsonParser);
        if (root.has(DEVICE_TYPE)) {
            final JsonNode jsonNode = root.get(DEVICE_TYPE);
            if (jsonNode.asText().equalsIgnoreCase(WEB)) {
                return objectMapper.readValue(root.toString(), WebDeviceInfo.class);
            } else if (jsonNode.asText().equalsIgnoreCase(IOS)) {
                return objectMapper.readValue(root.toString(), IOSDeviceInfo.class);
            }
        }
        throw deserializationContext.mappingException("Failed to de-serialize device info, as device_type was not \"web\" or \"ios\"");
    }
}

Now, I get a different error when attempting to deserialize my PushNotificationMessage JSON:
java.lang.StackOverflowError: null
    at com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:210)
    at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:69)
    at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:15)
    at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3770)
    at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:2207)
    at com.blah.serialization.DeviceInfoDeserializer.deserialize(DeviceInfoDeserializer.java:25)
    at com.blah.serialization.DeviceInfoDeserializer.deserialize(DeviceInfoDeserializer.java:16)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
    ... (above trace repeated many times)

EDIT: Just needed to add @JsonDeserialize(as = WebDeviceInfo.class) and @JsonDeserialize(as = IOSDeviceInfo.class) to my subclasses, now it works as expected. Big thank you to @Luciano van der Veekens.

A: Jackson is not aware of polymorphism, it just tries to create an instance of the concrete DeviceInfo class.
However, you can implement a custom deserializer that programmatically parses the device info JSON and knows when to instantiate one of the subclasses due to the uniqueness of some fields such as endpoint.
https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/annotation/JsonDeserialize.html
@JsonDeserialize(using = DeviceInfoDeserializer.class)
public class DeviceInfo {
}

An example can be found here: http://sunilkumarpblog.blogspot.nl/2015/12/javajson-polymorphic-serialization-de.html


text:
Q: one button one function on first click another on second I would like one button to perform two jquery functions. One on the first click then the other on the second click. Here is the code for the two buttons. Is there a way to combine the functions?
<input type="button" value="View Page" onclick="ViewPage()" />

<script type="text/javascript">
function ViewPage() {
example_animate('-=50%');
$("#mainContent").toggle();
}
</script>

<input type="button" value="View Menu" onclick="ViewMenu()" />

<script type="text/javascript">
function ViewMenu() {
example_animate('+=50%');
$("#mainContent").toggle();
}
</script>

A: Try something like this - DEMO
var action = 1;

$("input").on("click", viewSomething);

function viewSomething() {
    if ( action == 1 ) {
        $("body").css("background", "honeydew");
        action = 2;
    } else {
        $("body").css("background", "beige");
        action = 1;
    }
}

So in your case it will be
function viewSomething() {
    if ( action == 1 ) {
        example_animate('-=50%');
        action = 2;
    } else {
        example_animate('+=50%');
        action = 1;
    }
    $("#mainContent").toggle();
}

A: Another way using one method, both will fire only once
$("input").one("click", viewSomething);
function viewSomething()
{
    $("body").css("background", "honeydew");
    $("input").one("click", function(){ // on can be used
        $("body").css("background", "beige");
    });
}

DEMO.
Update: If you want to keep the second handler alive then replace one with on like this one.

A: You can also assign a name to html element..
<input type="button" value="Click me" onclick = 'viewSomething(this)'/>
<script>
    function viewSomething(e){

        //First time click
        if(e.name != 'Click'){
           e.name = "Click";
           <!--do whatever..-->
         }//end if

       //When click it again..
       else if(e.name == 'Click'){
           e.name = "Unclick";
           <!--do whatever-->
       }//end else
  }//end function
</script>

A: You could use an array to store your functions and a counter with data to track the index. This is very flexible because you can add as many functions as you like and it'll loop if you keep clicking.
Demo: http://jsbin.com/ehatoj/2/edit
var funcs = [
  function one() { alert('one'); },
  function two() { alert('two'); },
  function three() { alert('three'); }
];

$('button')
  .data('counter', 0) // begin counter at zero
  .click(function() {
    var counter = $(this).data('counter');
    funcs[ counter ]();
    $(this).data('counter', counter < funcs.length-1 ? ++counter : 0);
  });

A: You could add a class to your button so you know what the button should do, and then test in both functions if the button has this class or not.
Of course you will also need to remove the class in viewMenu(), that would look like this in jQuery v1.8.3 :
<input id="toggle-view" type="button" value="View Menu" class="view-page" />

$('#toggle-view').on('click', function()
{
   var button = $(this);

   if ( button.hasClass('view-page')  )
   {
       ViewPage();
       button.removeClass('view-page');
   }
   else
   {
        ViewMenu();
        button.addClass('view-page');
   }
});


text:
Q: kineticjs analog for jquery sortable Who can suggest kineticjs plugin or script with jquery's "sortable" functional?
I need create list of shapes with drag'n'drop and when one of the element moves other elements moving on his place

A: Here is a script that lets users sort list-items in a Kinetic List by dragging
Before:  This illustration below shows the user dragging item#1 to the bottom of the list.

After:   This illustration shows how the list redraws automatically in newly sorted order.

The data content of each List-Item is stored in an array of item objects:
If you need more item data, just add that data to the list-item objects
    // array of item objects

    var contents = [];

    // item objects contain a text label
    // and a reference to the Kinetic Group that displays this item

    contents.push( { text: "I'm list-item#1",  kItem: KineticGroup#1   } );

After the user drags a list-item to a new location, the entire list is resorted.
The resort order is based on the "Y" coordinate of each list-item on the list.
The code redraws all the list-items in the newly sorted order.
    // after dragging, list is resorted by the "Y" coordinate of each list-item

    function reorder(){
        contents.sort(compare);
        for(var i=0;i<contents.length;i++){
            contents[i].kItem.setY((i*(itemHeight+itemSpacer))+itemsTopMargin);
        }
        layer.draw();
    }

    // custom compare function that sorts based on Y-coordinates

    function compare(a,b){
        if(a.kItem.getY()b.kItem.getY()){ return 1; }
        return(0);
    }

After the user is done drag-sorting, the contents array is sorted in the user's order
Here is code and a Fiddle:  http://jsfiddle.net/m1erickson/gZWvC/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>

Sort by draggging item to new location


text:
Q: How to understand `[0, 1, 2, ...0[]]` in type definition in typescript? I see some type definition like this in Typescript: deep keyof of a nested object:
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]]

I can't understand what the last part ...0[] means.
Is there a document for this? Thanks

A: You need two pieces of information to understand this type:

*

*Rest elements in tuple types

The last element of a tuple type can be a rest element of the form ...X, where X is an array type. A rest element indicates that the tuple type is open-ended and may have zero or more additional elements of the array element type. For example, [number, ...string[]] means tuples with a number element followed by any number of string elements.

*

*you can restrict a type to one constant value:

const x: 0 = 0;
const y: 0 = 1; // ERROR: Type '1' is not assignable to type '0'.

Thus, the trailing ...0[] in tuple type means: any number of zeroes


text:
Q: Separating columns using pandas.read_csv I am trying to read one table from a larger .txt file into python.
An extract of the data is:
2 Network magnitudes:
    MLv       2.05 +/- 1.34   7
    M         2.05            7 preferred

7 Phase arrivals:
    sta  net   dist azi  phase   time         res     wt  sta
    BMOR  EC    0.0 226  P       00:22:31.385  -0.6 M  1.0  BMOR
    BREF  EC    0.0 347  P       00:22:31.543  -0.5 M  1.0  BREF
    BTAM  EC    0.0  58  P       00:22:31.796  -0.3 M  1.0  BTAM
    BVC2  EC    0.0  26  P       00:22:33.061   0.8 M  1.0  BVC2
    BNAS  EC    0.1 294  P       00:22:32.871  -0.1 M  1.0  BNAS
    SUCR  EC    0.1 314  P       00:22:34.610   0.6 M  1.0  SUCR
    BRRN  EC    0.1 207  P       00:22:34.768   0.4 M  1.0  BRRN

7 Station magnitudes:
    sta  net   dist azi  type   value   res        amp per
    BMOR  EC    0.0 226  MLv     1.48 -0.57    1.20076

I only want the phase arrivals table and so np.loadtext and np.genfromtxt both fall short for various reasons (can't deal with numbers and strings / contains a bug unless you specify only a one space (' ') delimiter, which I can't do here)
I've been trying with the pandas.read_csv fucntion but it isn't recognising the delimiters
a = pd.read_csv(datafileloc, sep='\+s', skiprows=5, skipfooter=3)

produces:
a
Out[90]:
  sta  net   dist azi  phase   time         res     wt  sta
0  BMOR  EC    0.0 226  P       00:22:31.385  -0....
1  BREF  EC    0.0 347  P       00:22:31.543  -0....
2  BTAM  EC    0.0  58  P       00:22:31.796  -0....
3  BVC2  EC    0.0  26  P       00:22:33.061   0....
4  BNAS  EC    0.1 294  P       00:22:32.871  -0....
5  SUCR  EC    0.1 314  P       00:22:34.610   0....
6  BRRN  EC    0.1 207  P       00:22:34.768   0....

which looks good apart from that they're each one string and it hasn't paid attention to the white space delimiters:
a.values
Out[89]:
array([['BMOR  EC    0.0 226  P       00:22:31.385  -0.6 M  1.0  BMOR'],
       ['BREF  EC    0.0 347  P       00:22:31.543  -0.5 M  1.0  BREF'],
       ['BTAM  EC    0.0  58  P       00:22:31.796  -0.3 M  1.0  BTAM'],
       ['BVC2  EC    0.0  26  P       00:22:33.061   0.8 M  1.0  BVC2'],
       ['BNAS  EC    0.1 294  P       00:22:32.871  -0.1 M  1.0  BNAS'],
       ['SUCR  EC    0.1 314  P       00:22:34.610   0.6 M  1.0  SUCR'],
       ['BRRN  EC    0.1 207  P       00:22:34.768   0.4 M  1.0  BRRN']], dtype=object)

Lines can be separated with list(a.values[0])[0].split() but this will then take reorganising to get individual columns. I would like to have pandas.read_csv just recognise they're separate so I can extract individual columns (being reasonably efficient is going to be important once I scale it up)
Where am I going wrong?

A: As pointed out by DSM, it is a typo in the delimiter:
\s+, not \+s
which came from a typo in the documentation, under the delim_whitespace parameter heading.


text:
Q: cmake -E equivalent in cmake 2.8 I am new to cmake and i am working with a 3.1 CMakefile with -E env option and I am backporting it to 2.8. What is the compatible or equivalent option in 2.8?
https://github.com/CZ-NIC/turris-os/blob/master/package/system/ubus/patches/001-python.patch
The line I am dealing with is
+ADD_CUSTOM_TARGET(python ALL
+ COMMAND ${CMAKE_COMMAND} -E env "CC=${CMAKE_C_COMPILER}
${CMAKE_C_COMPILER_ARG1}" "LDSHARED=${LDSHARED}" "CFLAGS=${PYTHON_CFLAGS}"
${PYTHON} ${SETUP_PY} build
+ DEPENDS ubus "${CURRENT_SOURCE_DIR}/ubus_python.c"
+)
+
+INSTALL(
+ CODE "execute_process(COMMAND ${CMAKE_COMMAND} -E env \"CC=${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}\" \"LDSHARED=${LDSHARED}\" \"CFLAGS=${PYTHON_CFLAGS}\" ${PYTHON} ${SETUP_PY} install --    prefix=${CMAKE_INSTALL_PREFIX})"
+)

-Zer0_0ne


text:
Q: Java ANSI и UTF-8 проблемы с компиляцией Столкнулся с проблемой, написав программу Java на Windows (кодировка ANSI) перенес исходники на Linux(Ubuntu) там в исходнике все названия кнопок которые были написаны на кириллице превратились в крякозябры, подсказали что нужно сохранить документ в кодировке UTF-8, действительно кириллица отображалась правильно, но исходники не поддавались компиляции, выводилась ошибка:
Tabl.java:1: error: illegal character: \187
я╗┐import javax.swing.JFrame;
 ^
1 error

читал что при компиляции можно использовать команду "-encoding"
но не знаю как её правильно использовать, и нужно ли её использовать, посоветуйте как легче справится с проблемой. Спасибо.
A: Нашел, в файл при сохранении в формате отличном от системного (по умолчанию) добавлялся BOM (Byte Order Mask)
Википедия Юникод

Для определения формата представления
Юникода в начало текстового файла
записывается сигнатура — символ U+FEFF
(неразрывный пробел с нулевой
шириной), также именуемый меткой
порядка байтов (англ. byte order mark,
BOM). Это позволяет различать UTF-16LE
и UTF-16BE, поскольку символа U+FFFE
не существует. Также этот способ
иногда применяется для обозначения
формата UTF-8, хотя к этому формату и
неприменимо понятие порядка байтов.
Файлы, следующие этому соглашению,
начинаются с таких последовательностей
байтов:
UTF-8  EF BB BF
UTF-16BE  FE FF
UTF-16LE  FF FE
UTF-32BE  00 00 FE FF
UTF-32LE  FF FE 00 00

в некоторых текстовых редакторах есть функция "кодировка UTF-8 без BOM", после сохранения в таком виде всё компилировалось корректно.
A: параметры для javac
хотя я лично пробовал игратся с кодировкой и у меня не получилось скомпилировать простенький класс :)
с другой стороны вы можете избежать излишних трудностей если будете использовать IDE (напр. eclipse) - pure java есть вариант и для linux и для windows


text:
Q: Android match_parent not working as expected In my layout file I use root ScrollViewand child LinearLayout.
I searched about this but did't get help.
I set match_parent in my both parent and child view.
But there is problem with child view.
Child view not filling like parent view.
Here is image and xml code.

Layout File.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:CustomTextView="http://schemas.android.com/apk/res-auto"
    xmlns:CustomEditTextView="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D3D6DB"
    android:orientation="vertical"
    tools:context=".tabs.MyTravelTab" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/card_background_new"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp" >

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="@dimen/field_height"
                    android:layout_weight="0.4"
                    android:gravity="left|center_vertical" >

                    <com.mymv.controls.CustomTextView
                        android:id="@+id/textGPS"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        CustomTextView:typeface="Roboto-Regular.ttf"
                        android:text="ABC"
                        android:textColor="@color/black"
                        android:textSize="12sp" />

                    <ToggleButton
                        android:id="@+id/gps_toggle"
                        android:layout_width="wrap_content"
                        android:layout_height="24dp"
                        android:layout_margin="5dp"
                        android:background="@drawable/gps_custom_toggle"
                        android:checked="false"
                        android:textOff=""
                        android:textOn="" />

                    <com.mymv.controls.CustomTextView
                        android:id="@+id/textManual"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        CustomTextView:typeface="Roboto-Regular.ttf"
                        android:text="DEF"
                        android:textColor="@color/black"
                        android:textSize="11sp" />
                </LinearLayout>

                <Spinner
                    android:id="@+id/spinnerPurposeOfJourney"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/field_height"
                    android:layout_weight="0.6"
                    android:background="@drawable/dropdown_black_border"
                    android:entries="@array/purpose_of_journey" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/gpsLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp"
                android:visibility="gone" >

                <LinearLayout
                    android:id="@+id/startGPSBtn"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/field_height"
                    android:layout_weight="0.5"
                    android:background="@drawable/textview_green_drawable_left_curve_selector"
                    android:gravity="center" >

                    <ImageView
                        android:id="@+id/imageView1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/gps" />

                    <com.mymv.controls.CustomTextView
                        android:id="@+id/textView1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        CustomTextView:typeface="Roboto-Regular.ttf"
                        android:text="START GPS"
                        android:textColor="@color/white" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/endGPSBtn"
                    android:layout_width="0dp"
                    android:layout_height="@dimen/field_height"
                    android:layout_weight="0.5"
                    android:background="@drawable/textview_red_drawable_right_curve_selector"
                    android:gravity="center" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/end_flag" />

                    <com.mymv.controls.CustomTextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        CustomTextView:typeface="Roboto-Regular.ttf"
                        android:text="END GPS"
                        android:textColor="@color/white" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="10dp" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center" >

                    <com.mymv.controls.CustomTextView
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_weight="@integer/layout_weight_textview"
                        CustomTextView:typeface="Roboto-Bold.ttf"
                        android:background="@drawable/textview_gray_drawable"
                        android:gravity="center_vertical"
                        android:padding="5dp"
                        android:text="DATA"
                        android:textColor="@color/gray" />

                    <com.mymv.controls.CustomTextView
                        android:id="@+id/edtTxtDate"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_marginLeft="-1dp"
                        android:layout_weight="@integer/layout_weight_edittext"
                        CustomTextView:typeface="Roboto-Regular.ttf"
                        android:background="@drawable/edittext_drawable_right_curv_selector"
                        android:gravity="center_vertical"
                        android:hint="DATA"
                        android:padding="5dp"
                        android:singleLine="true"
                        android:textColor="@color/black"
                        android:textColorHint="@color/gray"
                        android:textSize="15dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/manualLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:visibility="visible" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        android:gravity="center" >

                        <com.mymv.controls.CustomTextView
                            android:layout_width="0dp"
                            android:layout_height="@dimen/field_height"
                            android:layout_weight="@integer/layout_weight_textview"
                            CustomTextView:typeface="Roboto-Bold.ttf"
                            android:background="@drawable/textview_gray_drawable"
                            android:gravity="center_vertical"
                            android:padding="5dp"
                            android:text="DATA"
                            android:textColor="@color/gray" />

                        <com.mymv.controls.CustomEditTextView
                            android:id="@+id/edtTxtStartOdometer"
                            android:layout_width="0dp"
                            android:layout_height="@dimen/field_height"
                            android:layout_marginLeft="-1dp"
                            android:layout_weight="@integer/layout_weight_edittext"
                            CustomTextView:typeface="Roboto-Regular.ttf"
                            android:background="@drawable/edittext_drawable_right_curv_selector"
                            android:focusable="false"
                            android:gravity="center_vertical"
                            android:hint="DATA"
                            android:inputType="number"
                            android:maxLength="6"
                            android:padding="5dp"
                            android:singleLine="true"
                            android:textColor="@color/black"
                            android:textColorHint="@color/gray"
                            android:textSize="15dp" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        android:gravity="center" >

                        <com.mymv.controls.CustomTextView
                            android:layout_width="0dp"
                            android:layout_height="@dimen/field_height"
                            android:layout_weight="@integer/layout_weight_textview"
                            CustomTextView:typeface="Roboto-Bold.ttf"
                            android:background="@drawable/textview_gray_drawable"
                            android:gravity="center_vertical"
                            android:padding="5dp"
                            android:text="DATA"
                            android:textColor="@color/gray" />

                        <com.mymv.controls.CustomEditTextView
                            android:id="@+id/edtTxtEndOdometer"
                            android:layout_width="0dp"
                            android:layout_height="@dimen/field_height"
                            android:layout_marginLeft="-1dp"
                            android:layout_weight="@integer/layout_weight_edittext"
                            CustomEditTextView:typeface="Roboto-Regular.ttf"
                            android:background="@drawable/edittext_drawable_right_curv_selector"
                            android:focusable="false"
                            android:gravity="center_vertical"
                            android:hint="DATA"
                            android:inputType="number"
                            android:maxLength="6"
                            android:padding="5dp"
                            android:singleLine="true"
                            android:textColor="@color/black"
                            android:textColorHint="@color/gray"
                            android:textSize="15dp" />
                    </LinearLayout>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:gravity="center" >

                    <com.mymv.controls.CustomTextView
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_weight="@integer/layout_weight_textview"
                        CustomTextView:typeface="Roboto-Bold.ttf"
                        android:background="@drawable/textview_gray_drawable"
                        android:gravity="center_vertical"
                        android:padding="5dp"
                        android:text="DATA"
                        android:textColor="@color/gray" />

                    <com.mymv.controls.CustomEditTextView
                        android:id="@+id/edtTxtStartLocation"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_marginLeft="-1dp"
                        android:layout_weight="@integer/layout_weight_edittext"
                        CustomEditTextView:typeface="Roboto-Regular.ttf"
                        android:background="@drawable/edittext_drawable_right_curv_selector"
                        android:focusable="false"
                        android:gravity="center_vertical"
                        android:hint="DATA"
                        android:maxLength="100"
                        android:padding="5dp"
                        android:singleLine="true"
                        android:textColor="@color/black"
                        android:textColorHint="@color/gray"
                        android:textSize="15dp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:gravity="center" >

                    <com.mymv.controls.CustomTextView
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_weight="@integer/layout_weight_textview"
                        CustomTextView:typeface="Roboto-Bold.ttf"
                        android:background="@drawable/textview_gray_drawable"
                        android:gravity="center_vertical"
                        android:padding="5dp"
                        android:text="DATA"
                        android:textColor="@color/gray" />

                    <com.mymv.controls.CustomEditTextView
                        android:id="@+id/edtTxtEndLocation"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/field_height"
                        android:layout_marginLeft="-1dp"
                        android:layout_weight="@integer/layout_weight_edittext"
                        CustomEditTextView:typeface="Roboto-Regular.ttf"
                        android:background="@drawable/edittext_drawable_right_curv_selector"
                        android:focusable="false"
                        android:gravity="center_vertical"
                        android:hint="DATA"
                        android:maxLength="100"
                        android:padding="5dp"
                        android:singleLine="true"
                        android:textColor="@color/black"
                        android:textColorHint="@color/gray"
                        android:textSize="15dp" />
                </LinearLayout>

                <Button
                    android:id="@+id/btnRecord"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/field_height"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/button_blue_border"
                    android:text="Button"
                    android:textColor="@color/white"
                    android:textSize="15dp" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/viewUsage"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:layout_weight="0.5"
                android:background="@drawable/button_background_yellow"
                android:padding="10dp"
                android:text="Button1"
                android:textColor="@color/black" />

            <Button
                android:id="@+id/viewTravelHistory"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:layout_weight="0.5"
                android:background="@drawable/button_background_blue"
                android:padding="10dp"
                android:text="Button2"
                android:textColor="@color/white" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>

A: Try android:fillViewport="true" in your scrollview.

A: LinearLayout inside the ScrollView is recommended to use wrap_content for its size.
To display the full of listview, you can:

*

*Use android:fillViewport="true"attribute of ScrollView

OR

*Use exactly value for width and height for LinearLayout. You can calculate it depend on you need, such as equal to screen dimensions, or equal other view size, ...

A: Use
android:fillViewport="true" attribute of scrollview.
https://developer.android.com/reference/android/widget/ScrollView.html#attr_android:fillViewport


text:
Q: Prove that concatenation is greater than sum It appears that the concatenation of two positive integers is strictly greater than their sum.
I can prove this for the case when the order of magnitude of their sum is less than the order of magnitude of the concatenation, however I am struggling with the case when they are equal.

A: Order of magnitude is equal implies they have same number of digits, say $n$. Concatenation of integers $a,b$ that have n-digits is equal to $10^na+b$ or $10^nb+a$. Both these values are greater than $a+b$.

A: Hint: If the number $b$ is $k$ digits long, then $a\oplus b = a\left(10^k\right)+b$ ($\oplus$ represents concatenation).

A: Let $a\ge b\ge 1$ and $10^{n-1}\le a<10^n$ (that is, $a$ has $n$ digits). And let's denote concatenation of $a$ followed by $b$ by $a|b$.
Then the sum $a+b$ is certainly not greater that $2a$ since $b\le a$, and $2a$, in turn is certainly less than $10^n+a$ since $a<10^n$:
$$a+b\le 2a < 10^n+a$$
On the other hand, the concatenation of $b$ followed by $a$ is certainly at least equal to $10^n+a$, which would mean adding $1$ before $a$, since $b\ge1$:
$$b|a=10^nb+a\ge 10^n+a$$
Hence we have $a+b<b|a$.

Now, is it also true that $a|b>a+b$?
Yes, because
$$a|b\ge 10a+1>2a\ge a+b$$


text:
Q: Check if user like a page without creating facebook app I have to check in my script if a user like a facebook page.
I would realize it without Facebook app. I would not create it.
I founded some examples, but they require a Facebook app, and that user gives it the correct permission.
Can you help me? Is it possible?
Thanks for any suggestion.

A: You need to use the Facebook API and ask for permission from the user to do this.
Resources:
Facebook API info
User info

A: If your application is an external website, then you need to use the Facebook API and ask for the user_likes permission + valid access and make a POST to USER_ID/likes/PAGE_ID
If your application is a canvas or a tab application, then you can use the signed_request parameters that Facebook send you.
https://developers.facebook.com/docs/howtos/login/signed-request/
https://developers.facebook.com/docs/reference/api/user/
Regards


text:
Q: InnerBlocks with allowedBlocks not working with acf_register_block I using the InnerBlocks tag to allow for nested blocks, within my custom block. I am trying to use the 'allowedBlocks' argument to restrict the blocks allowed to only specific ones. However, if I put anything inside the InnerBlocks tag, the block does not load and just spins.
I am using acf_register_block for my block registry, as what we are doing heavily ties in with ACF.
I have enabled '__experimental_jsx' => true  in all the blocks I am working with.
This works

    <InnerBlocks />

This does not work

    <InnerBlocks allowedBlocks={ 'acf/orange-carousel' } />

It also doesn't work if I pass an array instead of a string for the allowed blocks.
I am using ACF Pro Beta 5.9
Any help is appreciated!

A: A late reply but I thought I would include a snippet that worked for me.
Update $allowed_inner_blocks with your own "block_types" and place the following code inside the parent block template;
<?php $allowed_inner_blocks = ['acf/logos']; ?>
<InnerBlocks allowedBlocks="<?php echo esc_attr(wp_json_encode($allowed_inner_blocks)); ?>" />

A: Is acf the correct namespace? if so, this should work in your edit function.
const ALLOWED_BLOCKS = [
    'acf/orange-carousel',
]

return (

        <InnerBlocks
            allowedBlocks={ ALLOWED_BLOCKS }
        />

);


text:
Q: Session Manager using Shared Pref I'm using shared preference to store user data, and in my start screen, I want to check whether username has already logged in or not, when user is still not logged out yet it will redirect to UserView.java when the application starts, otherwise it will go to LoginActivity.java
I've used these tutorial as my references :
Android Hive Tutorial Shared Pref, and
Android example tutorial Shared Pref..
but when I exit my activity without logging out, next time I open my application it's status is logged out (its like the session has ended although I have not logged out yet from my application),,
What should I do to fix this thing, so whenever I exit my application (without logging out) my data is still there in shared pref and will be redirected to UserView.java, Am i making any mistakes with my codes?
These are my code:
userSessionManager.java
package com.thesis.teamizer;

import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class userSessionManager {

// Shared Preferences Reference
SharedPreferences CurrentSession;

// Editor Reference for Editing Shared Preferences
Editor editor;

// Context Reference
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharef Preferences Name
public static String PrefName = "MyUsername";

// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_USERNAME = "username";

// Constructor
public userSessionManager(Context context) {
    this._context = context;
    CurrentSession = _context.getSharedPreferences(PrefName, PRIVATE_MODE);
    editor = CurrentSession.edit();
}

public void createUserLogin(String username) {

    // User has already login
    editor.putBoolean(IS_USER_LOGIN, true);

    // Storing username in pref
    editor.putString(KEY_USERNAME, username);

    // Editor ready to execute the previous codes
    editor.commit();
}

public boolean checkLogin() {
    // Check login status. If the user is not logged in
    if (!this.isUserLoggedIn()) {
        return true;
    }
    return false;
}

// Read session using hashmap
public HashMap<String, String> getUserDetails() {

    // Use hashmap to store user credentials
    HashMap<String, String> user = new HashMap<String, String>();

    // user name
    user.put(KEY_USERNAME, CurrentSession.getString(KEY_USERNAME, null));

    // return user
    return user;
}

public void logOut() {
    // clearing all data from Shared pref
    editor.remove(KEY_USERNAME);
    editor.clear();
    editor.commit();
}

// Will check if the user is Login or not by getting the boolean of
// IS_USER_LOGIN from CurrentSession(pref)
private boolean isUserLoggedIn() {
    // TODO Auto-generated method stub
    return CurrentSession.getBoolean(IS_USER_LOGIN, false);
}
}

LoginActivity.java
package com.thesis.teamizer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements View.OnClickListener     {

private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
String loginUrl;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private ProgressDialog pDialog;
String Username;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.login_screen);

    Declaration();

    bLogin.setOnClickListener(this);
    bRegis.setOnClickListener(this);
    bAdmin.setOnClickListener(this);

    if (session.checkLogin()) {
        Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
        finish();
        startActivity(intent);
    }
}

private void Declaration() {
    // TODO Auto-generated method stub
    etUsername = (EditText) findViewById(R.id.etLoginUsername);
    etPassword = (EditText) findViewById(R.id.etLoginPassword);
    bLogin = (Button) findViewById(R.id.bLogin);
    bRegis = (Button) findViewById(R.id.bRegister);
    bAdmin = (Button) findViewById(R.id.bAdminadmin);
    session = new userSessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();
    Username = user.get(userSessionManager.KEY_USERNAME);
    myIP ip = new myIP();
    String myIp = ip.getIp();
    String thisPhp = "doLogin.php";
    loginUrl = myIp + thisPhp;

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bLogin:
        new AttemptLogin().execute();

        break;

    case R.id.bRegister:
        Intent i = new Intent("com.thesis.teamizer.REGISTRATIONACTIVITY");
        startActivity(i);

        break;

    }
class AttemptLogin extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(loginUrl, "POST",
                    params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                String currentLoginUsername = username;
                session.createUserLogin(currentLoginUsername);
                Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
                finish();
                startActivity(intent);
                String sukses = "Sukses login";
                return sukses;
            } else if (success == 0) {
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        Toast.makeText(getApplicationContext(), file_url,
                Toast.LENGTH_SHORT).show();

    }

}

}

UserView.java
package com.thesis.teamizer;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class UserView extends Activity implements View.OnClickListener {

public Button createGr, viewGr, createAn, viewAn, notification, logout,
        calendar, createEvent, myEvent, createTask, myTask;
public String Username;
userSessionManager session;
Intent i;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_view);
    sessionAndDeclaration();
    createGr.setOnClickListener(this);
    viewGr.setOnClickListener(this);
    createAn.setOnClickListener(this);
    viewAn.setOnClickListener(this);
    notification.setOnClickListener(this);
    logout.setOnClickListener(this);
    createEvent.setOnClickListener(this);
    calendar.setOnClickListener(this);
    myEvent.setOnClickListener(this);
    createTask.setOnClickListener(this);
    myTask.setOnClickListener(this);
}

private void sessionAndDeclaration() {
    // TODO Auto-generated method stub
    session = new userSessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();

    // get name
    Username = user.get(userSessionManager.KEY_USERNAME);
    TextView a = (TextView) findViewById(R.id.tvUserVUsername);
    a.setText(Username);
    createGr = (Button) findViewById(R.id.bCreateGroup);
    viewGr = (Button) findViewById(R.id.bViewMyGroup);
    createAn = (Button) findViewById(R.id.bCreateAnnouncement);
    viewAn = (Button) findViewById(R.id.bViewMyAnnouncement);
    notification = (Button) findViewById(R.id.bNotification);
    logout = (Button) findViewById(R.id.bDoLogout);
    calendar = (Button) findViewById(R.id.bGoToMyCalendar);
    createEvent = (Button) findViewById(R.id.bCreateEvent);
    myEvent = (Button) findViewById(R.id.bGoToMyEvent);
    createTask = (Button) findViewById(R.id.bGoToCreateTask);
    myTask = (Button) findViewById(R.id.bGoToMyTask);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {

    case R.id.bCreateGroup:
        i = new Intent("com.thesis.teamizer.CREATEGROUPACTIVITY");
        startActivity(i);
        break;

    case R.id.bViewMyGroup:
        i = new Intent("com.thesis.teamizer.MYGROUPACTIVITY");
        startActivity(i);

        break;

    case R.id.bCreateAnnouncement:
        i = new Intent("com.thesis.teamizer.CREATEANNOUNCEMENTACTIVITY");
        startActivity(i);

        break;

    case R.id.bViewMyAnnouncement:
        i = new Intent("com.thesis.teamizer.VIEWALLANNOUNCEMENT");
        startActivity(i);
        break;

    case R.id.bNotification:
        i = new Intent("com.thesis.teamizer.NOTIFICATION");
        startActivity(i);
        break;

    case R.id.bDoLogout:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to Logout?")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                finish();
                                session.logOut();
                                Intent i = new Intent(
                                        "com.thesis.teamizer.LOGINACTIVITY");

                                // Closing all the Activities
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                                // Add new Flag to start new Activity
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                // Staring Login Activity
                                startActivity(i);
                                finish();
                            }
                        })
                .setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();

        break;

    case R.id.bGoToMyCalendar:
        i = new Intent("com.thesis.teamizer.VIEWCALENDAR");
        startActivity(i);
        break;

    case R.id.bCreateEvent:
        i = new Intent("com.thesis.teamizer.CREATEEVENT");
        startActivity(i);

        break;

    case R.id.bGoToMyEvent:
        i = new Intent("com.thesis.teamizer.MYEVENT");
        startActivity(i);
        break;

    case R.id.bGoToCreateTask:
        i= new Intent("com.thesis.teamizer.CREATETASK");
        startActivity(i);
        break;

    case R.id.bGoToMyTask:
        i = new Intent("com.thesis.teamizer.MYTASK");
        startActivity(i);
        break;

    }
}

}


text:
Q: Entity Framework: Mapping many-to-many During my project in which I make some sort of webshop, I've came across a problem with my .NET backend where I use Entity Framework Code First with Fluent API.
In my frontend, Orders can be made and are passed to my backend where they end up as a Order object (code below). This Order contains a User and a Dictionary where Items and their ordered quantities are stored. My current goal is to store those Orders in my database to retrieve an Order history.
My understanding is that by itself, EF can't map a Dictionary. Being a student and having done mostly frontend, I don't really know how to tackle this.
I've tried converting that Dictionary to a List of ItemWrappers (containing both the Item and the amount) and making 2 tables: Order (OrderId, UserId) and OrderItem (OrderId, ItemId, Amount). This converts the Many-to-Many (Users to Items and Order is derived from the relation attribute) to a One-to-Many (Order to OrderItem).
I understand this from a purely database perspective. I could have managed if I were to write all the queries myself, but given that EF adds some abstraction to that, I am a bit lost. How do you suggest I do this?
The code is simplified to only show the class structure. Id is always generated on add and is used as primary key.
 public class User {

        public int Id { get; set; }
        public string Name { get; set; }
}

 public class Item {
        public int Id { get; set; }
        public string Name { get; set; }
}

public class Order {
        public IList<OrderItemWrapper> ItemsList { get; set; }
        //Either one of these 2
        public Dictionary<Item, int> Items { get; set; }

        public User User { get; set; }
        public int Id { get; set; }
}

public class OrderItemWrapper {
        public Item Item { get; set; }//Will use ItemId as key
        public int Amount { get; set; }
}

A: Could you please go through my explanation for many-to-many relationship here.
Is the following tree of SchoolContext correct?


text:
Q: Sum employees based on mapping in another table I have one dynamic named range where I have the employees and their opportunities listed. the table also has a subtotal by employee. I have another table where I have a list of teams and the employees on those teams. The two tables are not the same size.
How do I sum up the employee totals from table 1 if they belong on the same team? In other words, how do I get the team total?
There is a similar question with an answer but when I try to use the sumif based on that answer, i am getting a #value error as the criteria range is not the same size.
Thanks


text:
Q: APNs not delivered to Ad-Hoc build I am working with an App which is using Apple Push Notifications.
I have permissions to use Push Notifications granted to the app.
When I was using xCode to install App I was able to receive APNS. However, when prepared ad-hoc build of my application the server (which is using URL = gateway.sandbox.push.apple.com ) was receiving from the service error "Invalid token".
So we decided to provide Production Certificate to server and it caused that there is no error returned but also no notification was delivered.
I have checked also app package and it seems to be OK:
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>XXXXXX</string>
<key>aps-environment</key>
<string>production</string>
<key>com.apple.developer.team-identifier</key>
<string>XXXXXX</string>
<key>get-task-allow</key>
<false/>
<key>keychain-access-groups</key>
<array>
<string>XXXXXX</string>
</array>
</dict>
</plist>

I am looking for a solution.

*

*I have APN Production Cert in Keychain Access (but without Private Key), but I can obtain a p12 file and import it that way with private key

*Maybe URL is wrong (but why it gives no error?)

I will be grateful for any help related to solving my problem.
Kind regards

A: The problem now was that we have been using for our tester ad-hoc deployment with development provisioning profile. And with X-Code6 there is no longer possible to do such thing. As a workaround we use XCode6 to package everything and XCode5 to export it.


text:
Q: Audio driver for iOS and OSX based on Core Audio Is it possible to have a common implementation of a Core Audio based audio driver bridge for iOS and OSX ? Or is there a difference in the Core Audio API for iOS versus the Core Audio API for OSX?
The audio bridge only needs to support the following methods:

*

*Set desired sample rate

*Set desired audio block size (in samples)

*Start/Stop microphone stream

*Start/Stop speaker stream

The application supplies 2 callback function pointers to the audio bridge and the audio bridge sets everything up so that:

*

*The speaker callback is called on regular time intervals where it's requested to return an audio block

*The microphone callback is called on regular time intervals where it receives an audio block

I was told that it's not possible to have a single implementation which works on both iOS and OSX as there are differences between the iOS Core Audio API and the OSX Core Audio API.
Is this true?

A: There are no significant differences between the Core Audio API on OS X and on iOS.  However there are significant differences in obtaining the correct Audio Unit for the microphone and the speaker to use.  There are only 2 units on iOS (RemoteIO and one for VOIP), but more and potentially many more on a Mac, plus the user might change the selection.  There are also differences in some of the Audio Unit parameters (buffer size, sample rates, etc.) allowed/supported by the hardware.


text:
Q: Find the page ranks of web pages Without damping, find the page ranks of the following webgraphs of three pages by determining their normalized eigenvectors for the eigenvalue of 1.
I don't know how to format this, but I'll do my best.
(a) 1 only goes to 3, 2 goes to 1 and 3, and 3 goes to 2
(b) 1 goes to 3, 2 goes to 1 and 3, 3 goes to 1
EDIT: I've added am imgur link since I have no clue how I'd write this in LaTex or text.

I do not understand how to set this up, the book and my professor were very vague in setting this up, as the book has two methods of solving this, but demonstrate these techniques using larger matrices, 6x6 and larger.
The answers are as follows;
(a) [1/5 2/5 2/5]^T
(b) [1/2 0 1/2]^T

A: Working backwards from the two answers, I would guess that you build a transition matrix $P$ for the graphs assuming equal probabilities for the page transitions. An element $p_{ij}$ of the matrix gives the probability of jumping to page $i$ from page $j$, so you would have nonzero entries in the $j$th column in the rows that correspond to the pages that are directly linked by page $j$, with a probability equal to $1$ over the total number of pages linked by that page. You then compute the null space of $P-I$ and normalize the resulting vector so that its components add up to $1$.
For example, the matrix for the first graph is $$P=\begin{bmatrix}0&\frac12&0\\0&0&1\\1&\frac12&0\end{bmatrix}.$$ Page 1 only goes to page 3, so the first column has a $1$ as its last element. Page 2 goes to 1 or 3 with equal probability, so there's a $\frac12$ in each of those slots of the second column. Page 3 only goes to page 2, so there a lone $1$ in that column, too.
We then find an eigenvector of $1$ by row-reducing $P-I$: $$\begin{bmatrix}-1&\frac12&0\\0&-1&1\\1&\frac12&-1\end{bmatrix}\to\begin{bmatrix}1&0&-\frac12\\0&1&-1\\0&0&0\end{bmatrix}$$ from which we can read the eigenvector $(1,2,2)$. Dividing this by the sum of its elements gives $\left(\frac15,\frac25,\frac25\right)$ as per the answer.