text:
Q: Error with %load_ext rpy2.ipython: "CompiledFFI' object has no attribute 'ffi" I am trying to run some R code in a predominantly Python script in Jupyter Notebook.
I have conda installed rpy2 on my terminal. Calling import rpy2 in my script works.
But when I try to run %load_ext rpy2.ipython (which is a necessary step to run R code), I have the following error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-fb23c6edefe4> in <module>
----> 1 get_ipython().run_line_magic('load_ext', 'rpy2.ipython')

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2312                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2313             with self.builtin_trap:
-> 2314                 result = fn(*args, **kwargs)
   2315             return result
   2316

</Users/dpatrick/opt/anaconda3/lib/python3.7/site-packages/decorator.py:decorator-gen-64> in load_ext(self, module_str)

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str)
     31         if not module_str:
     32             raise UsageError('Missing module name.')
---> 33         res = self.shell.extension_manager.load_extension(module_str)
     34
     35         if res == 'already loaded':

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/extensions.py in load_extension(self, module_str)
     78             if module_str not in sys.modules:
     79                 with prepended_to_syspath(self.ipython_extension_dir):
---> 80                     mod = import_module(module_str)
     81                     if mod.__file__.startswith(self.ipython_extension_dir):
     82                         print(("Loading extensions from {dir} is deprecated. "

~/opt/anaconda3/lib/python3.7/importlib/__init__.py in import_module(name, package)
    125                 break
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128
    129

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap.py in _gcd_import(name, package, level)

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap.py in _find_and_load(name, import_)

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap.py in _load_unlocked(spec)

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap_external.py in exec_module(self, module)

~/opt/anaconda3/lib/python3.7/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/ipython/__init__.py in <module>
----> 1 from . import rmagic
      2
      3 load_ipython_extension = rmagic.load_ipython_extension

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/ipython/rmagic.py in <module>
     53 # numpy and rpy2 imports
     54
---> 55 import rpy2.rinterface as ri
     56 import rpy2.rinterface_lib.callbacks
     57 import rpy2.robjects as ro

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/rinterface.py in <module>
      5 import typing
      6 from rpy2.rinterface_lib import openrlib
----> 7 import rpy2.rinterface_lib._rinterface_capi as _rinterface
      8 import rpy2.rinterface_lib.embedded as embedded
      9 import rpy2.rinterface_lib.conversion as conversion

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/rinterface_lib/_rinterface_capi.py in <module>
      8 from _rinterface_cffi import ffi
      9 from . import conversion
---> 10 from . import embedded
     11 from . import memorymanagement
     12

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/rinterface_lib/embedded.py in <module>
      6 from _rinterface_cffi import ffi
      7 from . import openrlib
----> 8 from . import callbacks
      9
     10 _options = ('rpy2', '--quiet', '--no-save')

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/rinterface_lib/callbacks.py in <module>
     34
     35 @ffi_proxy.callback(ffi_proxy._consoleflush_def,
---> 36                     ffi)
     37 def _consoleflush():
     38     try:

~/opt/anaconda3/lib/python3.7/site-packages/rpy2/rinterface_lib/ffi_proxy.py in decorator(func)
     42                                              'void', ('SEXP',))
     43 _evaluate_in_r_def = SignatureDefinition('_evaluate_in_r',
---> 44                                          'SEXP', ('SEXP args',))
     45
     46

AttributeError: 'CompiledFFI' object has no attribute 'ffi'

What exactly is this 'CompiledFFI' error? How should I fix it?
Thanks so much for your help!


text:
Q: Use of OCR to read node graphs I would like to code a program that will use a phones camera to read a node graph and then perform dijkstra's algorithm on it, displaying the shortest path.
Could pytesseract or other OCR tools for python read node graphs (such as in the image. Real use would be on printed ones) and give me enough information to get node coordinates and what letters are next to them, as well as the positions of the edges/which nodes they connect and what numbers are next to them?
Any help would be much appreciated.
https://i.stack.imgur.com/RUZwA.jpg

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSF 2.0 Warning about a component not surronded by an h:form tag I'm developing a crud web application using JSF 2.0. Editing my own jsf pages, it happens that I got the following warning message:

The form component needs to have a UIForm in its ancestry. Suggestion:
  enclose the necessary components within <h:form>

Is there any simple way to understand which component need to be surrounded by an <h:form> tag?


text:
Q: Neo4J Cypher - finding meeting point of two paths This is more of a "how to" question, there can be different ways but trying to find the most performant and effective way of solving this requirement.
I have a graph where there are nodes that act as fork nodes i.e. they spawn into two paths and these paths later meet at some other node, I know the node id and properties of the fork node (Node A in example below) and would like to know the node (Node B in ex below) at which the two paths meet.
Note - these paths can be of variable length i.e. one may have 6 nodes and the other only 2 nodes for e.g.
NodeA -[]-> Node 1 -[]-> Node 2 -[]-> Node 3 -[]-> Node 4 -[]-> Node 5 -[]-> Node 6 -[]-> Node B -[]-> Node C -[]-> Node D -[]-> Node E
NodeA -[]-> Node 7 -[]-> Node 8 -[]-> Node B -[]-> Node C -[]-> Node D -[]-> Node E

So if you see Node A spawns into two paths which finally meet again at Node B, so I want to get the Node B knowing Node A, pls suggest how we can do this in Cypher.
Thanks,
Deepesh

A: I'm going to assume that you know node a via it's id property and that it's 1234.  Also you may want to use labels here.  I'm not sure if you're using them or not, so I left them out.
MATCH
  (a)-[*1..10]->(b),
  (a)-[*1..10]->(b)
WHERE a.id = 1234
RETURN b

You could return the lengths of the paths too, but this should get you the result.  Also note that you can adjust the max length of the path (10 in this example) as a tradeoff on the performance of the query (it depends on the structure of your graph)
EDIT:
Also, if that doesn't work you may need to do:
MATCH
  path1 = (a)-[*1..10]->(b),
  path2 = (a)-[*1..10]->(b)
WHERE a.id = 1234 AND path1 <> path2
RETURN b

A: The answer to my question is as below (thanks to Brian - updating his answer with a LIMIT 1)
MATCH
path1 = (a)-[*1..10]->(b),
path2 = (a)-[*1..10]->(b)
WHERE a.id = 1234 AND path1 <> path2
RETURN b LIMIT 1

Adding LIMIT 1 to return only the intersection node otherwise it returns all the nodes following the intersection node also.


text:
Q: Why is pandas.dataframe.groupby faster when assigned to variable first? Can anyone please help understand why the following two ways of doing, what i thought was, otherwise the same thing with the pandas.dataframe groupby method, complete in such different times according to iPython's Magic %timeit?
%timeit somedf.groupby('someBoolColumn')['someBoolColumn'].count()
484 µs ± 9.52 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit grp = somedf.groupby('someBoolColumn')
grp['someBoolColumn'].count()
146 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

somedf has 7200 rows and 24 columns.
I cannot find,

*

*why the two liner assigning the object to variable grp first is >3
times faster, nor;

*if this is just specific to the groupby method or
    something more general to pandas or even python, for example, about
    variable assigment.
Many thanks for any enlightenment as this would really help with many much larger dataframes i'd like to process, repeatedly with many different combinations of parameters.

A: Ipython's %timeit docs  state:

In cell mode, the statement in the first line is used as setup code (executed
    but not timed) and the body of the cell is timed. The cell body has access to
    any variables created in the setup code.

(my emphasis). cell mode is triggered by using the double-percent form of %%timeit.
There is also a blurb in the documentation that IPython prints when you type %magic at the IPython prompt:

%%timeit x = numpy.random.randn((100, 100))
numpy.linalg.svd(x)

will time the execution of the numpy svd routine, running the assignment of x
  as part of the setup phase, which is not timed.

Thus,
%%timeit grp = somedf.groupby('someBoolColumn')
grp['someBoolColumn'].count()

is timing grp['someBoolColumn'].count(), but not the assignment grp = somedf.groupby('someBoolColumn').

How to use %%timeit without a setup line:
To use %%timeit to time both statements, simply leave the first line blank after %%timeit:
%%timeit
grp = somedf.groupby('someBoolColumn')
grp['someBoolColumn'].count()

The cell is finished by typing Enter twice.


text:
Q: Send Email using C# 2.0 I am trying to send an email but I am using asp.net c# 2.0
My server is supporting 2.0 version only. Is it possible to send email in 2.0 ?
protected void btnSubmit_Click(object sender, EventArgs e)
 {
  try
  {

   MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
   SmtpClient emailClient = new SmtpClient(smtp.gmail.com);
   emailClient.Send(message);
   litStatus.Text = "Message Sent";

  }
  catch (Exception ex)
  {
   litStatus.Text=ex.ToString();
  }
 }

A: I've just tested this and it works nice:
     public static void Send()
    {
        SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

        MailMessage MyMailMessage = new MailMessage("sender@gmail.com", "receiver@ymail.com",
            "subject", "message");
        MyMailMessage.IsBodyHtml = false;
        NetworkCredential mailAuthentication = new NetworkCredential("your_email@gmail.com", "password");

        mailClient.EnableSsl = true;
        mailClient.UseDefaultCredentials = false;
        mailClient.Credentials = mailAuthentication;
        mailClient.Send(MyMailMessage);
    }

I've also been here and turned on the access for less secure applications:
https://www.google.com/settings/security/lesssecureapps

A: According to the MSDN documentation SmtpClient was introduced in .NET 2.0, so you should be able to send emails in 2.0 using your code

A: You need to provide credentials:
NetworkCredential _Credentials =
new NetworkCredential("username", "password");
...

SmtpClient emailClient = new SmtpClient("smtp.gmail.com", 587); // I don't know gmails port it might be 465
smtpClient.UseDefaultCredentials = false;
emailClient.Credentials = _Credentials;

EDIT.
According to exception You pasted in comments try also to add following line:
emailClient.EnableSsl = True;

A: Try System.Net.Mail
and select the 2.0  version.


text:
Q: tar.Z file format, structure, header I am trying to figure out the file layout of
tar.Z file. (so called .taz file. compressed tar file).
this file can be produced with tar -Z option or
using unix compress utility(result are same)
I tried to google some document about this file structure
but there is no documentation about this file structure.
I know that this is LZW compressed file and starts with
its magic number "1F 9D" but thats all I can figure out.
someone please tell me more details about the file header or
anything.
I am not interested about how to uncompress this file, or
what linux command can process this file.
I want to know is internal file structure/header/format/layout.
thank you in advance

A: A .Z file is compressed using compress and can be uncompressed with uncompress (or on some machines this is called uncompress.real). This .Z file can hold any data. .tar.Z or .taz is just a .tar file that is compressed with compress.
The first 2 bytes (MAGIC_1 and MAGIC_2) are used to check if the .Z file really is a .Z file, and not something else with accidentally the same extension. These bytes are hardcoded in the sources.
The third byte is a settings byte and holds 2 values:

*

*The most significant bit is the block mode.

*The last 5 bits indicate the maximum size of the code table (the code table is used for lzw compression).

From the original code: BLOCK_MODE=0x80; byte3=(BIT|BLOCK_MODE); and BIT is in an if/else block where it is 12..16.
If block mode is turned on, in the code table a entity will be added at place 256 (remember 0..255 are filled with the values 0..255) and this will  contain the CLEAR sign. So whenever the CLEAR sign is gotten from the data stream from the file, the code table has to be reverted to it's initial state (so it has only 0..256 in it).
The maximum code size indicates the amount of bits the code table can be. When the maximum is hit, there are no entities added to the code table anymore. So if the maximum code size is 0b00001100, it means that the code table can only hold 12 bits, so a maximum of 2^12=4096 entities.
The highest amount possible that is used by compress is 16 bit. That means that there are 2 bits in this settings field that are unused.
After these 3 bytes the raw LZW data starts. Because the LZW table starts at 9 bits, the 4th byte will be the same as the first byte of the input (in case of a .tar.Z file, or taz file, this byte will be the first byte of the uncompressed .tar file).

A: A tar.Z file is just a compressed tar file, so you will only find the 1F 9D magic number telling you to uncompress it.
When uncompressed you can read the tar file header:
http://www.fileformat.info/format/tar/corion.htm

A: Q: this file can be produced with tar -Z option or using unix compress utility(result are same)
A: Yes.  "tar -cvf myfile.tar myfiles; compress myfile.tar" is equivalent to using "-Z".  An even better choice is often "j" (using BZip, instead of Zip)
Q: What is the layout of a tar file?
A: There are many references, and much freely available source.  For example:

*

*http://en.wikipedia.org/wiki/Tar_%28file_format%29
Q: What is the format of a Unix compressed file?
A: Again: many references; easy to find sample source code:

*

*http://en.wikipedia.org/wiki/Compress
Fot a .tgz (compressed tar file) you'll need both formats: you must first uncompress it, then untar it.  The "tar" utility will do both for you, automagically :)


text:
Q: how to delete specific data from text file and then update it I have a large text file. I read data from text file one at a time and check whether data agree with my condition. If not I want to delete that data in text file and update it.
For example say my data text file is:
100
201
302
455
Suppose I want to delete second one. After deletion I want new text file to be look like
100
302
455
(without any gap between 100 and 302). Since my text file is large around 100MB, I want to read data one by one rather than loading all at once. Thanks

A: 100MB is small compared to today's RAM sizes.  Why not load it all at once?  Then it's just a matter of using DeleteCases and exporting the file.
Otherwise I don't believe Mathematica is natively equipped to modify a file piece by piece in that fashion so you'll need to export to a second file.  As an example I'll filter a list of natural numbers to keep only the primes.  (It would be a trivial use of Not to drop the primes.)
First generate the starting data:
Export["firstfile.txt", Range@100, "Table"];

Open the input and output streams:
in = OpenRead["firstfile.txt"];
out = OpenWrite["secondfile.txt"];

Read, filter, and export:
Module[{x},
 While[x =!= EndOfFile,
  x = Read[in];
  If[PrimeQ@x, Write[out, x]]
 ]
]

Close the streams:
Scan[Close, {in, out}]

The result:
FilePrint["secondfile.txt"]

2
3
5
7
11
13
...

Note:  practically I would include in and out in my Module but here it made it harder to comment the code as I wanted.


text:
Q: How to shut down a minecraft server with python? I have multiple minecraft servers running on the machine. servers are started with bat files that have according titles. My question is that, how can i shut down a certain minecraft server with python? Or how to kill a titled cmd.exe process with python?

A: I would look at the tools in the os module, it would also help if i had more information about what operating system you are using.

A: os.kill to kill by PID

To kill by name, try psutil. You could kill all you "minecrafts" that way:
for proc in psutil.process_iter():
    if proc.name == "minecraft.exe":
        proc.kill()

By exploring psutil you might be able to find a solution to kill some of them. My best bet would be by using the cmdline attribute of the Process class.

A: I ended up using autohotkey. launched autohotkey with python and made separate  .ahk files for every server.


text:
Q: How to pass data to an external assembly User Control through MEF I am a beginner in MEF. According to my requirement I have to show the multiple plugin UI according to the selection of plugin. For that I have to pass plugin related data to the external plugin UserControl.
[InheritedExport(typeof(IConnect))]

public interface IConnect{}

Below code is using to initializing the external UI from the main application,
[ImportMany(typeof(IConnect))]

public IEnumerable<Lazy<IConnect>> Plugins;

....
var catalog = new DirectoryCatalog(@"C:\TestDll\");

var container = new CompositionContainer(catalog);

container.ComposeParts(this);

var childControl = SelectedPlugin as UserControl;

//Here I have to pass the required data to the usercontrol. How to do this?
Dockpanel.Children.Add(childControl );

Could you please suggest a way to pass data to the external user control

A: Our entire team here at work has been using MEF for years now, and I'm reasonably familiar with how it works.
To get everything bootstrapped off the ground, the first thing to do is ensure that a common MEF container is shared between your main application and the user control in your external assembly.
If you don't have a common MEF container, then your MEF imported classes will never be able to communicate with the host application, as they will be living in separate MEF universes.
Once you have a common container, anywhere you want to bootstrap a class out of the container, you can use something like this:
var test = MefContainer.GetExportedValue<ITest>();
test.Run();

Q. How do I add MEF to my project?
A. Using NuGet, search for "microsoft composition", and add MEF 2.
Q. So how do we create this shared MEF container?
A. As follows:

*

*Follow through a tutorial such as From Zero to Proficient with MEF.

*Create a class library that is shared between your imported control, and the host application.

*In this class library, create a singleton class called MefContainer. This means that anybody that wants to grab something out of the MEF container can reference this singleton to obtain the MEF container. The MEF container contains classes from all of the auto-discovered assemblies in the directories that we want to scan.

Q. How do I communicate with the user control?
A. Add this class to your shared class library:
public interface ITest
{
    string SharedValue { get; set; }
}

[Export(typeof(ITest))]
public class Test : ITest
{
    [ImportingConstructor]
    public Test()
    {

    }

    public string SharedValue { get; set; }
}

Now, both the host app and the user control can grab an instance of the same class out of the MEF container:
var test = MefContainer.GetExportedValue<ITest>();
var result = test.SharedValue;

By default, classes that are obtained from the MEF container are singleton's, unless we explicitly say that we want non-shared classes.
Q. How about adding Reactive Extensions (RX)?
It's ok to have a class with shared values. But it's nicer if one component can fire events off, and any other component can listen to this event.
To do this, add RX to your project using NuGet (search for "reactive extensions", add "Reactive Extensions - Main Library").
Add a Subject to your shared class:
private Subject<string> MyEvent { get; set; }

Now, if you have a MEF reference to this shared class, you can send an event out:
var t = MefContainer.GetExportedValue<ITest>();
t.MyEvent.OnNext("hello");

And, any other class can subscribe to these events:
var t = MefContainer.GetExportedValue<ITest>();
t.MyEvent.Subscribe(
    o =>
    {
        Console.Write(o);
    });

If code is already running in the MEF composition container, then there is no need to use MefContainer to get at the container. You can simply MEF import the shared communication class using the constructor:
public interface IClassRunningInContainer
{
}

[Export(typeof(IClassRunningInContainer))]
public class ClassRunningInContainer : IClassRunningInContainer
{
    [ImportingConstructor]
    public ClassRunningInContainer(ITest t)
    {
        t.OnNext("Hello, world!");
    }
}

Final Notes
Don't make the mistake of using MEF as a general dependency injection (DI) solution. You will run into roadblocks further down the road, as MEF is does not have the level of built in diagnostics to find out if things have gone wrong, compared to a dedicated dependency injection solution, such as Unity.
The ideal pattern is to use MEF for importing whole assemblies, then use Unity as your day to day DI container.


text:
Q: Java Iterator Infinite Loop Can't figure out why this is looping infinitely.
public void DLCCheck(IconSet iconSet) {
    Log.d(TAG, "Got dlc check. Looking to see if we need to remove any notes from the current list.");
    int foundCount = 0;
    for(Iterator<Item> i = mItemList.iterator(); i.hasNext(); ) {
         if(i instanceof NoteItem && ((NoteItem) i).getIconSet() == iconSet) {
             i.remove();
             foundCount++;
         }
    }
    Log.d(TAG, "Finished searching. Found " + foundCount + "notes in the current list to delete.");
    //notifyDataSetChanged();
    //EventBus.getDefault().post(new MoveNoteListOut());
}

Shouldn't this stop iterating when hasNext returns false? There are only 6 items in this list, yet it loops forever.

A: You're never calling i.next(). Also, i is instanceof Iterator, so i instanceof NoteItem will never be true. You should read the data in i.next() and evaluate such element with your conditions.
This in how the code should be:
for(Iterator<Item> i = mItemList.iterator(); i.hasNext(); ) {
     Item item = i.next();
     if(item instanceof NoteItem && ((NoteItem) item).getIconSet() == iconSet) {
                                 //here ---------------------------^^
                                 //not sure what type returns getIconSet
                                 //but if it's not a primitive then you should use equals
         i.remove();
         foundCount++;
     }
}


text:
Q: Count consecutive event ocurrence of string row value A per row value B in R I have a big data set with multiple football matches. Right now the format is wide and I want to count winning streaks, drawing streaks and loosing streaks and teams by their match.
In this case I have the following variables:

*

*Home_team: a string with a name of a country (Example: England, Spain, etc)

*Away_team: a string with a name of a country (Example: France, Germany, etc)

*Results: a string with three categories (HW: Home win, AW: Away win, D: Draw)

To give a simple example, my data looks something like this:
Home_team <- c("Peru","France","England","Senegal", "Chile", "Colombia","France","Spain","Colombia", "Angola", "Ecuador", "France",
               "Peru")
Away_team <- c("Brasil","Germany","Togo","Egypt", "Ecuador", "Argentina","Netherlands","Burkina Faso","New Zealand", "Venezuela", "Portugal", "Canada",
           "United States")
Results <- c("HW","HW","AW","D","AW","HW","HW","AW","HW","D","D","HW","D")

df_example <- data.frame(Home_team,Away_team,Results)
df_example

So in this example the following things happened:

*

*Peru (row 1) had a winning streak of 1 entering the game against the United States and drew the match.

*France entered a winning streak of 2 matches to their game against Canada.

*Colombia would be also entering a 2 game winning streak.

*Ecuador lost against Chile (1 game losing streak) and then drew against Portugal in their next match.

I was thinking that an easier way to do this is put everything in long format and count "Wins", "Losses" and "Draws". And every time the streak stops the counting starts again. But I am not sure if that is the best approach.
The big picture is that I would like to know if streaks (winning, loosing or even drawing) has an effect on the result of the next match.
Any help would be highly appreciated.

A: Here is one approach to try.
First, put data into long form. Using case_when you can determine the outcome for each each (e.g., the home team with "HW" game gets a "Win", while the away team gets a "Loss").
For each team, you can group the streaks using rleid from data.table. Every time the outcome changes, it moves on to a new streak.
Then, you can count up the number of games in a streak for a given team and outcome. It will be the row_number() for a given streak, team, and outcome.
Finally, you put back into wider form if desired. The new columns indicate the streak (number of games, and outcome) for the home and away teams, coming into the current game.
library(tidyverse)
library(data.table)

df_example %>%
  mutate(Game = row_number()) %>%
  pivot_longer(cols = c(Home_team, Away_team), names_to = "Location", values_to = "Team") %>%
  mutate(Outcome = case_when(
    Results == "HW" & Location == "Home_team" ~ "Win",
    Results == "HW" & Location == "Away_team" ~ "Loss",
    Results == "AW" & Location == "Home_team" ~ "Loss",
    Results == "AW" & Location == "Away_team" ~ "Win",
    Results == "D" ~ "Draw",
    TRUE ~ NA_character_
  )) %>%
  group_by(Team) %>%
  mutate(Change = rleid(Outcome)) %>%
  group_by(Change, .add = T) %>%
  mutate(Streak = row_number()) %>%
  group_by(Team) %>%
  mutate(Last = paste(lag(Streak, default = 0), lag(Outcome, default = "-"))) %>%
  pivot_wider(id_cols = c(Game, Results), names_from = Location, values_from = c(Team, Last))

Outcome
    Game Results Team_Home_team Team_Away_team Last_Home_team Last_Away_team
   <int> <chr>   <chr>          <chr>          <chr>          <chr>
 1     1 HW      Peru           Brasil         0 -            0 -
 2     2 HW      France         Germany        0 -            0 -
 3     3 AW      England        Togo           0 -            0 -
 4     4 D       Senegal        Egypt          0 -            0 -
 5     5 AW      Chile          Ecuador        0 -            0 -
 6     6 HW      Colombia       Argentina      0 -            0 -
 7     7 HW      France         Netherlands    1 Win          0 -
 8     8 AW      Spain          Burkina Faso   0 -            0 -
 9     9 HW      Colombia       New Zealand    1 Win          0 -
10    10 D       Angola         Venezuela      0 -            0 -
11    11 D       Ecuador        Portugal       1 Win          0 -
12    12 HW      France         Canada         2 Win          0 -
13    13 D       Peru           United States  1 Win          0 -


text:
Q: Firefox и подключаемые шрифты Firefox не хочет отображать шрифт. Chrome, Safari и Opera отображают нормально. Делаю так:
<head>
    <link href="http://allfont.ru/css/?fonts=cyrillicold" rel="stylesheet" type="text/css" />
</head>

А в CSS соответственно просто пишу:
font-family: "CyrillicOld", Arial, sans-serif;

Может и не самый лучший вариант - подключать вот так. Лучше было бы залить шрифт в папку сайта и подключать через CSS с @font-face. Но переделывать очень не хочется. Подскажите, что можно с этим сделать?

A: Текст такой должен быть?

Если да, то у вас другой тег затирает этот.
И еще один косяк при такой загрузке: при слабой скорости интернета буквы моргают. Сначала стандартный шрифт, потом только подгружается этот шрифт.
Делал на Firefox 38.0.5.


text:
Q: Django can't call custom django commands extwith call_command This is probably a really basic question but I can't find the answer anywhere for some reason. I created a custom command which I can call from the command line with python manage.py custom_command. I want to run it from elsewhere but don't know how to do so. I have added pages to my INSTALLED_APPS in settings.py. This question: Django custom command works on command line, but not call_command is very similar but I'm not sure what the answer means and I think it's unrelated. My file structure is :
├── custom_script
│   ├── script.py
│   ├── __init__.py
├── project
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── pages
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── __init__.py
│   ├── management
│   │   ├── commands
│   │   │   ├── __init__.py
│   │   │   └── custom_command.py
│   │   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py

content of script.py
from django.core.management import call_command
call_command('custom_command', 'hi')

content of custom_command.py
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('message', type=str)

    def handle(self, *args, **options):
        print('it works')

I want to run python custom_script/script.py which will call the custom_command but keep getting: django.core.management.base.CommandError: Unknown command: 'custom_command'. I have isolated the problem to the fact that django can't see my command as when I run print(management.get_commands()) my custom command is not listed. Additionally, after looking through the django python code for management for a while I noticed this settings.configured variable which upon checking is False which means it only passes in the default commands when management.get_commands is run. How can I get this to become True? Technically, I could use a subprocess if I really wanted to but since there is already a call_command feature I figured I'd try and use it.

A: Not sure if this will help anyone, but it turns out I was doing this the wrong way. Generally, I don't think my method above will work because you have to call a django command from outside the django project basically which means the settings will not be configured. My use case was running a django command in the background on a webserver using script.py as the file to run the command. If your use case is similar you should instead call the custom command directly from the command line with python manage.py custom_command, this worked for me at least.

A: If somebody is using poetry, pytest and pytest-django and configuring your pytest configuration using pyproject.toml, you are probably getting "Command not found". That's because poetry new uses 5.x for pytest for some reason while pytest docs clearly states that you have to use 6.x in order to use pyproject.toml as config file.
Edit pytest to ^6.0 in your pyproject.toml and run poetry update. Now it should work.


text:
Q: How to go back to main scene when my game paused in sprite kit When I pause my game I have a pause scene.
I put there 3 buttons :

*

*RateApp button

*BackToMain button.

*ResumeGame button.
what happens:

*

*RateApp button working.

*ResumeGame button working.
Not working :

*

*BackToMain button.

Why?
because my game still pause.
PauseGame function
func pauseGame() {
        isPause = true
        self.view?.paused = true
        pointsLabel.hidden = true
        BooCharacter.hidden = true
        PauseButton.hidden = true
        if #available(iOS 9, *) {
        RecordButton.hidden = true
        }

        PauseScreen = SKSpriteNode()
        PauseScreen.name = "PauseScreen"
        PauseScreen.position = CGPointMake(self.size.width/2, self.size.height/2)
        PauseScreen.color = UIColor.blackColor()
        PauseScreen.alpha = 0.9
        PauseScreen.size = CGSizeMake(1242,2208)
        addChild(PauseScreen)

        PauseLable.text = "Pause"
        PauseLable.fontSize = 75
        PauseLable.fontName = "Futura-Medium"
        PauseLable.fontColor =  UIColor(red:0.98, green:0.82, blue:0.32, alpha:1.0)
        PauseLable.position = CGPoint(x: self.size.width/2, y: self.size.height/2 + 170)
        addChild(PauseLable)

        ContinueButton.name = "CountinueButton"
        ContinueButton.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        ContinueButton.size = CGSizeMake(100, 100)
        addChild(ContinueButton)

        HomeButton.position = CGPoint(x: self.size.width/2 - 50, y: self.size.height/2 - 200)
        HomeButton.size = CGSizeMake(70 , 70)
        HomeButton.name = "HomeButton"
        HomeButton.runAction(SKAction.moveToY(90, duration: 0.6))
        HomeButton.removeFromParent()
        addChild(HomeButton)

        RateButton.position = CGPoint(x: self.size.width/2 + 50, y: self.size.height/2 - 200)
        RateButton.size = CGSizeMake(70 , 70)
        RateButton.name = "RateButton"
        RateButton.runAction(SKAction.moveToY(90, duration: 0.6))
        RateButton.removeFromParent()
        addChild(RateButton)

    }

Updated :
    let scene = GameScene(fileNamed:"GameScene")
    var HomeButton : UIButton!
    var RateButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        if (scene != nil) {
            // Configure the view.
            let skView = self.view as! SKView
            //skView.showsFPS = true
            //skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true
            //skView.showsPhysics = true

            NSNotificationCenter.defaultCenter().addObserver(self, selector: "goBack", name: "goBackClick", object: nil);

            /* Set the scale mode to scale to fit the window */
            scene!.scaleMode = .AspectFill

            skView.presentScene(scene)
        }
}

        override func viewWillLayoutSubviews() {
            super.viewWillLayoutSubviews()

                HomeButton.frame = CGRectMake(self.view!.frame.size.width/2 - 50, self.view!.frame.size.height/2 - 200, 70, 70)
                HomeButton.setImage(UIImage(named: "HomeButtonPause.png"), forState: UIControlState.Normal)
                HomeButton.addTarget(self, action: "pressedHomeButton", forControlEvents: .TouchUpInside)

                RateButton.frame = CGRectMake(self.view!.frame.size.width/2 + 50, self.view!.frame.size.height/2 - 200, 70, 70)
                RateButton.setImage(UIImage(named: "RateButtonPause.png"), forState: UIControlState.Normal)
              RateButton.addTarget(self, action: "pressedRateButton", forControlEvents: .TouchUpInside)

            self.view.addSubview(HomeButton)
            self.view.addSubview(RateButton)
        }

  func pressedHomeButton(sender: UIButton!) {
       //Back to main screen
     SKTAudio.sharedInstance().playSoundEffect("Click Button Sound.mp3");
          NSNotificationCenter.defaultCenter().removeObserver(self, name: "goBackClick", object: nil)
    self.dismissViewControllerAnimated(true, completion: {
    });

    }

      func pressedRateButton(sender: UIButton!) {
            //Rate App
            SKTAudio.sharedInstance().playSoundEffect("Click Button Sound.mp3");
            UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/us/app/boo-adventure/id1030047247?ls=1&mt=8")!)  //add your link here
            print("Rate App!")

        }

