text:
Q: Creating a packed Binary Representation of a Set of Files? So i am trying to work on my own little 3d game. Now i am more or less doing this to learn C#. I was wondering, what is the best methodology for packaging assets such as textures/scripts?
Generally what i was thinking of doing was this:
[header]
[number of records]
[Offset to Record 1 from End of header]
[Offset to Record 2 from end of Record 1]
.
.
[Offset to record N from Record N-1]
[record 1]
[256 bytes represent the filename]
[32 byte size]
[binary data]
[record 2]
.
.

Right now i just want it to store, simple pictures and text files. I've done some looking around and the best thing i really found was an old example of how doom wad's are stored.
Does anyone have any experience?

A: That's fine.  If you can load everything into virtual memory and let swapping handle it, then you can use any format, really.  If you want random access to just one record (so e.g. you can load lazily, although uncompressed memmap is also lazy), then you probably want to keep the index in memory.
Most people use a library that gives them access to a .zip, .jar, .pak (quake format), or other similar (compressed or not) archive format, as if it were part of the filesystem (that is, records are accessed by string keys).  I'd definitely go that way if you can find an already-made library, e.g. truezip for Java.  Apache Commons has one, but I don't know how easy it is to integrate w/ .NET (it's a big C code base I believe).  ZipFS looks like it's an actual .NET zip file mounter that only holds the headers in memory.
Or, with probably only a little less convenience, you could use DotNetZip directly

A: Do not waste your time inventing your own storage format.
You can use SharpZipLib or another free compression library for .net.
With it you can also pack multiple files into one archive and extract the files you want separately on demand.

A: Your design looks good to me, though I assume that you meant 32 bits for size rather than 32 bytes!
I think that your design would be best for situations where you want to load up all your assets in one go, because it's kind of a sequential design.  If you want to load up just a few assets at a time (maybe because each game level uses only a subset of the assets) then it would be somewhat less efficient, because you would have to read through each asset in turn to find the ones that you want.
In that case you might want to try a more indexed design, maybe something like this:
[HEADER]
[Miscellaneous header stuff]
[Offset to index from start of file]
[Number of entries in index]
[RECORD 1]
[Asset data]
[RECORD 2]
[Asset data]
.
.
[RECORD N]
[Asset data]
[INDEX]
[ID or filename of asset 1]
[Size of asset 1]
[Offset to asset 1 from start of file]
[Other asset 1 flags or whatever]
[ID or filename of asset 2]
[Size of asset 2]
[Offset to asset 2 from start of file]
[Other asset 2 flags or whatever]
.
.

This would allow for better random access of assets, because now you just have to search through your index (which you would load into memory) rather than through your whole file (which might not fit into memory).  If you wanted to get fancy you could use a tree or hashtable for the index.
The reason for putting the index at the end of the file rather than the front is that it makes it easier to add another asset to your pack file without having to rebuild the whole thing.  Otherwise, the extra entry in your index would throw out all your offsets.

EDIT: to respond to comments...
What I had in mind was that you would only access the assets via the index, so hopefully you would never run off the end of the assets when reading them.  Perhaps an example of a typical use case would help.
Say you wanted to read in the texture called "TankTexture.png".  Here is how I think that you would go about it:

*

*Open the pack file.

*Read in the fixed-size header.

*Extract the index offset and number of entries from the header.

*Seek to the start of the index.

*Read the index into an array (fixed index entry size times number of entries).

*Search through the index for the asset called "TankTexture.png".

*Extract the asset offset and size from the index entry.

*Seek to the start of the asset.

*Read in the number of bytes given by the asset size.

Of course, for subsequent assets you would need only steps 6-9.
I hope that helps to explain what I was thinking.  Let me know if you have any other questions.

A: If you want to do this for learning purposes then the WAD format is a good place to start. However, I'd propose using a chunked file format.
So it would basically follow your proposed format ( i.e header, TOC etc ) but for each data entry you'd have a chunk ID which identifies what type of data it is.
This has lots of benefits, mainly that you can vary your data format against your code format by setting your code to skip chunks that it doesn't understand - this allows your tools development to proceed whilst keeping backwards compatibility on your data in your game.
I'd also recommend having an extra 32 bit 'flags' entry in your TOC which would allow you to use a bitfield to enable options like compression type, encryption etc
Hope that helps

A: I say your format is a good choice.  Ideally, you want to pull in all your assets in one read.  For instance you'd want all your data for level 3 in the same package, that way you can load all your level data in one read without seeking.  Its really ok to have a single asset in more than one package. You just need to handle the case that an asset is already loaded and skip over it.
How you split up your data should be dependent on the dependencies between your data (ie if a script needs a certain model, they should both be in the same package) and how granular you need to make your reads (ex.  can you read all your level data in one go?  Then you can put your enemies in the level package.  But if your game streams in the world, maybe you need separate packages for enemies.)
Really, tracking you data dependencies is the hard part.  At build time you want to know the dependencies of every piece of data you pull in.  At run time you just want to read in your package and have the assets show up in memory.  You also need to track dependencies at run time because you'll need to know whats safe to UNLOAD at any give time.


text:
Q: How do I set id prefixes used by Zend_View_Helper_Navigation_XXX When I render a Zend_Nagivation instance in my view, by default the anchor tags have id's assigned with the prefix of the view helper, followed by a dash, and then the page's id.
Examples of Page 1's anchor id (all using the same Zend_Nagivation instance):

*

*Zend_View_Helper_Navigation_Menu = "menu-1"

*Zend_View_Helper_Navigation_Breadcrumbs = "breadcrumbs-1"

*My_View_Helper_Navigation_MyMenu = "mymenu-1"

This is perfect for most cases, but I'd like to set that prefix manually, and I can't find a way to do it.

Solution
Specifying the prefix can be accomplished by adding the following code, and then calling setIdPrefix() when rendering:
class My_View_Helper_Navigation_MyMenu extends Zend_View_Helper_Navigation_Menu
{
    protected $_idPrefix = null;

    /**
     * Set the id prefix to use for _normalizeId()
     *
     * @param string $prefix
     * @return My_View_Helper_Navigation_MyMenu
     */
    public function setIdPrefix($prefix)
    {
        if (is_string($prefix)) {
            $this->_idPrefix = $prefix;
        }

        return $this;
    }

    /**
     * Use the id prefix specified or proxy to the parent
     *
     * @param string $value
     * @return string
     */
    protected function _normalizeId($value)
    {
        if (is_null($this->_idPrefix)) {
            return parent::_normalizeId($value);
        } else {
            return $this->_idPrefix . '-' . $value;
        }
    }
}

A: The culprit is Zend_View_Helper_Navigation_HelperAbstract::_normalizeId() for which I see no other solution than to create your own custom version of each navigation view helper you require.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unrecognized selector sent to instance IOS 10 I have a very difficult problem when I launched my app on IOS10.3.3.. Indeed, I got this error in my splashviewController :
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   // [[EMAnalyticsManager sharedInstance]sendScreenViewWithName:SplashScreen];
}

I got this crash message:
[__NSCFString nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:]: unrecognized selector sent to instance 0x165e3630
2018-09-06 16:57:31.456059+0100 **********[2461:1072580] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:]: unrecognized selector sent to instance 0x165e3630'

I made many research to understand the cause of this crash that didn't occur in IOS11.
Any help please??

A: Some constraints might be causing this when the very first view controller is loaded. Please check your constraint and you can also remove the constraints and then verify if it works.


text:
Q: Python Pandas Period Date difference is in * MonthEnds>, how to convert it into INT value I am trying to find Period date difference. Per Pandas 0.24+ : Subtraction of a Period from another Period will give a DateOffset. instead of an integer (GH21314). But how to get INT results. I have look into similar query: Why can't I subtract one date period from the next and convert to an integer?
It says adding ".n" will give results, but that didn't work for me.
I also tried converting both into INT using .astype(int), but getting error: 'Period' object has no attribute 'astype'. I must be missing something, not sure what!
I am using Pandas Version: '1.0.1'.
DDL to generate Dataframe:
import pandas as pd

date_start = pd.Period('10/2018',freq='M')

df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
                  'date_end': ['2017-01', '2018-08', '2019-04','2018-06',
                               '2018-12', '2018-10']})
df['date_end'] = pd.PeriodIndex(pd.to_datetime(df['date_end'], format='%Y-%m'),
                                freq='M')

df['diff'] = date_start - df['date_end']

Thanks!

A: You need to access the individual Period[M] objects, not the series:
df['diff'].n
AttributeError: 'Series' object has no attribute 'n'

df['diff'].apply(lambda x: x.n)

0    21
1     2
2    -6
3     4
4    -2
5     0


text:
Q: Is it possible to add a function to a loop in ruby? I am still pretty new to Ruby and coding in general and I have been struggling at this particular task for a while a now.
I just wanted to know how to add a function in Ruby within a loop. For example:
def main()
name=read_string("What is your name? ")
if name=="Tom"
    puts "an awesome name"
else
    def print_silly_name(name)
        i=0
        puts name + " is a #{i}"+"name!"
        while i<60
            loop do puts " silly"
                i=i+1
            end

The output should have the word "silly" printed 60 times but I am not sure how to call the loop.

A: You first define your method, e.g.:
def print_silly_name(name)
  print "#{name} is a"
  60.times { print " silly" }
  puts " name!"
end

And then you call your method:
def main
  name = read_string("What is your name?")

  if name == "Tom"
    puts "an awesome name"
  else
    print_silly_name(name)
  end
end

Example output:

What is your name?
Bob
Bob is a silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly name!

A: You must delare the method outside of main():
def print_silly_name(name)
  i=0
  while (i<60)
      puts name + " is a #{i}"+"name!"
      i+=1
  end
end

and than just call it in your .rb file:
print_silly_name('Josh')