i trying to create 2 subviews for my 2 button (Home Button , Rate Button)
and i created UIButtons for them but Xcode return error!
PauseGame function Updated!
   func pauseGame() {
        isPause = true
        GameViewController().ContinueGame()
        pointsLabel.hidden = true
        BooCharacter.hidden = true
        PauseButton.hidden = true
        if #available(iOS 9, *) {
        RecordButton.hidden = true
        }

        PauseScreen = SKSpriteNode()
        PauseScreen.name = "PauseScreen"
        PauseScreen.position = CGPointMake(self.size.width/2, self.size.height/2)
        PauseScreen.color = UIColor.blackColor()
        PauseScreen.alpha = 0.9
        PauseScreen.size = CGSizeMake(1242,2208)
        addChild(PauseScreen)

        PauseLable.text = "Pause"
        PauseLable.fontSize = 75
        PauseLable.fontName = "Futura-Medium"
        PauseLable.fontColor =  UIColor(red:0.98, green:0.82, blue:0.32, alpha:1.0)
        PauseLable.position = CGPoint(x: self.size.width/2, y: self.size.height/2 + 170)
        addChild(PauseLable)

        ContinueButton.name = "CountinueButton"
        ContinueButton.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        ContinueButton.size = CGSizeMake(100, 100)
        addChild(ContinueButton)

        GameViewController().viewWillLayoutSubviews()

    }