text:
Q: NuxtJS/VueJS: How to know if page was rendered on client-side only? Currently I create a html5 video player component for an universal nuxtjs/vuejs app.
There is an autoplay attribute for the video tag to start videos after navigate to them.
Usually browsers don't do that directly after page load, it's prohibited.
I need a variable in my component to know if autoplay will be possible to style elements based on this information.
In other words: The variable should be true if the current page was only rendered on client-side, but false if it was rendered on server-side first.
It's not possible to work with "window.history.length" because the autoplay will also not be possible after refresh, although this would not have an effect on the history length.
Also it's not possible to set a variable in the "created" method since it will be called on server- and client-side too.

A: One possible solution would be to get the length of the Vue router entries. This seems currently not to be possible without manually tracking. So I ended with this code in my layout component:
watch: {
  $route () {
    Vue.prototype.$navigated = true
  }
}

The value of $navigated is undefined or true and so I know in the layout children components if video autoplay is possible or not.

A: In nuxt - there is the <client-only> component that renders components only on the client side
<template>
  <div>
    <sidebar />
    <client-only placeholder="Loading...">
      <!-- this component will only be rendered on client-side -->
      <comments />
    </client-only>
  </div>
</template>

In nuxt, there are is asyncData which is run beforeCreate(), i.e. you can retrieve data from the server side in asyncData before the component is mounted.

Alternatively, you can check on the created() for the process, e.g.
created() {
  if (process.client) {
    // handle client side
  }
}

edit
https://stackoverflow.com/a/53058870/2312051

Audio.play() returns a Promise which is resolved when playback has been successfully started. Failure to begin playback for any reason, such as permission issues, result in the promise being rejected.

const playedPromise = video.play();
if (playedPromise) {
  playedPromise.catch((e) => {
    if (e.name === 'NotAllowedError' ||
        e.name === 'NotSupportedError') {
        //console.log(e.name);
    }
  });
}

In your case, looks like your browser/os does not allow automatic playing of audio. The user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button. Here is the reference.


text:
Q: How do I get static expression ActionLinks etc in ASP.NET MVC 1? I've read loads of examples in which

<%= Html.ActionLink("Home", "Index", "Home")%>

is rewritten as

<%= Html.ActionLink<HomeController>(c => c.Index(), "Index")%>

However, with a fresh ASP MVC project, this doesn't compile. I've read its something to do with needing to add the ASP MVC Futures assembly. Is this correct and if so, where do I get it?

A: Yes, you need the ASP.NET MVC Futures assembly, it's available here for 1.0:
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471


text:
Q: How to format embedded if statements in javascript What would be the best way to format this code?
It looks a bit messy to me, in regard to indentation, etc.
    if (typeof _srwc != 'undefined') {
        for (var i=0; i < _srwc.length; i++){
             var currentArg = _srwc[i];;
              if (typeof window[currentArg[0]] == 'function') {
                 window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
                 } else {
                 console.log('The Setter method: "' + currentArg[0] + '" is undefined');
                 }
        }
    }

A: Try indenting the code inside the if, like this:
    if (typeof _srwc != 'undefined') {
        for (var i = 0; i < _srwc.length; i++) {
            var currentArg = _srwc[i];;
            if (typeof window[currentArg[0]] == 'function') {
                window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
            } else {
                console.log('The Setter method: "' + currentArg[0] + '" is undefined');
            }
        }
    }

Also, JSBeautifier is very useful for indenting JavaScript.

A: You can also use:
if (typeof _srwc != 'undefined')
{
    for (var i = 0; i < _srwc.length; i++)
    {
        var currentArg = _srwc[i];
        if (typeof window[currentArg[0]] == 'function')
        {
            window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
        }
        else
        {
            console.log('The Setter method: "' + currentArg[0] + '" is undefined');
        }
    }
}

That way all opening brackets are on the same vertical line as the closing ones and you can easily track which closing bracket is the one for a selected opening one (the first one below it on the same spacing distance). It's easier to trask the code that way if you're not using an IDE that is coloring the coresponding brackets.

A: When coding any language, normally entering a new block would cause indentation and exiting the same block does the opposite.  (JS indentation should be 4 spaces)
ie
function xyz(){
    alert("xyz");
}

and
function abc(){
    if(true){
        alert("true");
    }else{
        alert("false");
    }
    alert("abc");
}

..but like me if you get lazy and stop indenting using a tool like JSBeautifier whcih are available in most languages online just give it a search.


text:
Q: Check if a string is a string in ruby I want to check a string entered by a user. If it is a string, then move along, if not, then throw an error. I do not know how to check if the user input is a string or an int. Below is my code:
puts "what is your name?"
name = gets.chomp
if name == Int
puts "error enter a string"
end
if birthdate != Int
puts "error enter your birthdate"
end
puts "how old are you "
age = gets.to_i
if age == String
puts "error please enter your age"
end

puts "hello"  + name + " wow that is a good day to be born" + "thats a great age"
puts "the half  of your age is #{age/2.0} that is good to know"

A: I think this is what you are looking for.
 if name.class == String

Also this will always be false
age = gets.to_i  # this is converting to integer
if age.class == String # I think this is what you meant

age will always be an Integer her because you have cast it as such with .to_i

A: It may be checked as this:
  puts "what is your name?"
  name = gets.chomp
  if !(name =~ /[0-9]/).nil?
   puts "error enter a string"
  end
  puts "what is your age?"
  age = gets.chomp
  if age.to_i.to_s == age
   puts "error enter a integer"
  end


text:
Q: lodash dependency in a Gutenberg plugin I'm taking my first steps in Gutenberg block development and I'm already stuck. My block JS script makes use of a couple lodash functions (filter and pick). I'm registering my block using the following function:
function register_block() {
    wp_register_script(
        'block-script',
        plugins_url( 'block.build.js', __FILE__ ),
        array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' )
    );

    register_block_type( 'my/block', array(
        'editor_script' => 'block-script',
    ) );
}

As you can see I'm adding the lodash lib as a dependency, and checking the page source code it's effectively loaded before my plugin's script. However, I'm getting a ReferenceError: pick is not defined console error.
This is the line that calls the pick function:
onSelectImages( images ) {
    this.props.setAttributes( {
        images: images.map( ( image ) => pick( image, [ 'alt', 'caption', 'id', 'url' ] ) ),
    } );
}

I don't know what I'm doing wrong. Any ideas?
Thanks in advance

A: In the block script I had to replace:
import pick from 'lodash/pick';

with:
const { pick } = lodash;

And now it seems to work for me.

A: The problem is that lodash isn't a script dependency, it's an NPM dependency:
array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' )

You can't enqueue it this way and expect your application to build. Lodash may be available in WP Admin, but webpack runs in a local Node CLI context, and it doesn't know what lodash is. So instead you need to use npm to acquire the library and include it in your final JS build via babel/webpack/etc. This way webpack/babel know about lodash and can do their job correctly.


text:
Q: threading.Thread not executing loops on functions I've been trying to code an auto-clicker, but I first needed to learn how to use the Thread library, but I don't know why the code just stop when it runs the first time at the loop.
import time

from threading import Thread

def countdown(n):
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(5)

t = Thread(target = countdown, args =(10, ))
t.start()

The output is only:
>>> T-minus 10

Anyone can help me?

A: I just understood what was going on! If you trying to run a thread on a Jupyter Cell, it won't show the output, I changed the code a bit to test it.
import time

from threading import Thread

TIMES = 0

def countdown(n):
    global TIMES
    while n > 0:
        TIMES += 1
        time.sleep(5)

t = Thread(target = countdown, args =(10, ))
t.start()

And in the next cell I just kept printing the TIMES value and it was changing! but just in the background!
for i in range(10):
    time.sleep(3)
    print(TIMES)


text:
Q: How can i search for a specific word(Value) in database? I am making an android app , which scans a text and detects if a certain word is abusive. So i want my abusive words to be stored in database (SQLite).
My question is can i check if my text contains a word which is "forbidden". Should i use loop to check if each word of the text is contained in my database ? I need this to be fast.
Any help will be much appriciated.
Thanks in advance!
EDIT
I want the forbidden word to be displayed or stored in Arraylist.

A: I would suggest you save your scanned word in database, now use Like query to verify any forbidden word exists. If yes then keep that word otherwise delete it straightaway.
SELECT column_word FROM table WHERE id = "your_word_id" AND (column_word LIKE '%word1%'
                OR column_word LIKE '%word2%' OR column_word LIKE '%word3%')

If result cursor have more than zero data then it must have forbidden word.


text:
Q: How to get points from polydata instance? Like the code below, when we make an instance of vtkPolyData()(:here, polydata), we use SetPoints(points) to assign points. Then, when I want to get points(:an instance of vtkPoints()) this time, what should I do for polydata(:an instance of vtkPolyData())?
def points2actor(xyz, apoint_size):
    import vtk
    points = vtk.vtkPoints()
    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # Add points
    for i in range(0, len(xyz)):
        p = xyz.loc[i].values.tolist()
        point_id = points.InsertNextPoint(p)
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(point_id)
    # Create a poly data object
    polydata = vtk.vtkPolyData()
    # Set the points and vertices we created as the geometry and topology of the polydata
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.Modified()
    # Mapper for points
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(polydata)
    # ACTOR for points
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(apoint_size)
    return actor, polydata

A: Depending on what you plan to do with the data, it's probably the most efficient to load them into a numpy array:
from vtk.util import numpy_support

src_points = numpy_support.vtk_to_numpy(polydata.GetPoints().GetData())

Also python's builtin help is very useful with VTK.
import vtk
polydata = vtk.vtkPolyData()

help(vtk)
help(polydata)

A: points = polydata.GetPoints()
There is no python doc but the cpp API is the same:

*

*https://vtk.org/doc/nightly/html/classvtkPolyData-members.html

*https://vtk.org/doc/nightly/html/classvtkPointSet.html#af8a9a39d0ff4c56454be8d35a42b7f34


text:
Q: WPF application freezes on first WCF call I have WPF application that needs to access WCF service at start ( login window ). Each time application runs on Windows 7 it freezes on login until gets a responce from WCF. Is there any way to design this process differently?

A: It sounds like you need to make your calls asynchronously. Either start the call on a new thread (preferably using a Task), or call the WCF service using an asynchronous design pattern.

A: Put the WCF call in a background thread

A: There are two causes for something perceived as "freezing" when carrying out WCF Service Calls:

*

*Calling the service in a synchronous fashion will block your UI thread until the call has completed. This bad and the reason why Silverlight forbids synchronous calls and forces you to follow the Begin/End Async pattern for any kind of RPC - be it WebRequest or WCF Layer. By default the async methods are not generated when adding a service reference to your WPF project but you can turn it on using Configure Service Reference.

*The second cause is less obvious. The initial service client instantiation can take almost 3 seconds - even on fast machines. That's why you are well advised to QueueWorkUserItem the proxy instantiation and the BeginXXX call even when using the async pattern.

A: If you need the response from this service call to start the application, you can use a background thread to call this service and handle the return value. While this thread is consuming the service you can display your window or a splash screen.
If you don't need the retrun value from this service method you can use [OperationContract(IsOneWay=true)] on your service. So that you don't need to worry about threading and stuff.

A: You're calling a WCF call on the main thread, Therefore it will appear to crash.

*

*You can either, put it in a thread and call it at the start of your app.
Put it in a background process ( if you're in visual studio you can drag this off the tool bar)

You can do threads quite easily by defining a Thread, then defining a threadstart, passing in your login WCF call, and the call thread.start(); and pass in your threadstart you defined.
A background worker is pretty similar, you can put your code in the backgroundWorker1_DoWork() method

*

*Or make your WCF call Async, so it will send off the login response, and your login code will call on the "OnTaskCompleted" method( you could also  put it on a new thread as well, but don't really have to)

Try this thread for Async WCF calls
How to make a call to my WCF service asynchronous?


text:
Q: Reemplazar "/" por "-" dado en un string javascript y jquery tengo el siguente problema la cual consiste que estoy obteniendo un string de un input que contiene una fecha de la siguente manera "28/04/2018", despues necesito pasarlo a otro input para enviarlo desde un formulario.
Estoy intentado reemplazar de la siguente manera:
Esta la que obtengo atraves de jquery
var fecha = "28/04/2018"

Lo estoy intentando reemplazar de la siguiente manera
var nfecha = fecha.replace("//g", "-");

Espero su ayuda, gracias...

A: Según esta respuesta, debes hacerlo de esta forma:

var fecha = "28/04/2018"
var diaMesAño = fecha.replace(/\//g, '-');
console.log(diaMesAño);

Edit
Para responder a los comentarios. Una opción habría sido ponerlo todo desde el principio de esta forma:

var fecha = "23/11/2018"
var diaMesAño = fecha.split('/');
var formateado = diaMesAño[2] + '-' + diaMesAño[1] + '-' + diaMesAño[0];

console.log(formateado);

A: en mi trabajo usamos este código
Fecha.split("/").join("-")

Lo que hace es con el Split separa el string en un vector, dividido por las / y con join concatena el vector poniendo de separación el -
Espero te ayude, saludos

A: Según lo que pides en los comentarios, esta podría ser tu solución:

var fecha = "28/04/2018"
var splitDate = fecha.split("/");
var nuevaFecha = splitDate[2]+"-"+splitDate[1]+"-"+splitDate[0];
console.log( nuevaFecha);


text:
Q: Why not using events instead of state variables, for requests to oracles? Why not just emit events instead of using state variables, for requests to oracles? For example:
contract OracleConsumer {
  address oracle = 0x123...; // known account of oracle service

  modifier onlyBy(address account) {
    require(msg.sender == account);  _;
  }

  event OracleRequest(..., abi encoding of callback function )

  function updateExchangeRate() {
    event OracleRequest("USD", ..., "oracleResponse(bytes)" )
  }

  function oracleResponse(bytes response) onlyBy(oracle) {
    // use the data
  }
}

Instead of ones like in here


text:
Q: How to get all the keys present on the android keyboard using appium? While automating an android application using appium, is there a way to fetch all the keys currently displayed on a soft keyboard that get opened on clicking any input field.
Let's suppose if we click on a numeric field, we expect that a numeric keyboard will be opened, is there a way to get all the keys displayed as a result of this click?

A: No, Appium is not exposing any API to parse keyboard visual part or get keyboard type.
You can check if keyboard shown, send an event to it like keyUp/keyDown, hide it.
If its critical to test it, you may use new feature findElementByImage, where you will prepare images of keyboards and store it in your project, in test you will try to search for it. If element found, then your expected type of keyboard is present.

A: One of the solution can be type some keyword using tap on location and then get the text in search box. Now try to parse this to integer. If you are able to parse that means keyboard was numeric else alphabet. But this is not very optimized solution and needs extra care.


text:
Q: ggplot2: Thresholds for scale_alpha() Is it possible to specify thresholds for color-scales?
Look at this example:
xy <- expand.grid(x=1:20,y=1:20)
xyd <- data.frame(xy,z=runif(400),a=rowSums(xy)/40)
g <- ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) +
       geom_tile() +
       scale_alpha(range=c(0,1), limits=c(0.5,1))
g

What I want is that Values of a below 0.5 get an alpha value of 0 so that the lower left half will be invisible. Obviously I could transform the original data but that would destroy the legend.

A: None of my attempts to use the scales to control alpha were completely successful.  My best attempt was to use ifelse to control the value of a:
ggplot(xyd, aes(x=x, y=y, fill=z)) +
  geom_tile(aes(alpha=ifelse(a<=0.5, 0, a))) +
  scale_alpha(range=c(0,1))

So, a different approach is required: remove the values that you don't want to plot from the data:
xyd <- with(xyd, xyd[a>0.5, ])

ggplot(xyd, aes(x=x, y=y, fill=z)) +
  geom_tile(aes(alpha=a))

A: The threshold is working and the values outside that threshold are set to NA; the problem is that an alpha of NA is getting rendered as full opacity.  Setting the na.value on the scale to 0 gets the results you want.
ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) +
       geom_tile() +
       scale_alpha(range=c(0,1), limits=c(0.5,1), na.value = 0)


text:
Q: How to replace lookbehind PHP structure of Regex into Javascript? I have built Regex which is working properly with php , but not working in Javascript due to Invalid group structure error.
I know it is because Javascript does not support Lookbehind expressions. I tried to convert it but not able to do so.
Regex link : https://regex101.com/r/bC4hN2/1
Regex Expression : (?<=^| )(.\d+)?(?=$| )|(?<=^| ).\d+(?=$| )
Acceptance Criteria : Values should lie between 0 and 1 and should start with decimal point
Valid entries

*

*.20

*0

*1

*.1

Invalid Entries

*

*1.20

*1.0

*0.20

*2

This scenarios working properly with PHP Regex Expression , but not with Javascript due to errors.
How should i convert it to Javascript OR any alternate expression to achieve my scenario ?
Thanks

A: This can be done easily as mentioned in comments but let's modify your regex. (Your match is in first capturing group)
(?:\s|^)([01]\b|(?:\.\d+))(?=\s|$)

Regex Demo


text:
Q: Get Android resource ID from string in an adapter I'm trying to get Android resource ID and set ImageView src to that specific ID from a JSON array.
I'm using the following code
String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        int res = Resources.getSystem().getIdentifier("ic_" + str, "drawable", this.getClass().getPackage().getName());
        if(res == 0)
        {
            Log.d("is null", "null");
            Log.d("string = ", "ic_" + str);
            Log.d("package", this.getClass().getPackage().getName());
        }

But from some reason it's detecting the res int as 0. Package name seems correct, string is correct but for some reason it's not finding the correct drawable resource. What am I doing wrong here?
EDIT:
Full adapter code

package com.xyz

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

/**
 * Created by Kreso on 23.3.2017..
 */

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{

    private List<Category> mDataset;
    private Context context;

    public CategoryAdapter(List<Category> categoriesList) {
        mDataset = categoriesList;
    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView txtHeader;
        public ConstraintLayout holderLayout;
        public ImageView icon;

        public ViewHolder(View v) {
            super(v);
            txtHeader = (TextView) v.findViewById(R.id.firstLine);
            holderLayout = (ConstraintLayout) v.findViewById(R.id.itemHolder);
            icon = (ImageView) v.findViewById(R.id.icon);
            context = v.getContext();
        }
    }

    /*public void add(int position, String item) {
        mDataset.add(position, item);
        notifyItemInserted(position);
    }*/

    public void remove(int position) {
        mDataset.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mDataset.size());
    }

    // Provide a suitable constructor (depends on the kind of dataset)
   /* public CategoryAdapter(ArrayList<String> myDataset) {
        mDataset = myDataset;
    }*/

    // Create new views (invoked by the layout manager)
    @Override
    public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_row, parent, false);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
    final String name = mDataset.get(position).name;
        holder.txtHeader.setText(mDataset.get(position).name);
        //holder.icon.setImageResource(R.drawable.ic_beer);
        String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        int res = context.getResources().getSystem().getIdentifier("ic_" + str, "drawable", context.getPackageName());
        if(res == 0)
        {
            Log.d("is null", "null");
            Log.d("string = ", "ic_" + str);
            Log.d("package", this.getClass().getPackage().getName());
        }

        holder.icon.setImageResource(res);
        holder.holderLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remove(position);
        }
    });

}

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

A: use this code, to get image from Resources :
int res = context.getResources().getIdentifier("ic_" + str, "drawable", context.getPackageName());