A: Try this to take you back to the beginning of your GameScene
func goToGameScene(){
    let gameScene:GameScene = GameScene(size: self.view!.bounds.size) // create your new scene
    let transition = SKTransition.fadeWithDuration(1.0) // create type of transition (you can check in documentation for more transtions)
    gameScene.scaleMode = SKSceneScaleMode.Fill
    self.view!.presentScene(gameScene, transition: transition)
    }

if this doesn't work let me know.


text:
Q: HDIV confidentiality true problam with Select element I am populating a select element using EL values and getting problem
<form:select path="district" cssClass="inputText">
    <option value="" title='${SELECT_DISTRICT}'>
       <c:out value="--${SELECT_DISTRICT}--"></c:out>
    </option>
    <form:options items="${districtList}"/>
</form:select>

When i have changed configuration confidentiality="true" in hdiv-config.xml it is giving select values as incrementing number starting from "0" and while making confidentiality="false" populating values as desired.

A: I do not understand exactly what is your issue, because it seems you are describing the HDIV confidentiality behaviour. I mean, when the confidentiality is activated HDIV hides real values (using instead relative values such as:0,1,2..) and when the confidentiality is deactivated render real values.
Could you give please more information about the issue?
Anyway when you use select tag (I suppose you are using Spring MVC tags) you should use also spring mvc option tag:
<form:select path="username">
    <form:option value="j2ee" label="j2ee" />