A: I have managed to solve it by using a slightly different approach
// Remove file extension
        String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        // Replace - with underscore _
        str = str.replace("-", "_");

        int res = 0;
        // Try to find the resource with that name (icons in drawable folder)
        try {
            res = R.drawable.class.getField("ic_" + str).getInt(null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // if no icon is found
            holder.icon.setImageResource(R.drawable.ic_coffee);
        }
        // Set icon resource
        holder.icon.setImageResource(res);


text:
Q: spring-cloud with ribbon/eureka/hystrix using restTemplate unable to set connect/read timeouts I have built a spring boot application using spring-cloud and want to use RestTemplate within my client application (which is also a microservice) so that I can continue using mockMvc for integration testing.   I am a using the default ribbon/eureka/hystrix client setup with my client microservice and eureka client within the service I'm calling.  This is working (once I figured out that serviceIds are what identifies a service endpoint within restTemplate).  My problem is that I cant seem to change the restTemplate read nor connection timeout from what seems like a default of 300ms.
Details on the call:
`@Configuration
 @EnableAutoConfiguration
 @ComponentScan
 @EnableConfigurationProperties
 @EnableHystrix
 @EnableEurekaClient
public class Application { ... public static void main(String[] args) {} ... }

@Component
class EricComponentToDoHystrix {   // apparently this has to be a component for hystrix to work btw
    @Autowired
    RestTemplate restTemplate;
    ..
    @HystrixCommand(fallbackMethod="defaultRestTemplateCall")
    public void doRestTemplateCall()
        ResponseEntity<String> result = restTemplate.getForEntity("http://someservice/doSomething", String.class);  // actually make a call
    ..
    }
}`

with an application.properties containing:
spring:
  cloud:
    client:
      serviceIds:
        - someservice

someservice:
  ribbon:
    #listOfServers: localhost:7080
    #NIWSServerListClassName: com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList

    # the eureka vipAddress of the target service (Disabled)
    DeploymentContextBasedVipAddresses: someservice

    # Interval to refresh the server list from the source
    ServerListRefreshInterval: 1000

    # Connect timeout used by Apache HttpClient.. apparently not by restTemplate
    ConnectTimeout: 30000

    # Read timeout used by Apache HttpClient.. apparently not by restTemplate
    ReadTimeout: 30000

eureka:
  client:
    #Region where eureka is deployed -For AWS specify one of the AWS regions, for other datacenters specify a arbitrary string
    #indicating the region.This is normally specified as a -D option (eg) -Deureka.region=us-east-1
    region: default

    #For eureka clients running in eureka server, it needs to connect to servers in other zones
    preferSameZone: false

    us-east-1:
      availabilityZones: default

  instance:
    #Virtual host name by which the clients identifies this service
    virtualHostName: ${spring.application.name}
    appGroupName: ericGroup

# disable Ribbon's cicruit breaker and rely soley on Hystrix.
# this helps to avoid confusion.
# see https://github.com/Netflix/ribbon/issues/15
niws:
  loadbalancer:
    availabilityFilteringRule:
      filterCircuitTripped: false

Anybody know what properties I need so set to modify restTemplate's default timeouts?  Documentation is very light on this subject and it seems the code just recently even allowed restTemplate to be used against ribbon/eureka spring boot defaults.  Perhaps this has not been built yet.

A: The RestTemplate you are injecting is completely vanilla except for a RibbonInterceptor that chooses the physical host in the URI for you (see https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java). The timeouts and other properties are controlled in the RestTemplate through the ClientHttpRequest. You probably should just inject the RibbonInterceptor into your own RestTemplate and set up a ClientHttpRequestFactory to do the timeouts, e.g.
@Component
class EricComponentToDoHystrix {
    private RestTemplate restTemplate;
    @Autowired
    public EricComponentToDoHystrix(RibbonInterceptor interceptor) {
         restTemplate = new RestTemplate();
         restTemplate.setInterceptors(Arrays.asList(interceptor));
         restTemplate.setRequestFactory(...);
    }
}

A: Since I can't comment, I'll answer.  The RestTemplate integration only uses the Ribbon LoadBalancer, not RestClient or NFHttpClient.
You no longer need spring.cloud.client.serviceIds, btw.  If it is in docs, I'll remove it.


text:
Q: Unable to delete UDF I am using cassandra 3.10 and I am trying to delete two UDF which I had created: cal_group_and_total and group_by_total. group_by_total calls the former function so I first decided to delete the second function. And when I enter the following command: cqlsh>DROP FUNCTION group_by_total;. I get the following error: InvalidRequest: Error from server: code=2200 [Invalid query] message="Unconfigured function tec.group_by_total()"

A: 1) First check if function exist.
cqlsh> USE keyspace_name;

cqlsh> DESCRIBE FUNCTIONS;

2) If exist
cqlsh> DROP FUNCTION keyspace_name.group_by_total;


text:
Q: using Java mouseClicked event handler to change icons I have tons of labels. My problem is that I don't know how to write that if i click label2, then set a new image on label2 but label1 doesnt change. labels are named like A1-A10. (I actually have 92 labels, so this is getting cumbersome.) Here's my code:
public void mouseClicked(MouseEvent event) {

    if (event.getSource()==A1 && (x==1)) {
        A1.setIcon(new ImageIcon("zoldgomb.jpg"));
        x=2;
    } else if(x==2) {
        A1.setIcon(new ImageIcon("sargagomb.jpg"));
        x=1;
    }
}

edit
ok, i solved it, thx everybody :)
if (event.getSource() instanceof JLabel) {
                if (x == 1) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("zoldgomb.jpg"));
                    x = 2;
                } else if (x == 2) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("sargagomb.jpg"));
                    x = 1;
    }
}

A: *

*It sounds like you should be using either an array or ArrayList of JLabel.

*Variable names should all begin with a lower letter while class names with an upper case letter. Also you should avoid using trivial variable names such as b or s unless they are being used for trivial purposes such as the index of a for loop. Instead use names that have some meaning so that your code becomes self-commenting.

*You can identify which JLabel was pressed by calling getSource() on the MouseEvent objevct passed into your method. Your parameter is named event above.

*Then after testing which JLabel is pressed, call its setIcon(...) method.

*You're better off reading in your images once and saving them to a variable, and not re-reading them in on each mouse click.


text:
Q: query that subtracts sum of one column from another I have a table similar to the following in my database
+----+----+----+---------------------+
| id | a  | b  | date_created        |
+----+----+----+---------------------+
|  1 | 22 | 33 | 2014-07-31 14:38:17 |
|  2 | 11 |  9 | 2014-07-30 14:40:19 |
|  3 |  8 |  4 | 2014-07-29 14:40:34 |
+----+----+----+---------------------+

I'm trying to write a query that subtracts sum(b) from each a. However, the values of b included in sum(b) should be only those that are earlier than (or the same time as) the a they are being subtracted from. In other words, the results returned by the query should be those shown below
22 - (33 + 9 + 4)
11 - (9 + 4)
 8 - (4)

is it possible to calculate this in a single query?

A: select id, a, a - (select sum(b)
                     from My_TABLE T2
                    where T2.date_created <= T1.date_created)
  from MY_TABLE T1;

A: Something like this should work:
select t1.a - ifnull( sum(t2.b), 0)
from myTable t1
left outer join myTable t2 on t2.date_created <= t1.date_created
group by t1.a

Note that the table is joined to itself to access two different sets of information.
Edit:
I think you probably want to group by the date_created like:
select t1.date_created, t1.a - ifnull( sum(t2.b), 0)
from myTable t1
left outer join myTable t2 on t2.date_created <= t1.date_created
group by t1.date_created, t1.a

A: Another alternative
SQL Fiddle Example
SELECT
   id,
    a - (@total := @total + b) as Total
 FROM
    (SELECT *, @total:=0
     FROM  my_table
     ORDER  BY date_created asc) AS Base

A: SELECT x.*
     , x.a - SUM(y.b)
  FROM my_table x
  JOIN my_table y
    ON y.date_created <= x.date_created
 GROUP
    BY x.id;


text:
Q: Connection to postgresql on EC2 from heroku I have problems connecting to an external Postgresql database on EC2 from my heroku app. The problem seams to be with the permission on EC2.
I have done the following:
- added 098166147350/default for my security group on port 5432 (my postgresql port)
- connect to the site using the "Public DNS"-address (ec2-x-x-x-x.compute-1.amazonaws.com).
The database I try to connect to is in the EU and not US-East region as the heroku app, don't know if this makes any difference?
Anyway if I add 0.0.0.0/0 to 5432 it does work, so I guess it got to have to be the security settings.
Anyone have any idea what the problem could be?

A: I got back from heroku support:
Apparently the different i region (us-east (heroku) -> eu (my db)) makes a different in adding a security group like that. So the they suggested a VPN tunnel from us-east on my account to eu. Or just 0.0.0.0/0 and rely on SSL and good passwords.


text:
Q: Recursive directory with mkdir not working I am uploading multiple images within a single category and I would like to store each group of images in a unique directory within my 'images/' directory as follows:
'images/unique_category/image1.jpg'
I have the following code but it is not creating a directory. I suspect it has something to do with setting the recursive parameter as 'true' which I believe I have done. Am I using the mkdir function incorrectly?
Thank you!
$unique_directory = "../images/".$_POST['item_name'];
if (is_dir($unique_directory)
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  $unique_directory."/".$_FILES["file"]["name"]);
  echo "Stored in: " . $unique_directory."/".$_FILES["file"]["name"];
  }