</form:select>

See: Spring MVC sample
Regards,
Roberto Velasco (HDIV team)


text:
Q: Getting MessageEdited for last 100 message for each chat I have registered MessageEdited event in my telethon, but I have got only a few of them. I think there is a limit on the count of last messages of each chat, that telegram sends updates for them. If yes, how many is that?
And also how can I receive updates for last 100 messages per chat, in telethon?


text:
Q: How do you build a custom plane geometry in three.js? I want to create a plane in three.js, but with more points than default (so I don't want to use PlaneGeometry, as I don't think it will let me define custom points).  The reason being is that I want to be able to animate or move any given point in time.
This is what I have so far:
var camera;
var scene;
var renderer;
var mesh;

init();
animate();

function init() {

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000);

    var light = new THREE.DirectionalLight( 0xffffff );
    light.position.set( 0, 1, 1 ).normalize();
    scene.add(light);

    var geometry = new THREE.PlaneGeometry( 50, 50);

    var texture = THREE.ImageUtils.loadTexture('images/03032122.png', {}, function() {
    renderer.render(scene, camera);
    })
    var material = new THREE.MeshBasicMaterial({map: texture, transparent: true })

    mesh = new THREE.Mesh(geometry, material );
    mesh.position.z = -50;
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setSize( window.innerWidth, window.innerHeight );

    renderer.setClearColor( 0xffffff, 1);
    document.body.appendChild( renderer.domElement );

    window.addEventListener( 'resize', onWindowResize, false );

    render();
}

function animate() {
    //mesh.scale.x+= 0.0003;

    render();
    requestAnimationFrame( animate );

}

function render() {
    renderer.render( scene, camera );
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}

What I'm looking to do, is create something like this:
http://www.math.ubc.ca/~cass/courses/m308-02b/projects/schweber/square%20tiles.gif

A: Becare about PlaneGeometry, it is deprecated (so it will be removed in a next revision). Use PlaneBufferGeometry instead.
@pailhead's answer is correct if you want the 'normal' plane division.
If you want the vertices to have other positions you would have to build the geometry vertex per vertex that is something else*.
Also and that answers your need to move/animate the vertices later, you can change each vertex'position after the geometry creation by writing :
planeMesh.geometry.vertices[i].set(x,y,z);// this way you can move each vertex coordinates
planeMesh.geometry.verticesNeedUpdate=true;

* : example for a plane with 4 vertices (=2 triangles) :
var geo=new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(x1,y1,z1),//vertex0
    new THREE.Vector3(x2,y2,z2),//1
    new THREE.Vector3(x3,y3,z3),//2
    new THREE.Vector3(x4,y4,z4)//3
    );
geometry.faces.push(
    new THREE.Face3(2,1,0),//use vertices of rank 2,1,0
    new THREE.Face3(3,1,2)//vertices[3],1,2...
    );

of course what makes this geometry a plane is that the 4 vertices are coplonar.
When you create a geometry with many faces, you understand you need a pen + paper to draw your faces :) Depending on your geometry you can also use an algorithm.

A: I created my customized plane, using:
        // Plane
            var size = 500, step = 100;
            var geometry = new THREE.Geometry();
            for ( var i = - size; i <= size; i += step ) {

                geometry.vertices.push( new THREE.Vector3( - size, 0, i ) );
                geometry.vertices.push( new THREE.Vector3(   size, 0, i ) );

                geometry.vertices.push( new THREE.Vector3( i, 0, - size ) );
                geometry.vertices.push( new THREE.Vector3( i, 0,   size ) );

            }

            var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.5 } );

            var line = new THREE.Line( geometry, material, THREE.LinePieces );
            scene.add( line );

A: Try adding two more arguments to THREE.PlaneGeometry.
THREE.PlaneGeometry( width , height, widthSegments , heightSegments)
consult the library (look at a function call), consult the documentation.
This might also possibly be used:
http://threejs.org/docs/#Reference/Extras.Geometries/ParametricGeometry

A: If you want to add a plane with custom borders I recommend you to change the position attribute array directly and updating the geometry points position:
// Here you chose the divisions in x
    const x_lenght = 1
    const divisions = 10

    let geometry = new THREE.PlaneBufferGeometry( x_lenght, 1, divisions, 1 )
    let material = new THREE.MeshPhongMaterial( { color: 0xecf0f1, wireframe: true } )

    let pointPos = geometry.getAttribute("position").array

    for (let i = 0; i < divisions + 1; i++) {
      let x = pointPos[3 * i] + x_lenght/2

      // This case is making y = x^2
      pointPos[3 * i + 1] = Math.pow(x, 2)
      pointPos[3 * ( divisions + 1 ) + 3 * i + 1] = - pointPos[3 * i  + 1]

      console.log(`x = ${pointPos[3 * i]}; y = ${pointPos[3 * ( divisions + 1 ) + 3 * i + 1]}`)

        }

    pointPos.needsUpdate = true;

    mesh = new THREE.Mesh(geometry, material )

    scene.add(mesh)

Here is my example https://codepen.io/ferrari212/pen/bGpgLBd?editors=0010


text:
Q: express how to handle errors with redirects & messages I can't seem to wrap my head around how to properly handle errors.
The basic 404, is no problem (simply set header 404 and render 'not found' page). But let's say for example:
You find a user by id, but the user doesn't exist. I suppose for this you set the header-status to 500. But how do you redirect the page back (or simply assign a redirect page) and set a flashmessage?
In most tutorials I usually find the following:
model.SignUp.forge({id: req.params.id}).fetch({withRelated: ['usermeta']}).then(function(user) {
    res.render('admin/pages/users/details', {title: 'Signups', error: false, details: user});
  }).catch(function(err) {
    res.status(500).json({error: true, data: {message: err.message}});
  });

You simply catch the problem whenever an error occurs. I also come across this sometimes:
transporter.sendMail(mailOptions, function(err) {
    if(err) {
        req.flash('error', 'blablabla');
        res.redirect('back');
    }
});