else
  {
  mkdir($unique_directory, 0777, true);
  move_uploaded_file($_FILES["file"]["tmp_name"],
  $unique_directory."/".$_FILES["file"]["name"]);

A: Here, give this a try. I tested it on my (hosted) server and it works. Yet, I tested it by placing the files in the root of it, and used images instead of ../images for the $unique_directory variable.
I also used the chmod command apart from the other function, because the other method did not work.
N.B.: If possible, try changing 0777 to 0755, because using 0777 is not the safest setting.
<?php
$filename = $_POST['item_name'];
$unique_directory = "../images";

if (!is_dir($unique_directory . '/' . $filename)){

    mkdir($unique_directory . "/" . $filename);

    chmod("$unique_directory" . "/" .$filename, 0777);
}

if (is_dir($unique_directory))
  {
  move_uploaded_file($_FILES['file']['tmp_name'], $unique_directory . "/" . $filename . "/" . $_FILES['file']['name']);
  echo "1) Stored in: " . $unique_directory . "/" . $filename . "/" . $_FILES['file']['name'];
  }

else
  {
  move_uploaded_file($_FILES['file']['tmp_name'], $unique_directory . "/" . $filename . "/" . $_FILES['file']['name']);
  echo "2) Stored in: " . $unique_directory . "/" . $filename . "/" . $_FILES['file']['name'];
}
?>


text:
Q: Magento 2 checkout 'shipping-information' response In checkout page when we click Next button from shipping step, we can see a response named shipping-information that contains payment methods and totals information. Where is this response come and can i access/modify the response?

A: This is a response from Checkout Web API entry point:
/V1/guest-carts/:cartId/shipping-information - GuestShippingInformationManagementInterface::saveAddressInformation for guest customer
/V1/carts/mine/shipping-information - ShippingInformationManagementInterface::saveAddressInformation for logged customer.
/V1/carts/:cartId/shipping-information - ShippingInformationManagementInterface::saveAddressInformation for logged customer.
All Checkout Web API entry points are specified in webapi.xml.
To customize this response, you need to create own Web API services and override Checkout entry points in your custom webapi.xml or use plugins for API interfaces implementations, but you must be sure what you won't broke Magento Checkout js components.

A: You need to modify following class

Magento/Checkout/Model/ShippingInformationManagement.php

saveAddressInformation Method return payment info and total.
You can modify this class using plugin.


text:
Q: SPARK to ELASTIC SEARCH program throwing exception, Append output mode not supported l am running the following code on windows its throwing an error and not working . zk,kafka,elasticsearch all server are running though. data is already published to the kafka topic
  object kses {
      def main(args: Array[String]): Unit = {

  val spark = SparkSession.builder.
    master("local")
    .appName("sparkToES")
    .config("es.nodes", "localhost")
     .config("es.index.auto.create","true")
     .getOrCreate()

  import spark.implicits._

  spark.sparkContext.setLogLevel("ERROR")

  val df = spark
    .readStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "localhost:9092")
    .option("subscribe", "logi1")
    .option("startingOffsets", "earliest")
    .load()

  val data = df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    .as[(String, String)]

  val results = data
    .map(_._2)
    .flatMap(value => value.split("\\s+"))
    .groupByKey(_.toLowerCase)
    .count()

    val query = results.writeStream

      .format("org.elasticsearch.spark.sql")
      .outputMode("append")
      .option("es.nodes", "localhost")
      .option("es.port", "9200")
      .option("es.nodes.discovery", "true")
      .option("es.http.timeout", "20s")
      .option("es.http.retries", "0")
      .option("es.resource","logi123")
      .option("checkpointLocation", "~/checkpoint_es")
      .start()

  query.awaitTermination()

}

}

  ERROR - Exception in thread "main" org.apache.spark.sql.AnalysisException: Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark;

When i change it to 'complete' mode then also code doesnot run.

zk,kafka,elasticsearch all server are running though.

A: ElasticSearch Resource path in Save() should be the path of the Index Resource on the ES node not your local path.
Check the connectivity of the ES node and provide the valid Index (for ex: "index/persons") path in Save() method.
df.write.format("org.elasticsearch.spark.sql").option("es.nodes.wan.only","true")
.option("es.port","9200")
.option("es.net.ssl","true")
.option("es.nodes","192.168.0.1")
.mode("append")
.option("es.nodes.client.only", "false")
.save(<Index Resource PATH>)


text:
Q: Reactive Angular Material Data Table I've created an Angular Material Data Table with this ng generate @angular/material:material-table command and it gave me following file structure:

*

*table-datasource.ts

*table.component.ts

*table.component.html
The idea here is to do all the fetching, sorting and pagination in the table-datasource.ts. By default the data is placed in an Array inside table-datasource.ts but in my case its coming from an ngxs-store which exposes an Observable of an Array. Atm I have following implementation:
table-datasource.ts:
export class TokenTableDataSource extends DataSource<TokenTableItem> {
  @Select(TokenTableState.getTokenTableItems) private tokenTableItems$:Observable<TokenTableItem[]>;
  totalItems$ = new BehaviorSubject<TokenTableItem[]>([]);

  constructor(private paginator: MatPaginator, private sort: MatSort) {
    super();
  }

  /**
  * Connect this data source to the table. The table will only update when
  * the returned stream emits new items.
  * @returns A stream of the items to be rendered.
  */
  connect(): Observable<TokenTableItem[]> {
    this.tokenTableItems$.subscribe(item => this.totalItems$.next(item));

    // init on first connect
    if (this.totalItems$.value === undefined) {
      this.totalItems$.next([]);
      this.paginator.length = this.totalItems$.value.length;
    }
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.totalItems$),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(
      map(() =>  this.totalItems$.next(this.getPagedData(this.getSortedData([...this.totalItems$.value])))),
      mergeMap(() => this.totalItems$)
    );
  }
  ...generated paging and sorting methods

table-component.html:

  ...multiple columns

  <mat-paginator #paginator
      [length]="this.dataSource.totalItems$.value?.length"
      [pageIndex]="pageIndex"
      [pageSize]="pageSize"
      [pageSizeOptions]="pageSizeOptions"
      [showFirstLastButtons]=true
      (page)="handlePage($event)">
  </mat-paginator>

table.component.ts:
export class TokenTableComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: TokenTableDataSource;

  pageSizeOptions = [5, 10, 20, 40];
  pageSize = this.pageSizeOptions[0];
  pageIndex = 0;
  tableLength = 0;

  ... colums definition

  ngOnInit(): void {
    this.dataSource = new TokenTableDataSource(this.paginator, this.sort);
  }

  public handlePage(pageEvent: PageEvent) {
    // do what?
  }
}

What's working:

*

*The data is rendered correct (triggered with a button and via the ngxs-store)

*I can sort the data

What's not working:

*

*On first data load the pageSize is ignored at all and all rows are displyed

*When clicking sorting or a pagination element, the current selected pageSize is taken and this amount of rows is rendered. What's strange to me is that this only works descending (given pageSize is 10 and I select 5 it results in 5 rows but once 5 is selected it's not possible to display more rows than 5 again)

Requirements:

*

*I like the idea to encapsulate all data manipulations behind TableDataSource.connect() so a solution like this where the fetching is done in the comonent is not desired. Furthermore this doesn't have sorting implemented.

*The app uses an ngxs-store, which is very similar to ngrx, so any solution involving this part is welcome.

*I haven't figured out what to do with pageEvents so my guess is that the solution is in the handlePage() method.

Versions:

*

*RxJS 6.3.x

*Angular 7.x

*ngxs 3.3.x

A: I figured out how to setup a table for my requirements. The main change is that I removed the Observable which fetches the data from the TableDataSource and introduced a DataService:
export class DataService {
  //the @Select is from ngxs but can be anything returning an Observable
  @Select(TokenTableState.getTokenTableItems) private tokenTableItems$: Observable<TokenTableViewItem[]>;
  private initValue$: BehaviorSubject<TokenTableViewItem[]> = new BehaviorSubject<TokenTableViewItem[]>([]);

  getAllItems(): Observable<TokenTableViewItem[]> {
    const sources = [this.tokenTableItems$, this.initValue$];
    return merge(...sources);
  }
}

Basically that service gets the data from any Observable input and merges this in the getAllItems method with an initial value.
The Component has an instance of this service:
private _dataService: DataService | null;
which it hands over to the TableDatasource in the load method:
private loadData(): any {
    this._dataService = new DataService();
    this.dataSource = new TokenTableDataSource(
      this._dataService,
      this.paginator,
      this.sort
    );
    fromEvent(this.filter.nativeElement, 'keyup').subscribe(() => {
      if (!this.dataSource) {
        return;
      }
      this.dataSource.filter = this.filter.nativeElement.value;
    });
  }

The reason I don't have a reference of the DataService in the TableDataSource is that the paginator in the Component needs the length of the table for rendering (seen below).
The TableDataSource consumes the DataService like this:

*

*In the connect method it holds an array with possible data mutations:
const dataMutations = [
  this._dataChange,
  this._sort.sortChange,
  this._filterChange,
  this._paginator.page
];

*The _dataChange member of the array gets it value by subscribing to the getAllItems method from our DataService:
this._internalService.getAllItems().subscribe(data => {
  this._dataChange.next(data);
});

*The dataMutations are used like this to filter, sort and return the data which should be displayed:
return merge(...dataMutations).pipe(
  map(() => {
    // Filter data
    this.filteredData = this._dataChange.value
      .slice()
      .filter((item: TokenTableViewItem) => {
        const searchStr = (item.symbol + item.name).toLowerCase();
        return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
      });
    // Sort filtered data
    const sortedData = this.getSortedData(this.filteredData.slice());

    // Grab the page's slice of the filtered sorted data.
    this.renderedData = this.getPagedData(sortedData);
    return this.renderedData;
  })
);

The filterChange is defined in the local instance
_filterChange = new BehaviorSubject('');
while the pagination and sorting are triggered from outside via the constructor
constructor(
  public _internalService: DataService,
  public _paginator: MatPaginator,
  public _sort: MatSort
) {
  super();
  this._filterChange.subscribe(() => (this._paginator.pageIndex = 0));
}

I also found a solution for the pagination which is defined in the component.html like this:
<mat-paginator #paginator
  [length]="dataSource.filteredData.length"
  [pageIndex]="pageIndex"
  [pageSize]="pageSize"
  [pageSizeOptions]="pageSizeOptions"
  [showFirstLastButtons]=true>
</mat-paginator>

and with the variables set in the component.ts:
pageSizeOptions = [5, 10, 20, 40];
pageSize = this.pageSizeOptions[0];
pageIndex = 0;

The full code can be seen at this project and a live version of the table is used at whatsmytoken.com.

A: WOW!
just about the same time, I wrote an article about my Reactive DataSource, that can be easily extended for multiple data lists! you can add optional and required mutators, accompanied of getter functions to collect the respective arguments and merge them in a REQuest object.
I explained the overall stuff here:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6
and I mounted a demo on StackBlitz too
with a Github repo showing with simple commits,
how simple is to set up a filtered/sorted/paginated list in a clean way.
I hope you give me some feedback about my library,
and if you find it appealing, I can be sure to support you with your use cases too :)
Happy coding!


text:
Q: Errors when creating a cumulative return column using for loop for each stock dataframe I get five stocks history price and want to create a column of cumulative return for each of them and i tried to use the for loop. But it returned the errors of "TypeError: 'Ticker' object is not subscriptable"
msft = yf.Ticker("MSFT")
apple=yf.Ticker("AAPL")
amzn=yf.Ticker("AMZN")
alibaba=yf.Ticker("BABA")
Tencents=yf.Ticker("TCEHY")

baba=alibaba.history(period="ytd")
msft=msft.history(period="ytd")
apple=apple.history(period="ytd")
Tencents=Tencents.history(period="ytd")
amzn=amzn.history(period="ytd")

for stock_df in (msft,apple,amzn,alibaba,Tencents):
    stock_df["cum-return"]=stock_df["Close"]/stock_df["Close"].iloc[0]

Can anyone help me with this problem. Thanks

A: In the array, you are iterating over alibaba, its type is yf.Ticker, you should replace that with babainstead, since baba is the DataFrame.
Not subscriptable means you are trying to slice an element which can't be sliced, for example stock_df['cum-return], yf.Ticker don't support slicing.


text:
Q: add controls (Picturebox) in loop What i have:  Big PictureBox (lets call it Pic_Map) on the form. A class Ore.cs, A List<Ore> ores; and a database that pulls the data and places it into the ores list.
Functionality:  So, The functionality of this is i have a TextBox/Combobox and a Button. When i press the Button, it will loop through the ores list and Dynamically add PictureBoxes ontop of the Pic_Map based on TexBox/ComboBox being equal to the data (in this case Ore_Name).
Problem:  This all works fine, but the problem is that when i add the PictureBoxes Dynamically, it only seems to add the last value on the ores list (Red circles on Pic_Map). so, it ends up showing only 1 PictureBox instead of lets say 3, since i have 3 value Names that match with the TextBox/ComboBox.
Question:  How to get it to work like when i write/choose "Flame Stone" it looks on all the data that has "Flame Stone" in its name and add it (Instead of it adding only the last value from the list).
Code:
private void PopulateComboBoxByName()
    {
        PictureBox ore_Area = new PictureBox();

        db.GetOre(); //Getting data and putting it into "ores" list

        foreach (Ore ore in db.ores)
        {
            if (CBOX_Filter.SelectedItem.ToString() == ore.Ore_Name)
            {
                int area_Width = Convert.ToInt32(ore.Area_Width);
                int area_Height = Convert.ToInt32(ore.Area_Height);

                int ore_Width = Convert.ToInt32(ore.Ore_Width);
                int ore_Height = Convert.ToInt32(ore.Ore_Height) - area_Height / 2;
                ore_Area.Name = "ore_Area";

                ore_Area.ImageLocation = @"Data\Images\Circle.png";
                ore_Area.SizeMode = PictureBoxSizeMode.StretchImage;

                ore_Area.Size = new Size(Convert.ToInt32(area_Width), Convert.ToInt32(area_Height));
                ore_Area.Location = new Point(Convert.ToInt32(ore_Width), Convert.ToInt32(ore_Height));
                ore_Area.BackColor = Color.Transparent;

                this.Controls.Add(ore_Area);
            }
        }

        ore_Area.Parent = PIC_Map;
    }

Images:
Data:

Map:

A: Thanks to LarsTech, it has been fixed.
Making the picturebox is moved inside the loop, this.controls.add is changed to PIC_Map.controls.add and Ore_Area.Parent = PIC_Map; is deleted.


text:
Q: Custom route doesn't find controller action For some reason my application isn't routing to my controller method correctly. I have a routelink like this in my webpage -
<%= Html.RouteLink("View", "Blog", new { id=(item.BlogId), slug=(item.Slug) }) %>