In the first case you return a json file but no redirect or render. In the second part no status has been provided.
What practices do you guys implement?

A: I'm a huge fan of central error handling in my express apps.  How does this work?  Well, I have a library of HTTP error objects that all have a 'status' property on them.  All my route handlers and middeware return a callback with one of those error objects depending on what happened, and do not call res.send (or any other res.* method) if there was an error.  I then have an error handling middleware (or more than one, if I it's getting to be complex) that decides if I want to do a redirect or just send the response code, or whatever depending on the needs of the app.
Taking your example:
app.post('/signup', function(req, res, next){
  model.SignUp.forge({id: req.params.id}).fetch({withRelated: ['usermeta']}).then(function(user) {
    res.render('admin/pages/users/details', {title: 'Signups', error: false, details: user});
  }).catch(function(err) {
    return next(new HttpServerError(err));
  });
}

an HttpServerError has a status of 500, and so I have at least a 'catch all' error handling middleware that looks like this (in the case of a json api):
app.use(function(err, req, res, next){
  console.log(err.stack);
  res.status(err.status).send({message: err.clientMessage});
});

You can also do multiple handlers, and render or redirect based on the state of the request (e.g. accepts headers or type of error).
For example, in a traditional web app, I might use the name of the error to figure out what template to render, and I might redirect to a login page if it's a 403 error.
For sake of completeness, here's an example HttpServerError:
'use strict';

const util = require('util');

function HttpServerError(message){
  this.message = message;
  this.clientMessage = 'Dangit! Something went wrong on the server!';
  this.status = 500;
  Error.captureStackTrace(this, NotFoundError);
}

util.inherits(HttpServerError, Error);

HttpServerError.prototype.name = 'HttpServerError';

module.exports = HttpServerError;


text:
Q: Processing : how to set an image to the foreground I would like to know if somebody can help me to set an image to the foreground using processing.
I have a sketch where a video is displayed in a continuous loop and above this video, there is an alpha mask to see the video where it is transparent.
Then, the video from the webcam is triggered with an IR proximity sensor. This video is warped with a cylinder, and I would like the video be under the mask because I will enlarge it to fit with the mask.
I search on internet but nothing about it.
I tried to move the lines above, under the video but nothing works. I did it with the previous version when there was no warping and I simply move two lines and it has working. But now I have this warping, nothing works, it drives me crazy...
Thanks so much for your help.
Here my code :
///////////////////////////////////////////////////////
EDIT
///////////////////////////////////////////////////////
Thanks again for your help, and sorry about the link, I didn't know.
I know how to use a movie/video from the webcam/picture as a texture, that's not my problem.
The problem I encounter is that I would put a mask above the shape with the texture on it, and I don't know how to do it, I try and search many many things. I'm dealing with this problem since 3 days...
So, here my code where I isolate the problem (MCVE), about the mask, I created it with photoshop: a simple shape with black background and transparency shape in the middle, exported for web in PNG format with transparency.
int tubeRes = 32;
float[] tubeX = new float[tubeRes];
float[] tubeY = new float[tubeRes];
PImage img;
PImage masque;

void setup() {
  size(1280, 1024, P3D);
  img = loadImage("berlin-1.jpg");
  masque = loadImage("mask.png");
  float angle = 210.0 / tubeRes;
  for (int i = 0; i < tubeRes; i++) {
    tubeX[i] = cos(radians(i * angle));
    tubeY[i] = sin(radians(i * angle));
  }
  noStroke();
}

void draw() {
  translate(width / 2, height / 2);
  beginShape(QUAD_STRIP);
  texture(img);
  for (int i = 0; i < tubeRes; i++) {
    float x = tubeX[i] * 120;
    float z = tubeY[i] * 100;
    float u = img.width / tubeRes * i;
    vertex(x, -270, z, u, 0);
    vertex(x, 230, z, u, img.height);
  }
  endShape();
  beginShape(QUADS);
  texture(img);
  vertex(0, -100, 0, 0, 0);
  vertex(100, -100, 0, 100, 0);
  vertex(100, 100, 0, 100, 100);
  vertex(0, 100, 0, 0, 100);
  endShape();
  translate(-640, -515);
}

enter image description here

A: You're going to have to start smaller, and you're going to have to isolate your problems into a simpler sketch. Right now you've got a ton of things going on: playing a video file, camera capture, serial sensors, image masking, and OpenCV logic. That's way too much to debug at one time.
Instead, create a much smaller example sketch that only does one thing. Start with a sketch that simply shows a video playing. When you get that working, then add logic that uses the video as a texture.
Here's an example MCVE that shows how to use a video as a texture:
import processing.video.*;

Movie movie;

void setup() {
  size(500, 500, P3D);
  frameRate(30);
  movie = new Movie(this, "DSC_1940.MOV");
  movie.loop();
}

void draw() {

  background(0);

  beginShape();
  texture(movie);

  vertex(mouseX, mouseY, 0, 0);
  vertex(400, 100, movie.width, 0);
  vertex(400, 400, movie.width, movie.height);
  vertex(100, 400, 0, movie.height);

  endShape();
}

void movieEvent(Movie myMovie) {
  myMovie.read();
}

Please notice that this is much simpler than your code, and it only does one thing at a time. Start over with something like this, and try to hardcode as much as possible. We don't need to see your serial code, and if possible we don't need to see anything from your webcam or from OpenCV.
Take this example sketch and add logic to use an image mask, or to use a cylinder instead of a square. (But again, don't include any logic that isn't directly related to your problem!) Then when you get stuck, you can post it as an MCVE in a new question. Good luck.
Edit
If all you're trying to do is mask an image, then you can simply use the PImage::mask() function. More info can be found in the reference, but it should be as simple as calling img.mask(masque) in your code:
img = loadImage("berlin-1.jpg");
masque = loadImage("mask.png");
img.mask(masque);

Then you should be able to use img as a texture, and the mask will have already been applied.
However, your .png file doesn't seem to work as a mask! If I use the mask.jpg file from the image masking example (in your Processing editor, go to File > Examples > Image > Alphamask, then go to Sketch > Show Sketch Folder, then find mask.jpg in the data directory) or if I save your .png file as a .jpg file it works okay.
If I save the example mask.jpg file as a .png file, it works okay. So something is wrong with your file particularly.


text:
Q: How to add subitems to ExpansionPanelList - ListView.Builder? import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatefulWidget(),
      ),
    );
  }
}

class Item {
  Item({
    this.expandedValue,
    this.headerValue,
    this.isExpanded = false,
  });

  String expandedValue;
  String headerValue;
  bool isExpanded;
  List<Item> _subItems;

  List<Item> get getSubItems => _subItems;
  set subItems(List<Item> subItems) {
    _subItems = subItems;
  }
}

List<Item> generateItems(int numberOfItems) {
  return List.generate(numberOfItems, (int index) {
    return Item(
      headerValue: 'Panel $index',
      expandedValue: 'This is item number $index',
    );
  });
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<Item> _data = generateItems(8);

  @override
  void initState() {
    _data.forEach((element) {
      element.subItems = generateItems(3);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        child: _buildPanel(),
      ),
    );
  }

  Widget _buildPanel() {
    return ExpansionPanelList(
      expansionCallback: (int index, bool isExpanded) {
        setState(() {
          _data[index].isExpanded = !isExpanded;
        });
      },
      children: _data.map<ExpansionPanel>((Item item) {
        return ExpansionPanel(
          headerBuilder: (BuildContext context, bool isExpanded) {
            return ListTile(
              title: Text(item.headerValue),
            );
          },
          body: Container(
            child: ListView.builder(
              itemCount: item._subItems.length,
              itemBuilder: (context, position) {
                return Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text(
                      position.toString(),
                      style: TextStyle(fontSize: 22.0),
                    ),
                  ),
                );
              },
            ),
          ),
          isExpanded: item.isExpanded,
        );
      }).toList(),
    );
  }
}

A: I think, ExpansionTile is what you need
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatefulWidget(),
      ),
    );
  }
}

class Item {
  Item({
    this.headerValue,
    this.expandedValue,
  });

  String headerValue;
  String expandedValue;
  List<Item> subItems;
}

List<Item> generateItems(int numberOfItems) {
  return List.generate(numberOfItems, (int index) {
    return Item(
      headerValue: 'Panel $index',
      expandedValue: 'This is item number $index',
    );
  });
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<Item> _data = generateItems(8);

  @override
  void initState() {
    _data.forEach((element) {
      element.subItems = generateItems(3);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: _data.length,
      separatorBuilder: (context, index){
        return const Divider(height: 1.0);
      },
      itemBuilder: (context, index){
        final item = _data[index];
        return ExpansionTile(
          title: Text(item.headerValue),
          subtitle: Text(item.expandedValue),
          children: item.subItems.map((subItem){
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  subItem.expandedValue,
                  style: TextStyle(fontSize: 22.0),
                ),
              ),
            );
          }).toList(),
        );
      },
    );
  }
}


text:
Q: compare two images using Selenium Ruby Webdriver Please help give me a solution to compare if two images in two URLs of an Web application are identical (I mean that content in each image are identical) or not by using Selenium Ruby Webdriver.
ex: I have a small image displayed when accessing the URL below:
 http://testing.com/image1.png

I also have another image when accessing the URL below:
 http://testing.com/image2.png

How can I compare these two images to see if they are identical using Selenium Ruby Webdriver ? Any suggestion is appreciated. Thanks much.

A: rmagick can be used to compare two images for identical pixels, using the compare_channel method:
img1 =  Magick::Image.read('image1.png')
img2 =  Magick::Image.read('image2.png')

diff_img, diff_metric  = img1[0].compare_channel( img2[0], Magick::MeanSquaredErrorMetric )

# diff_img is a cool feature - an image showing which pixels are different

# diff_metric == 0.0 for "no difference"

See http://studio.imagemagick.org/RMagick/doc/image1.html#compare_channel for more details.


text: Q: How to read wav file as http response from android volley I am writing android app that sends text to third party app and returns response as a wav audio data using android volley library. Has anybody done this ? I am unable to figure out how do I read the wav response and play the same in android media player