In global.asax.cs I have the following routes -
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "MoreBlogs",
        "Blog/Page/{page}",
        new { controller = "Blog", action = "Index" }
    );

    routes.MapRoute(
        "Blog",
        "Blog/View/{id}/{slug}",
        new { controller = "Blog", action = "View"}
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Blog", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

And then I have a class BlogController that has a method -
   public ActionResult View(int id, string slug)
    {

       ... etc.
    }

I put a breakpoint in the first line of the View method but it's not getting hit at all. I checked with a route debugger for the format localhost/Blog/View/1/test and it matched my custom route. All I'm getting is a 404 while running this, I can't work out why the route won't post to the view method in my controller - any ideas?

A: (Assuming the route debugger was based on Phil Haack's debugger post)
If you're getting a 404, that makes me think the actual view page itself cannot be found.

A: Assuming that you are also using areas within the application, and that RouteLink is actually being called from within an Area, I think you may need to specify area="" in your routeValues object ( you also need to specify the controller). In general, I think that you will need to add the area="..." part with all your Routelink calls when using Areas.
This is something that I have picked up about RouteLink and Area, but cant seem to find any reference material detailing the limitations.


text:
Q: Would a set of very massive spinning disks on the lowest points of a ship increase its inertia to ocean waves? Would a set of very massive spinning disks on the lowest points of a ship increase its inertia to ocean waves? As ships are filled with an enormous mass of balast water which is not enviroment friendly should this idea possibly make a change? How to fix the issue that the center of rotation of such disk would feel a very strong torque when a huge wave strikes the ship?

A: If the mounting of the spinning disk is fixed then it will be no good.
However, in the market of luxury motor yachts there are systems available that apply gyroscopic effects with a responsive mounting. You can internet search with search terms such as 'stabilizer', 'gyro' and/or 'gyroscopic'
Strong actuators are in place that tilt the fast spinning gyro wheel.

Use case:
The mounting to the frame of the boat is such that on a flat sea the gyro system can cause the boat to roll from from side to side.
When the boat is in a swell that is causing the boat to roll from side to side the gyro system can diminish that side-to-side roll to a large extent.
Incidentally, a boat fitted with a gyro stabilizer still needs to be well trimmed in order to not have any list. If you would try to counteract a list with the gyro system then quite quickly the gyro system will be saturated.
Ideally the gyro stabilizer system should remain close to it's unsaturated home position. That way the system has room to spare. A swell causes oscillation with respect to the trimmed state. So the gyro stabilizer system will perform best when operating on a well trimmed boat.

[Later addition]
Initially I opted to only mention the existence of gyro stabilizers. A quick search will find that the operating principle of gyro stabilizers is gyroscopic precession. Gyroscopic precession is discussed here on physics.stackExchange in a 2012 answer written by me.
(Well, the question 'what is gyroscopic precession?' has many duplicates here on physics stackexchange, because people keep asking that same question over and over again. (Yeah, duplicates are supposed to be flagged, but with gyroscopic precession questions that isn't happening.))
The gyro stabilizers on luxury yachts are set up as follows: the spin axis points vertical. There are actuators that can force a pitching motion of the spinning gyro wheel. (I'm using the standard names for ship motions )
When the ship is on calm water:
When the gyro wheel is in pitching motion then in response the gyro wheel will tend to roll. The gyro wheel is mounted in such a way that roll motion of the gyro wheel is transferred to the entire ship.
So on calm water:
Forcing a pitching motion of the gyro wheel causes roll of the ship as a whole.
When there is a swell then the gyro stabilization system is used to counteract the effect of that swell on the ship.
Here is what would happen if the gyro wheel is mounted in such a way that the spin axis is fixed relative to the frame of the ship.
In that case: when there is a swell it causes the ship to roll from side to side. In order to counteract that rolling the gyro wheel must perform a pitching motion. But a ship is much longer than it is wide; pitching motion of a ship requires a far far larger force than rolling motion.
When pitching motion is denied to the gyro wheel the spinning gyro wheel offers no opposition to rolling of the ship.
So that is a circumstance that is unique to the case of mounting a gyro wheel, for the purpose of attitude control, on a ship.
With a gyro stabilizer system the purpose of the actuators is to force the pitching motion that is required to elicit the desired response from the gyro wheel.

A: There is another way to accomplish this which does not require big rotating masses, as follows:
In the ship is mounted a small gyroscope with roll and pitch sensors attached to it, just like in the attitude gyro in an airplane's autopilot.
Sticking out of the sides of the hull are large fins whose pitch is controlled with accordingly large servomotors.
The servomotor control system is connected to the roll and pitch sensors in the gyro, so that when the gyro senses roll or pitching movement of the hull from wave action, the servomotors adjust the pitch of the fins to produce a countertorque which cancels the rolling and pitching induced by the waves.
As such, this system works in exactly the same way as the autopilot system in the airplane: when engaged, it holds the hull level and horizontal in the roll and pitch axis.
Systems like this can be retrofitted to ships originally intended for cargo use when they are converted to passenger use, to increase passenger comfort. However, engaging the automatic roll-and pitch control lock has the effect of slowing down the ship, so even if it is available, it is not always used if the captain is in a hurry.


text:
Q: Use capitalized hash keys in a map? I'm trying to create some sample data:
1.upto(19).map {|n| { Keyword: "some-term-#{n}", TotalSearches: n } }

But the data that comes back has slightly different hash keys:
[{:Keyword=>"some-term-1", :TotalSearches=>1}, ...

How can I force it to use the hash keys I specified, like this?
[{"Keyword"=>"some-term-1", "TotalSearches"=>1}, ...

If I put quotes around the hash keys:
1.upto(19).map {|n| { "Keyword": "some-term-#{n}", "TotalSearches": n } }

I get an error.

A: There's two notations for Ruby hashes.
The first is the traditional notation:
{ :key => "value" }
{ "key" => "value" }

The new notation looks more like JavaScript and others:
{ key: "value" }

This is equivalent to the traditional notation { :key => "value } which is how it shows up in inspect mode, so don't worry if the presentation changes, it's actually the same thing. The new notation forces the use of symbol keys.
If you want to use string keys you need to use the traditional notation.
It's worth noting you can mix and match in the same definition:
{ key: "value", "Key" => "value" }

Ruby encourages the use of symbol keys in cases where the keys are predictable and used frequently. It discourages symbol keys when you're dealing with arbitrary user data such as parameters from forms. In that case strings are a better plan.


text:
Q: Check user Exist in AD group using python I am new to python development, trying to convert PowerShell code to python.
I am looking for a python code to check user exists in AD domain . Equivalent to PowerShell command (dsquery user -name $username) . if account exists then get the user CanonicalName Properties.  Equivalent to PowerShell command (Get-ADUser $username -Properties * | Select CanonicalName). Thanks for your help.


text:
Q: Test async function without setTimeout I would like it if someone can help me to test this function without using the setTimeout that I am using IN THE TEST FILE. after doing a lot of research I was able to make it go, but that setTimeout is a time bomb.
I probed with jasmine-promises and a thousand different ways but none of them worked.
service:
angular.module('moduloPrueba', [])
  .factory('asincronico', function($q) {

  return {
    tes:tes,
  };

  function tes(){
    var deferred = $q.defer();

    setTimeout(function () {

      deferred.resolve(79);
    }, 50);

    // Return the deferred promise
    return deferred.promise;
  }

});

jasmine test:
describe('description', function () {
  var asi;
  var root;
  var res;

  beforeEach(function () {
    module('moduloPrueba');
    inject(function (asincronico, $rootScope) {
      root = $rootScope;
      asi = asincronico;
    })
  });

  it('should ', function (done) {
    asi.tes().then(function (resp) {
      res = resp;
      done();
    });

    setTimeout(function () {
      root.$digest();
      expect(res).toEqual(79);
      expect(res).not.toEqual(123);
    }, 200);

  });

});

A: Use the $timeout service instead of setTimeout.
angular.module('moduloPrueba', [])
    .factory('asincronico', function ($q, $timeout) {

        return {
            tes: tes
        };

        function tes() {
            var deferred = $q.defer();

            $timeout(function () {

                deferred.resolve(79);
            }, 50);

            // Return the deferred promise
            return deferred.promise;
        }

    });

Then call $timeout.flush() in your test to wait for the timeout to finish, followed by a $rootScope.$digest() to get the promise to resolve. You also will not need a done callback anymore since this will run synchronously.
describe('description', function () {
    var asi;
    var root;
    var timeout;

    beforeEach(function () {
        module('moduloPrueba');
        inject(function (asincronico, $rootScope, $timeout) {
            root = $rootScope;
            asi = asincronico;
            timeout = $timeout;
        })
    });

    it('should ', function () {

        asi.tes().then(function (resp) {
            expect(resp).toEqual(79);
            expect(resp).not.toEqual(123);
        });

        timeout.flush();
        root.$digest();
    });

});


text:
Q: java check if list of object contains object with concrete name I have list of objects:
List<City> cities = city.getList();

I would like to remove duplicates (where duplicates mean objects with the same value of parameter name and different (id, and other parameters);
I have code for that:
for(City c: cities) {
    System.out.println("analise " + c.name);
    if(!temp.contains(c)) {
        temp.add(c);
    }
}

I've wrote for that hashCode() and equals() method:
@Override
public int hashCode() {
    return id.hashCode();
}

...
  @Override
    public boolean equals(Object other) {
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof GenericDictionary))return false;
        GenericDictionary otherMyClass = (GenericDictionary) other;
        if(this.name == otherMyClass.name) {
            return true;
        } else {
            return false;
        }
    }

But it dosnt apply it. It use object.equals() method instead of mine

A: It looks like your problem is in String comparison :
if(this.name == otherMyClass.name)

Change it to :
if(this.name.equals(otherMyClass.name))


text:
Q: Tensorflow 2.4 doesn't work despite my cpu having AVX support I am running Ubuntu 20.04.1 LTS/tf version 2.4.0, and I am not able to run the tensorflow library, because it always results in an error
This is the only line that I put in
import tensorflow as tf
This is the error it gives out
Illegal instruction (core dumped)
These are the processor specs
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 58
model name  : Intel(R) Core(TM) i5-3437U CPU @ 1.90GHz
stepping    : 9
microcode   : 0x21
cpu MHz     : 842.451
cache size  : 3072 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm cpuid_fault epb pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts md_clear flush_l1d
bugs        : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs itlb_multihit srbds
bogomips    : 4789.04
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

If more information will be needed I will provide it.

A: I have the same problem running the tf version 2.4.0 in Ubuntu 18.04.4 LTS. I have been looking for a solution but I didn't find it yet so, for now, I am using the previous version which works for me.
pip uninstall tensorflow
pip install tensorflow==2.3.1

A: It should be fixed now in 2.4.1


text:
Q: "suggested edits pending approval" notification should be hidden if you can't review edits Today I have reviewed 20 edits, so I cannot review any more. However, that tempting little badge next to the "review" link in the top-right corner continues to update and be visible, which is somewhat irritating.
Can this be hidden from view if the user cannot review any further? Otherwise, it's a bit of a distraction :)


text:
Q: Handling manual inputs in ssh script I am accessing a remote machine using ssh and have written a simple bash script on my host pc to copy files from the remote computer to the host.
which is simply:  scp remote@ip:/path/to/file/ destination
But I get this promt everytime to input the password for the remote machine and am therefore not able to run this script while I am away from the computer.
Is there any way around this difficulty. for example, I do not have to type the password but it can access it from some file available in host directory automatically.
Thanks.


text:
Q: tkinter scrollbar (frame/canvas) in application that create SubFrames I have researched and tested a number of solutions on stackoverflow and other sites but I cannot get a scrollbar to work with my application.
I'm looking for a scrollbar capable of scrolling the SubFrame group that my application creates. I also need to delimit a minimum window height, and that this window can be extended, but without breaking the scrollbar.
Thank you in advance to all who will help me.
I admit not having understood which should go above the other, the Canvas or the Frame.
Here is a piece of code, with all the graphical widgets to visualize the scrollbar effect :
import tkinter as tk
from tkinter import ttk

class FrameStack(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.subframes = []

        self.topFrame = tk.Frame(root)
        self.topFrame.pack(side="top", fill="x")

        self.groupOfFrames = tk.Frame(root)
        self.groupOfFrames.pack(side="top", fill="both", expand=True, pady=(32,0))

        self.scrollbar = tk.Scrollbar(self.groupOfFrames, orient="vertical")
        self.scrollbar.pack(side="right",fill="y")

        #self.canvas = tk.Canvas(self.groupOfFrames, yscrollcommand=self.scrollbar.set)
        #self.canvas.pack()
        #self.canvas_window = self.canvas.create_window(0, 0, anchor="nw", window=self.groupOfFrames)

        self.create_widget()

    def create_widget(self):
        tk.Label(self.topFrame, text="BUS").grid(row=0, column=0)
        tk.Label(self.topFrame, text="IP").grid(row=1, column=0)
        tk.Label(self.topFrame, text="REG").grid(row=2, column=0)
        tk.Label(self.topFrame, text="SIZE").grid(row=3, column=0)

        self.combobox_bus = ttk.Combobox(self.topFrame, values=list(dic.keys()), width=40, justify='center', state="readonly")
        self.combobox_bus.bind('<<ComboboxSelected>>', self.getUpdateDataIP)
        self.combobox_bus.grid(row=0, column=1, sticky="nsew")

        self.combobox_ip = ttk.Combobox(self.topFrame, justify='center', width=40, state="readonly")
        self.combobox_ip.bind('<<ComboboxSelected>>', self.getUpdateDataReg)
        self.combobox_ip.grid(row=1, column=1, sticky="nsew")

        self.button_read = tk.Button(self.topFrame, text="Read", command=self.read)
        self.button_write = tk.Button(self.topFrame, text="Write", command=self.write)
        self.button_read.grid(row=0, column=2, columnspan=2, sticky="nsew")
        self.button_write.grid(row=1, column=2, columnspan=2, sticky="nsew")

        self.button_hsid = tk.Button(self.topFrame, text="HSID")
        self.button_hsid.grid(row=0, column=4, columnspan=2, sticky="nsew")

        self.button_add = tk.Button(self.topFrame, text="+", command=self.add_frame)
        self.button_add.grid(row=1, column=4, columnspan=2, sticky="nsew")

        self.combobox_reg_dl = ttk.Combobox(self.topFrame, width=40, justify='center', state="readonly")
        self.combobox_reg_dl.bind('<<ComboboxSelected>>', self.getUpdateDisplayReg)
        self.combobox_reg_dl.grid(row=2, column=1, sticky="nsew")

        self.button_dump = tk.Button(self.topFrame, text="Dump", command=self.dump)
        self.button_load = tk.Button(self.topFrame, text="Load", command=self.load)
        self.button_dump.grid(row=2, column=2, columnspan=2, sticky="nsew")
        self.button_load.grid(row=2, column=4, columnspan=2, sticky="nsew")

        self.select_size = tk.StringVar()
        self.select_size.set("0")
        self.entry_size = tk.Entry(self.topFrame, textvariable=self.select_size, justify='center')
        self.entry_size.grid(row=3, column=1, sticky="nsew")
        tk.Scale(self.topFrame, from_=0, to=1024, variable=self.select_size)

        self.select_read_size = tk.IntVar()
        self.select_read_size.set(8)
        self.radio_8 = tk.Radiobutton(self.topFrame, text=" 8", variable=self.select_read_size, value=8)
        self.radio_16 = tk.Radiobutton(self.topFrame, text="16", variable=self.select_read_size, value=16)
        self.radio_32 = tk.Radiobutton(self.topFrame, text="32", variable=self.select_read_size, value=32)
        self.radio_64 = tk.Radiobutton(self.topFrame, text="64", variable=self.select_read_size, value=64)
        self.radio_8.grid(row=3, column=2)
        self.radio_16.grid(row=3, column=3)
        self.radio_32.grid(row=3, column=4)
        self.radio_64.grid(row=3, column=5)

    def getUpdateDataIP(self, event):
        self.combobox_ip['values'] = list(dic[self.combobox_bus.get()].keys())
        self.combobox_ip.set('')
        self.combobox_reg_dl['values'] = ['']
        self.combobox_reg_dl.set('')
        for f in self.subframes:
            f.combobox_reg_rw['values'] = ['']
            f.combobox_reg_rw.set('')

    def getUpdateDataReg(self, event):
        self.combobox_reg_dl['values'] = list(dic[self.combobox_bus.get()][self.combobox_ip.get()].keys())
        self.combobox_reg_dl.set('')
        for f in self.subframes:
            f.combobox_reg_rw['values'] = list(dic[self.combobox_bus.get()][self.combobox_ip.get()].keys())
            f.combobox_reg_rw.set('')

    def getUpdateDisplayReg(self, event):
        self.combobox_reg_dl.set(self.combobox_reg_dl.get()+" ("+dic[self.combobox_bus.get()][self.combobox_ip.get()][self.combobox_reg_dl.get()]+")")

    def delete_frame(self, frame):
        self.subframes.remove(frame)
        frame.destroy()

    def add_frame(self):
        f = SubFrame(parent=self.groupOfFrames, controller=self)
        if self.combobox_bus.get()!="" and self.combobox_ip.get()!="":
            f.combobox_reg_rw['values'] = list(dic[self.combobox_bus.get()][self.combobox_ip.get()].keys())
        self.subframes.append(f)
        f.pack(side="top", fill="x", pady=(0,5))

    def read(self):
        pass

    def write(self):
        pass

    def dump(self):
        pass

    def load(self):
        pass

class SubFrame(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.parent = parent
        self.controller = controller
        self.create_widget()

    def create_widget(self):
        self.combobox_reg_rw = ttk.Combobox(self, width=47, justify='center', state="readonly")
        self.combobox_reg_rw.bind('<<ComboboxSelected>>', self.getUpdateDisplayReg)
        self.select_val = tk.StringVar()
        self.entry_value = tk.Entry(self, bd=1.5, width=20, textvariable=self.select_val, justify='center')
        self.button_write = tk.Button(self, text="Write", command=self.write)
        self.button_read = tk.Button(self, text="Read", command=self.read)
        self.button_help = tk.Button(self, text="?", command=self.help)
        self.button_remove = tk.Button(self, text="-", command=self.remove)

        self.combobox_reg_rw.grid(row=0, column=0, columnspan=2, sticky="ew")
        self.entry_value.grid(row=0, column=2, columnspan=2, sticky="ew")
        self.button_write.grid(row=1, column=0, sticky="ew")
        self.button_read.grid(row=1, column=1, sticky="ew")
        self.button_help.grid(row=1, column=2, sticky="nsew")
        self.button_remove.grid(row=1, column=3, sticky="nsew")

    def remove(self):
        self.controller.delete_frame(self)

    def getUpdateDisplayReg(self, event):
        self.combobox_reg_rw.set(self.combobox_reg_rw.get()+" ("+dic[self.controller.combobox_bus.get()][self.controller.combobox_ip.get()][self.combobox_reg_rw.get()]+")")

    def write(self):
        print(self.entry_value.get())

    def read(self):
        print(self.combobox_reg_rw.get())

    def help(self):
        pass

if __name__ == "__main__":
    #dic = extractor.main()

    dic = {'1': {'1.1': {'1.1.1': 'A', '1.1.2': 'B'}, '1.2': {'1.2.1': 'C', '1.2.2': 'D'}}, '2': {'2.1': {'2.1.1': 'E', '2.2.2': 'F'}, '2.2': {'2.2.1': 'G', '2.2.2': 'H'}}}

    root = tk.Tk()
    root.title("XXXXXX")
    root.resizable(False, True)

    fs = FrameStack(root)
    fs.pack(fill="both", expand=True)
    root.mainloop()

A: It is the canvas that has the ability to scroll, so your self.groupOfFrames needs to go inside the canvas. And since you want the scrollbar and canvas to appear as a single complex object, they should go in a frame.
You need to make sure that when the window is resized, the frame inside the canvas is resized as well. And you also need to make sure that when you add something to self.groupOfFrames you also update the scrollregion. These can be done by binding to the <Configure> event of each widget.
Thus, I would create the FrameStack like the following. Please note that self.topFrame and self.bottomFrame are children of self rather than root. That is a mistake I didn't catch in the code I gave you in your previous question.
class FrameStack(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.subframes = []
        self.topFrame = tk.Frame(self)
        self.bottomFrame = tk.Frame(self)

        self.topFrame.pack(side="top", fill="x")
        self.bottomFrame.pack(side="bottom", fill="both", expand=True)

        self.canvas = tk.Canvas(self.bottomFrame, bd=0)
        vsb = tk.Scrollbar(self.bottomFrame, command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=vsb.set)

        vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)

        self.groupOfFrames = tk.Frame(self.canvas)
        self.canvas.create_window(0, 0, anchor="nw", window=self.groupOfFrames, tags=("inner",))

        self.canvas.bind("<Configure>", self._resize_inner_frame)
        self.groupOfFrames.bind("<Configure>", self._reset_scrollregion)

    def _reset_scrollregion(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def _resize_inner_frame(self, event):
        self.canvas.itemconfig("inner", width=event.width)


text:
Q: Sequelize connection to postgres refused on ubuntu 18.04 I deployed my nodejs 10.16.3 app to ubuntu 18.04 from my win10 PC development. After starting the app with pm2 start /ebs/myapp/index.js on ubuntu, there is an error about sequelize (5.19.1) database connection:
$cat index-error.log
Unable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5433
    at connection.connect.err (/ebs/myapp/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:170:24)
    at Connection.connectingErrorHandler (/ebs/myapp/node_modules/pg/lib/client.js:174:14)
    at Connection.emit (events.js:198:13)
    at Socket.reportStreamError (/ebs/myapp/node_modules/pg/lib/connection.js:72:10)
    at Socket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  name: 'SequelizeConnectionRefusedError',
  parent:
   { Error: connect ECONNREFUSED 127.0.0.1:5433
       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
     errno: 'ECONNREFUSED',
     code: 'ECONNREFUSED',
     syscall: 'connect',
     address: '127.0.0.1',
     port: 5433 },
  original:
   { Error: connect ECONNREFUSED 127.0.0.1:5433
       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
     errno: 'ECONNREFUSED',
     code: 'ECONNREFUSED',
     syscall: 'connect',
     address: '127.0.0.1',
     port: 5433 } }

The postgres (11.5) is running on the same host and I can access it via command line with success.
pm2 log file also indicates that the nodejs app is listening on port 3000. This app front is a nginx reverse proxy which likely has nothing to do with this error.
Here is the db connection string:
const Sql = require("sequelize");
const db = new Sql('mydb', 'postgres', `${process.env.DB_PASSWORD}`, {
    host: 'localhost',
    dialect: 'postgres',
    port:5433,
} );

Why the sequelize connection is refused?
Update: postgresql log:
$ cat postgresql-11-main.log
2019-10-07 20:24:27.712 UTC [665] postgres@emps ERROR:  syntax error at or near "psql" at character 1
2019-10-07 20:24:27.712 UTC [665] postgres@emps STATEMENT:  psql
        ;
ubuntu@:/var/log/postgresql$ cat postgresql-11-main.log.1
2019-10-04 09:10:49.214 UTC [22809] LOG:  received fast shutdown request
2019-10-04 09:10:49.221 UTC [22809] LOG:  aborting any active transactions
2019-10-04 09:10:49.292 UTC [22809] LOG:  background worker "logical replication launcher" (PID 22816) exited with exit code 1
2019-10-04 09:10:49.298 UTC [22811] LOG:  shutting down
2019-10-04 09:10:49.435 UTC [22809] LOG:  database system is shut down
2019-10-04 09:11:11.561 UTC [1084] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2019-10-04 09:11:11.567 UTC [1084] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2019-10-04 09:11:11.628 UTC [1096] LOG:  database system was shut down at 2019-10-04 09:10:49 UTC
2019-10-04 09:11:11.648 UTC [1084] LOG:  database system is ready to accept connections
2019-10-04 09:11:12.196 UTC [1134] [unknown]@[unknown] LOG:  incomplete startup packet
2019-10-04 09:11:17.827 UTC [1282] [unknown]@[unknown] LOG:  incomplete startup packet
2019-10-04 09:13:42.106 UTC [1084] LOG:  received fast shutdown request
2019-10-04 09:13:42.110 UTC [1084] LOG:  aborting any active transactions
2019-10-04 09:13:42.114 UTC [1084] LOG:  background worker "logical replication launcher" (PID 1102) exited with exit code 1
2019-10-04 09:13:42.115 UTC [1097] LOG:  shutting down
2019-10-04 09:13:42.138 UTC [1084] LOG:  database system is shut down
2019-10-04 09:13:46.533 UTC [3040] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2019-10-04 09:13:46.535 UTC [3040] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2019-10-04 09:13:46.566 UTC [3041] LOG:  database system was shut down at 2019-10-04 09:13:42 UTC
2019-10-04 09:13:46.577 UTC [3040] LOG:  database system is ready to accept connections
2019-10-04 09:13:47.110 UTC [3048] [unknown]@[unknown] LOG:  incomplete startup packet
2019-10-04 09:13:52.713 UTC [3082] [unknown]@[unknown] LOG:  incomplete startup packet

A: The logs of your PostgreSQL server say that it is launched at the default port 5432. But in your app you'r trying to connect to 5433.
Try this connection instead:
const Sql = require("sequelize");
const db = new Sql('mydb', 'postgres', `${process.env.DB_PASSWORD}`, {
    host: 'localhost',
    dialect: 'postgres',
    port: 5432, // instead of 5433
} );