text:
Q: counting -99.9 in r I am new in using R and I have a question for which I am trying to find the answer. I have  a file organized as follows (it has thousands of rows but I just show a sample for simplicity):
YEAR   Month  day    S1      T1     T2         R1
1965    3       2    11.7    20.6    11.1    18.8
1965    3       3    14.0    16.7     3.3     0.0
1965    3       4   -99.9   -99.9   -99.9   -99.9
1965    3       5     9.2     5.6     0.0   -99.9
1965    3       6    10.1     6.7     0.0   -99.9
1965    3       7     9.7     7.2     1.1     0.0

I would like to know for each column (T1, T2, and R1) in which Year, Month and Day the -99.9 are located; e.g. from 1980/1/3 to 1980/1/27 there are X -99.9 for T1, from 1990/2/10 to 1990/3/30 there are Y-99.9 for T1....and so on. Same for T2, and R.
How can do this in R?
This is only one file like this but I have almost 2000 files with the same problem (I know I need to loop it) but if I know how to do it for one file then I will just create a loop.
I really appreciate any help. Thank you very much in advance for reading and helping!!!

A: I took the liberty of renaming your last  dataframe column "R1"
 lapply(c('T1', 'T2', 'R1'), function(x) { dfrm[ dfrm[[x]]==-99.9 , # rows to select
                                               1:3 ] }# columns to return
        )
#-------------
[[1]]
  YEAR Month day
3 1965     3   4

[[2]]
  YEAR Month day
3 1965     3   4

[[3]]
  YEAR Month day
3 1965     3   4
4 1965     3   5
5 1965     3   6

It wasn't clear whether you wanted the values or counts (and I don't think you can have both in the same report.) If you wanted to name the entries:
> misdates <- .Last.value
> names(misdates) <- c('T1', 'T2', 'R1')

If you wanted a count:
 lapply(misdates, NROW)
$T1
[1] 1

$T2
[1] 1

$R1
[1] 3

(You might want to learn how to use NA values. Using numbers as missing values is not recommended data management.)

A: If I understand correctly, you want to obtain how many "-99.9"s you get per month AND by column,
Here's my code for S1 using plyr. You'll note that I expanded your example to get one more month of data.
library(plyr)

my.table <-read.table(text="YEAR Month day S1 T1 T2 R1
1965 3 2 11.7 20.6 11.1 18.8
1965 3 3 14.0 16.7 3.3 0.0
1965 3 4 -99.9 -99.9 -99.9 -99.9
1965 3 5 9.2 5.6 0.0 -99.9
1965 3 6 10.1 6.7 0.0 -99.9
1965 3 7 9.7 7.2 1.1 0.0
1966 1 7 -99.9 7.2 1.1 0.0
1966 1 8 -99.9 7.2 1.1 0.0
", header=TRUE, as.is=TRUE,sep = " ")

#Create a year/month column to summarise per month
my.table$yearmonth <-paste(my.table$YEAR,"/",my.table$Month,sep="")

S1 <-count(my.table[my.table$S1==-99.9,],"yearmonth")
S1
  yearmonth freq
1    1965/3    1
2    1966/1    2


text:
Q: CodeMirror and Socket.io- Emitting the Contents of the Editor with onChange I'm trying to submit the contents of the editor to my server onChange.
I'm using node.js, socket.io, jquery, and codemirror.
This is my code thus far (client-side) ("code.server" means that I'm sending the code-textarea contents to my server.  I use "code.client" to send information back to the client):
<textarea id="code"></textarea>
<script>
var socket = io.connect();

var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
                lineNumbers: true,
            matchBrackets: true,
            onChange: function(){
            var value = getValue();
            socket.emit("code.server", value);
            }
});
</script>

Yet it isn't working.  What am I doing wrong?  I could submit the contents of the textarea before I added CodeMirror:
<script>
$("#code").keyup(function () {
        var value = $(this).val();
        socket.emit("code.server", value);
}).keyup();
</script>

I used jQuery, in case that wasn't clear.
And now, after adding codemirror, I can't get the contents and send them to the server.  What is going on?  Thank you for helping me, I've been working on this problem for several days, it's driving me crazy.

A: From the code above the getValue method is undefined, I think you want either this.getValue or editor.getValue.


text:
Q: Calculating the summation of powers of a number modulo a number There are 3 numbers: T, N, M. 1 ≤ T, M ≤ 10^9, 1 ≤ N ≤ 10^18 .
What is asked in the problem is to compute [Σ(T^i)]mod(m) where i varies from 0 to n. Obviously, O(N) or O(M) solutions wouldn't work because of 1 second time limit. How should I proceed?

A: As pointed out in previous answers, you may use the formula for geometric progression sum. However there is a small problem - if m is not prime, computing (T^n - 1) / (T - 1) can not be done directly - the division will not be a well-defined operations. In fact there is a solution that can handle even non prime modules and will have a complexity O(log(n) * log(n)). The approach is similar to binary exponentiation. Here is my code written in c++ for this(note that my solution uses binary exponentiation internally):
typedef long long ll;
ll binary_exponent(ll x, ll y, ll mod) {
  ll res = 1;
  ll p = x;
  while (y) {
    if (y % 2) {
      res = (res * p) % mod;
    }
    p = (p * p) % mod;
    y /= 2;
  }
  return res;
}

ll gp_sum(ll a, int n, ll mod) {
  ll A = 1;
  int num = 0;
  ll res = 0;
  ll degree = 1;
  while (n) {
    if (n & (1 << num)) {
      n &= (~(1 << num));
      res = (res + (A * binary_exponent(a, n, mod)) % mod) % mod;
    }
    A = (A + (A * binary_exponent(a, degree, mod)) % mod) % mod;
    degree *= 2;
    num++;
  }
  return res;
}

In this solution A stores consecutively the values 1, 1 + a, 1 + a + a^2 + a^3, ...1 + a + a^2 + ... a ^ (2^n - 1).
Also just like in binary exponentiation if I want to compute the sum of n degrees of a, I split n to sum of powers of two(essentially using the binary representation of n). Now having the above sequence of values for A, I choose the appropriate lengths(the ones that correspond to 1 bits of the binary representation of n) and multiply the sum by some value of a accumulating the result in res. Computing the values of A will take O(log(n)) time and for each value I may have to compute a degree of a which will result in another O(log(n)) - thus overall we have O(log(n) * log (n)).
Let's take an example - we want to compute 1 + a + a^2 .... + a ^ 10. In this case, we call gp_sum(a, 11, mod).
On the first iteration n & (1 << 0) is not zero as the first bit of 11(1011(2)) is 1. Thus I turn off this bit setting n to 10 and I accumulate in res: 0 + 1 * (a ^ (10)) = a^10. A is now a + 1.
The next second bit is also set in 10(1010(2)), so now n becomes 8 and res is a^10 + (a + 1)*(a^8)=a^10 + a^9 + a^8. A is now 1 + a + a^2 + a^3
Next bit is 0, thus res stays the same, but A will become 1 + a + a^2 + ... a^7.
On the last iteration the bit is 1 so we have:
res = a^10 + a^9 + a^8 + a^0 *(1 + a + a^2 + ... +a^7) = 1 + a .... + a ^10.

A: One can use an algorithm which is similar to binary exponentiation:
// Returns a pair <t^n mod m, sum of t^0..t^n mod m>,
// I assume that int is big enough to hold all values without overflowing.
pair<int, int> calc(int t, int n, int m)
    if n == 0 // Base case. t^0 is always 1.
        return (1 % m, 1 % m)
    if n % 2 == 1
        // We just compute the result for n - 1 and then add t^n.
        (prevPow, prevSum) = calc(t, n - 1, m)
        curPow = prevPow * t % m
        curSum = (prevSum + curPow) % m
        return (curPow, curSum)
    // If n is even, we compute the sum for the first half.
    (halfPow, halfSum) = calc(t, n / 2, m)
    curPow = halfPow * halfPow % m // t^n = (t^(n/2))^2
    curSum = (halfSum * halfPow + halfSum) % m
    return (curPow, curSum)

The time complexity is O(log n)(the analysis is the same as for the binary exponentiation algorithm). Why is it better than a closed form formula for geometric progression? The latter involves division by (t - 1). But it is not guaranteed that there is an inverse of t - 1 mod m.

A: It's a geometric series whose sum is equal to :

A: you can use this:
a^1 + a^2 + ... + a^n = a(1-a^n) / (1-a)

so, you just need to calc:
a  * (1 - a^n) / (1 - a) mod M

and you can find O(logN) way to calc a^n mod M


text:
Q: Flex SWFLoader Event.COMPLETE not triggering While trying to load a Bitmap onto a SWFLoader the Event.COMPLETE event is not being triggered
mySWFLoader.source = new Bitmap(Bitmap(someEvent.content).bitmapData);

but if I use a URL as source the complete event is triggered:
mySWFLoader.source = "http://example.com/123.jpg";

Is there some kind of restriction while using Bitmap as source?

A: I believe if you use data that already exists in memory (which your Bitmap would) then no load operation would happen.  It should be usable immediately after construction.  I know attaching movies in AS2 worked like that.  If it was part of the library you could use it right away and no loading events would happen.

A: Use
mySWFLoader.addEventListener(Event.ADDED,handleSwfLoadComplete);

It fires when the content is actually created and added to the display list.
I encountered the same issue. The problem is that when you use Bitmap or Class as source, the content is populated only after the Bitmap or class was instantiated.
This happens in swfLoader.loadContent which eventually adds the newly created content to the displayList as the loader's child, and eventually dispatches the ADDED event.


text:
Q: Clustering Lists of Words (Python) I have 54 lists consisting of words of varying lengths. For example:
1 = ["fly", "robot", "ketchup"].
2 = ["rain", "fly", "top", "jacket"].
....
I would like to cluster similar lists into groups based on the words in each list. The order of the words in the list does matter slightly but isn't the only criteria for a match. Any ideas? I was thinking of using BERT and then K-means clustering.
I want the lists to remain intact, just grouped/clustered.

A: I think BERT + K-Means is a good approach. Since the order of the words matter I would just treat each list as a sentence and instead of using just BERT I would use SentenceBERT which is usually better for clustering tasks.
Here you have a good tutorial from the original SentenceBERT documentation.


text:
Q: Can't save and load a trained CNN model for binary image classification I have built a Binary Image classifier using Convolutional Neural Networks using TensorFlow.It is running fine, however, each time it takes too long to train from scratch. So, I want to save the trained model and load it next time. I can't seem to understand how to implement these guides in my program as shown in the TensorFlow documentation.
Here's the full code:
# Python program to create
# Image Classifier using CNN

# Importing the required libraries
import cv2
import os
import numpy as np
from random import shuffle
from tqdm import tqdm
from keras.models import Sequential
'''Setting up the env'''

TRAIN_DIR = 'D:\\Project\\Final_Project\\chest_xray\\train\\'
TEST_DIR = 'D:\\Project\\Final_Project\\chest_xray\\test0\\'
check_point = 'D:\\Project\\Final_Project\\chest_xray\\chkpt\\'
IMG_SIZE = 80
LR = 1e-4

'''Setting up the model which will help with tensorflow models'''
MODEL_NAME = 'NormalVsAbnormalXRays-{}-{}.model'.format(LR, '6conv-basic')

'''Labelling the dataset'''

def label_img(img):
    word_label = img.split('.')[-3]
    # DIY One hot encoder
    if word_label == 'Nor':
        return [1, 0]
    elif word_label == 'Pne':
        return [0, 1]
    else :
        return[0, 0]

'''Creating the training data'''

def create_train_data():
    # Creating an empty list where we should the store the training data
    # after a little preprocessing of the data
    training_data = []

    # tqdm is only used for interactive loading
    # loading the training data
    for img in tqdm(os.listdir(TRAIN_DIR)):
        # labeling the images
        label = label_img(img)

        path = os.path.join(TRAIN_DIR, img)

        # loading the image from the path and then converting them into
        # greyscale for easier covnet prob
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

        # resizing the image for processing them in the covnet
        img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))

        # final step-forming the training data list with numpy array of the images
        training_data.append([np.array(img), np.array(label)])

        # shuffling of the training data to preserve the random state of our data
    shuffle(training_data)

    # saving our trained data for further uses if required
    np.save('train_data.npy', training_data)
    return training_data

'''Processing the given test data'''

# Almost same as processing the traning data but
# we dont have to label it.
def process_test_data():
    testing_data = []
    for img in tqdm(os.listdir(TEST_DIR)):
        path = os.path.join(TEST_DIR, img)
        img_num = img.split('.')[0]
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
        testing_data.append([np.array(img), img_num])

    shuffle(testing_data)
    np.save('test_data.npy', testing_data)
    return testing_data

'''Running the training and the testing in the dataset for our model'''
#train_data = create_train_data()
#test_data = process_test_data()

train_data = np.load('train_data.npy')
test_data = np.load('test_data.npy')
'''Creating the neural network using tensorflow'''
# Importing the required libraries
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression

import tensorflow as tf
model = Sequential()
tf.reset_default_graph()

saver = tf.train.import_meta_graph('D:\\Project\\Final_Project\\chest_xray\\check_point-78.meta')
convnet = input_data(shape=[None,IMG_SIZE, IMG_SIZE, 1], name='input')

convnet = conv_2d(convnet, 32, 4, activation='relu')
convnet = max_pool_2d(convnet, 2)

convnet = conv_2d(convnet, 64, 4, activation='relu')
convnet = max_pool_2d(convnet, 2)

convnet = conv_2d(convnet, 128, 4, activation='relu')
convnet = max_pool_2d(convnet, 2)

convnet = conv_2d(convnet, 64, 4, activation='relu')
convnet = max_pool_2d(convnet, 2)

convnet = conv_2d(convnet, 32, 4, activation='relu')
convnet = max_pool_2d(convnet, 2)

convnet = fully_connected(convnet, 1024, activation='relu')
convnet = dropout(convnet, 0.3)

convnet = fully_connected(convnet, 2, activation='softmax')
convnet = regression(convnet, optimizer='adam', learning_rate=LR,
                     loss='categorical_crossentropy', name='targets')

model = tflearn.DNN(convnet, tensorboard_dir='log', checkpoint_path='check_point',best_checkpoint_path= 'check_point',max_checkpoints= 5)

# Splitting the testing data and training data
train = train_data
test = train_data

'''Setting up the features and lables'''
# X-Features & Y-Labels

X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
Y = [i[1] for i in train]
test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
test_y = [i[1] for i in test]

'''Fitting the data into our model'''
# epoch = 40 taken
model.fit({'input': X}, {'targets': Y}, n_epoch=1,
          validation_set=0.05,
          snapshot_step=500, show_metric=True, run_id=MODEL_NAME)
model.save(MODEL_NAME)

'''Testing the data'''
import matplotlib.pyplot as plt

# if you need to create the data:
# test_data = process_test_data()
# if you already have some saved:
test_data = np.load('test_data.npy')

fig = plt.figure(figsize=(80,80))

for num, data in enumerate(test_data[:1]):

    img_num = data[1]
    img_data = data[0]

    y = fig.add_subplot(1, 1, num + 1)
    orig = img_data
    data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1)

    # model_out = model.predict([data])[0]
    model_out = model.predict([data])[0]

    if np.argmax(model_out) == 1:
        str_label = 'Abnormal'
    else:
        str_label = 'Normal'

    y.imshow(orig, cmap='gray')
    plt.title(str_label,fontsize=20)
    y.axes.get_xaxis().set_visible(False)
    y.axes.get_yaxis().set_visible(False)
 plt.show()

I have tried to use saver = tf.train.import_meta_graph('D:\\Project\\Final_Project\\chest_xray\\check_point-78.meta') to import the graph but I get this error
Traceback (most recent call last):
  File "D:/Project/Final_Project/chest_xray/Final_CNN.py", line 104, in <module>
    saver = tf.train.import_meta_graph('D:\\Project\\Final_Project\\chest_xray\\check_point-78.meta')
  File "C:\Users\waqar\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1674, in import_meta_graph
    meta_graph_or_file, clear_devices, import_scope, **kwargs)[0]
  File "C:\Users\waqar\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1696, in _import_meta_graph_with_return_elements
    **kwargs))
  File "C:\Users\waqar\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\meta_graph.py", line 852, in import_scoped_meta_graph_with_return_elements
    ops.prepend_name_scope(value, scope_to_prepend_to_names))
  File "C:\Users\waqar\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3490, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "C:\Users\waqar\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3550, in _as_graph_element_locked
    "graph." % repr(name))
KeyError: "The name 'Adam' refers to an Operation not in the graph."

Process finished with exit code 1


text:
Q: How to change MediaType for MappingJacksonHttpMessageConverter in OAuth2RestTemplate I have an application that is using Spring Source OAuth2 as s client to retrieve user data from a resource server and create a local user. I keep getting the error when the OAuth2ClientContextFilter tries to retrieve the token:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [org.springframework.security.oauth2.common.OAuth2AccessToken] and content type [application/x-javascript;charset=utf-8]

I understand the default MediaType is 'application/json' so I tried to customize the MappingJacksonHttpMessageConverter like this:
<bean id="jacksonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <bean class="org.springframework.http.MediaType">
                    <constructor-arg value="application"/>
                    <constructor-arg value="x-javascript"/>
                    <constructor-arg value="UTF-8"/>
                </bean>
            </list>
     </property>
</bean>

I also tried the 'ALL' constructor arg that is supposed to support */* content types but no luck. See http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/MediaType.html
Other important info is that I am using an all XML configuration right now. I just upgraded our 2.5 app to 3.1.1. I'm using OAuth2RestTemplate in a spring security PRE_AUTH filter, not in a controller. So I'm not using annotations to map the rest calls. I've tried adding <context:annotation-config/> but that didn't make a difference.
I'm simply calling my OAuth service bean from my custom AbstractPreAuthenticatedProcessingFilter. When the service bean tries to execute the rest call for user data, an exception is thrown, triggering the OAuth2ClientContextFilter which attempts to retrieve the token. Here's my OAuth2 service bean config:
<bean id="reprintsOauthService" class="com.coral.user.ReprintsOauthService">
    <property name="reprintsUserInfoUrl" value="https://www.demo.com/api/userinfo.ashx" />
    <property name="reprintsRestTemplate">
        <bean class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
            <constructor-arg ref="reprintsResource"/>
            <property name="messageConverters">
                <list>
                   <ref bean="jacksonConverter"/>
                </list>
            </property>
        </bean>
    </property>
</bean>

Am I missing something? Why doesn't Jackson map the response?

A: Fixed! The problem was that the OAuth2RestTemplate isn't used for token retrieval. So I had to customize the org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport and add the MappingJacksonHttpMessageConverter to the existing method like this:
  public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    this.messageConverters = new ArrayList<HttpMessageConverter<?>>(messageConverters);
    this.messageConverters.add(new FormOAuth2AccessTokenMessageConverter());
    this.messageConverters.add(new FormOAuth2ExceptionHttpMessageConverter());

    MappingJacksonHttpMessageConverter jackson = new MappingJacksonHttpMessageConverter();
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(new MediaType("application", "x-javascript"));
    jackson.setSupportedMediaTypes(mediaTypes);
    this.messageConverters.add(jackson);

    if(logger.isDebugEnabled())
    {
        logger.debug("*** Added custom media type 'application/x-javascript' to the Jackson converter");
    }
}

A: I came to this question by searching for "oauth RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type"
your answer was the hint I needed to solve the problem! I added the following Maven dependencies (which are optional in the oauth2 pom):
<!-- spring oauth2 json dependency: -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.3.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.2</version>
</dependency>

When creating the AuthorizationCodeAccessTokenProvider i added the jackson message converter:
protected AuthorizationCodeAccessTokenProvider getAccessTokenProvider() {
    final AuthorizationCodeAccessTokenProvider oAuthProvider = new AuthorizationCodeAccessTokenProvider();
    final List<HttpMessageConverter<?>> messageConv = new ArrayList<HttpMessageConverter<?>>();
    messageConv.add(new MappingJackson2HttpMessageConverter());
    oAuthProvider.setMessageConverters(messageConv);
    return oAuthProvider;
}


text:
Q: AIrflow - task_instance.try_number is not working I am trying to send parameter to an airflow task in order to identify the last execution.
The following code always send {"try_number": "1"} as POST data.
Airflow version: 1.10.2
Thanks
    xxx = SimpleHttpOperator(
        task_id='XXX',
        endpoint='/backend/XXX',
        http_conn_id='backend_url',
        data=json.dumps({"try_number": "{{ti.try_number}}"}),
        headers={"Content-Type": "application/json"},
        response_check=lambda response: response.json().get('status') == 'ok',
        dag=dag,
    )

A: The problem is with the rendered view,
I looked at the rendered result's instead of viewing the actual value of the operator.
I pushed the output to new XCOM (xcom_push=True) and now I can see the right value:
{ "status": "ok", "try_number": "15" }


text:
Q: Single Page application and the back button[AJAX] I have a website that has been entirely designed to operate without generating any browser history other then the main page. This was mostly for security so the browser state and the server never are out of sync.
I want to know if there is a way to intercept the browser "back" button when they are anywhere except on the main page of our site to operate an internal "back" button.

A: You can use Push State Navigation to handle browser's back button. Take a look at this link https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


text:
Q: Objects do not inherit bucket permissions In GCS storage, when adding permissions to a bucket (NOT the whole project; just a single bucket inside that project), you used to be able to set up the permissions of a bucket so that any NEW objects put in the bucket inherit the bucket's permissions.
In the newest version of the GCS however, we have not been able to figure out how to do this. We can set permissions to a root bucket:
{
    "email": "someuser@someaccount.iam.gserviceaccount.com",
    "entity": "someuser@someaccount.iam.gserviceaccount.com",
    "role": "READER"
  }

But then when a new object is placed in that bucket, it does not inherit this role.
Is there a way to either (a) inherit the role, or (b) set an IAM role to the bucket (we have only been able to set an IAM role to the project, not a specific bucket)?
Thanks!

A: There are five different ways to configure Access Control options for Cloud Storage buckets. I suggest you the Access Control Lists (ACLs) to inherit the role in a single bucket since ACLs are used when "you need fine-grained control over individual objects".
To change the permissions on a single bucket inside a project using the Console,

*

*Go to Storage, browser. Once there you will see a bucket list.

*Select the bucket in which you want to change the permissions.

*Click on the three vertical dots at the right side and select "Edit bucket permissions".

*Type the account that you want to configure and select the desired role.

The described procedure is detailed here, as well as other ways to set the ACLs, as for example using the Cloud Shell. The next command specify individual grants:
gsutil acl ch -u [USER_EMAIL]:[PERMISSION] gs://[BUCKET_NAME]

Find a list of predefined roles here.
Update 2
Considering the next error:

CommandException:
  user@account.iam.gserviceaccount.com:roles/storage.legacyBucketReader
  is not a valid ACL change Allowed permissions are OWNER, WRITER,
  READER

And the fact that there are two types of roles involved:

*

*Identity and Access Management (IAM) roles: members project oriented roles. "Defines who (identity) has what access (role) for which resource". Example: gsutil iam ch user:[USER_EMAIL]:objectCreator,objectViewer gs://[BUCKET_NAME]

*Access Control Lists (ACLs): grant read or write access to users for individual buckets or objects. Example: gsutil acl ch -u [USER_EMAIL]:READER gs://[BUCKET_NAME]
The command is not working because both commands are mixed. For gsutil acl, the only possible permissions are READER, WRITER, OWNER, Default, as you can see here.


text:
Q: Making websites hosted on localhost available to all on network I have a website hosted in IIS on my local PC
If I go to http://localhost or http://192.168.1.1 my site comes up.
But what must I do to let other users on our network to see my site?
I am using Windows 7.......

A: You can either allow them to connect to your machine using the http://192.168.1.1 address or you can create a name that maps to 192.168.1.1. How you create the name depends on what infrastructure you have. If you have a local DNS server then add the name pointing to 192.168.1.1 into that. Failing that you could add the name to the hosts file on you machines.

A: Check that Windows Firewall allows external connections from local IP addresses on your network to port 80.  Opening ports on this page explains how to do that.


text:
Q: Utilizar pgAdmin 4 con atajos de teclado Cordial saludo.
A sido muy interesante y practico para mi, utilizar diferentes aplicaciones por medio de atajos de teclado, es por ello que al comenzar a trabajar con pgAdmin 4, comencé a buscar algunos atajos que me permitan ejecutar acciones de forma rápida pero aun no he podido encontrar los de mi interés.
Agradezco su ayuda con los atajos de teclado que me permitan realizar las siguientes acciones:

*

*abrir un Query Tool

*cerrar un Query Tool

*moverme entre varias ventas Query Tool

*moverme de Query Tool a Browser y viceversa

*abrir las opciones de una tabla (las opciones que aparecen al dar clic derecho sobre la tabla)

*moverme de la zona de trabajo Query a la zona Data output


text:
Q: Best way to confine given string to white list I have a urlconf setup to catch /account/invoices/*/, and with it I want to catch a few optional qualifiers. In this case: unpaid, paid, disregarded. I'm not outputting this so I think accepting input in this fashion should be fine, but still I need to white list and translate these options into what the API expects. Is there a better way to do this (where the variable 'paid' comes in as a view argument)?
filter['unpaid'] = 0
filter['paid'] = 1
filter['disregarded'] = 2

if paid is in filter:
    paid = filter[paid]

A: Simple solution:
if paid in ['unpaid', 'paid', 'disregarded']

Your solution and DataGreed's are more verbose and require you to make up values for your dict/object elements.

A: Yes, your solution is good. But i just like dict.get a little more:
enum = {
        'unpaid'      : 0,
        'paid'        : 1,
        'disregarded' : 2,
        }

def view(request, option):

    value = enum.get(option, None)


text:
Q: Nested Datagrid working Hi Iam using a nested datagrid and following is its definition,
Here is the screenshot of the output,

In above image , I have 2 datagrids. If I click on any row of outergrid , Corresponding innergrid is displayed. Now, Iam not getting how this event is handled and corresponding inner grid data is displayed.
This is the class structure to which Iam binding my datagrid,
class MyClass
    {
        public string Col1{ get; set; }
        public string Col2{ get; set; }
        public string Col3{ get; set; }
        public string Col4{ get; set; }
        public string Col5{ get; set; }
        public ObservableCollection<InnerObject> inner_object{ get; set; }
    }

class InnerObject
{
    public string EventName { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public string Message { get; set; }
    public int RIndex { get; set; }
}
<DataGrid
        x:Name="objDatagrid"
        ItemsSource="{Binding DataView}"
        CanUserAddRows="False"
        CanUserDeleteRows="False"
        AutoGenerateColumns="False"
        BorderBrush="Gray"
            >
            <DataGrid.RowStyle>
                <Style TargetType="{x:Type DataGridRow}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding TDate}" Value="">
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.RowDetailsTemplate >
                <DataTemplate>

                        <DataGrid
            x:Name="objInnerDatagrid"
            IsReadOnly="True"
            ItemsSource="{Binding ElementName=objDatagrid, Path=SelectedItem.inner_object}">
                            <DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Date}" Value="">
                                            <Setter Property="Visibility" Value="Collapsed"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </DataGrid.RowStyle>
                            <DataGrid.Columns>
                            </DataGrid.Columns>
                        </DataGrid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Col1" Width="SizeToHeader" Binding="{Binding Col1}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Col2" Width="80" Binding="{Binding Col2}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Col3" Width="80" Binding="{Binding Col3}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Col4" Width="120" Binding="{Binding Col4}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Col5" Width="100" Binding="{Binding Col5}" IsReadOnly="True"/>
            </DataGrid.Columns>
        </DataGrid>

Iam a newbie to WPF. Can anyone please explain me the above code and its working ?
It will be a great help.
Thanks in advance.

A: DataGrid.RowDetailsVisibilityMode defines when details row is shown and DataGrid.RowDetailsTemplate defines what is shown.

By default, the row details section is displayed for selected rows if a RowDetailsTemplate is defined

It works because you bind inner DataGrid.ItemsSource to inner_object of SelectedItem - in your case MyClass - of objDatagrid control
ItemsSource="{Binding ElementName=objDatagrid, Path=SelectedItem.inner_object}">

There is however potential problem with that. It will always bind to first selected item and not the one that you have currently open. For example when DataGrid.RowDetailsVisibilityMode = Visible all details will point to same item selection. Since each row's DataContext, that includes row details, will be already set to an instance of MyClass all you have to do is:
ItemsSource="{Binding Path=inner_object}">

on the inner DataGrid

A: As you can already see in your code the RowDetailsTemplate displays the inner grid. Default behavior of displaying the row details is when someone selects the parent row.
If you want this behavior to override (e.g. you want to show the details Data grid on double click or something) then you may have to do some code behind work ...
See this post for more details...
Show RowDetails on double-click in WPF DataGrid


text:
Q: Looking for a feature that enables me to drag a particular Navigation Menu anywhere on the screen I am looking for a feature that allow me to mouse click on a Navigation Menu and drag it. Suppose, if I have navigation menus such as HOME, ABOUT US, PROFILE, SERVICES & CONTACT US and among these menus if I click on HOME nav menu (without releasing the clicked mouse) and be able to drag it around the page upto a limited height of the page. When I say limited height, say upto the height of a particular banner with the height of 680px.
I tried to search on the net but was unable to find anything related to this funtionality or feature and do not know if such a thing can be created.
I would really appreciate if anyone can help me with any such feature and if yes then how can I achieve this.
Thanks in Advance.  CJ

A: There is no plugin that I know of, or something already done, because this appears to be a simple drag and drop problem. I would recommend reading the guides here and implementing your own drag and drop for this problem.