问:
Nested Class factory with tkinter
I'm trying to build a script for import in my future projects.
That Script should create some tk.Frames in a tk.Frame and let me edit the created ones in a main.

I think, the best way to get there is to create a Holder_frame class and put some nested classes in.
so I could call them in my main with Holder_frame.F1.
I tried a lot of code and I ended up here making me an account.
Anyway here is where Im at:

```<code>import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    Names = []
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        frame_names = Holder_frame.Names
        for i in range(0,frames):
            frame_names.append("F"+str(i+1))
        print(frame_names)
        Holder_frame.factory()
    def factory():
        print(Holder_frame.Names)
        print(type(BaseClass))
        for idex,i in enumerate (Holder_frame.Names):
            print(i)
            class NestedClass(BaseClass):
                pass

            NestedClass.__name__ = i
            NestedClass.__qualname__ = i

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        Holder_frame.F1.tkraise()
    def raise2():
        Holder_frame.F2.tkraise()

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)

    root.mainloop()
</code>```

Everything works fine, till I try to call a Frame.
(AttributeError 'Holder_frame' object has no attribute 'F1')
I think my problem is the structure but need some help to solve it.

Any suggestions?

答:
If I'm getting it right I think you mean to have some sort of a Base class that has some configuration which a set of frames have in common like for example you want to have 10 frames of 300x400 geometry and of a brown background in common and later having another set of frames with a different configuration, which can be accessed in an organised way. Then I would say you have an interesting way but I would rather use a list or a dictionary anyway.

Here are some approaches to achieve this goal.

Approach 1

In this approach, I've created a function that returns a dictionary with all the frames created and contained in it like in format ({..., 'F20': tkinter.frame, ...})

import tkinter as tk

def get_base_frames(num, master, cnf={}, **kw):
    """
    Create list of frames with common configuration options.

    Args:
        num (int): Number of frames to be created.
        master (tk.Misc): Takes tkinter widget or window as a parent for the frames.
        cnf (dict): configuration options for all the frames.
        kw: configuration options for all the frames.

    Return:
        Dictionary of frames ({..., 'F20': tkinter.frame, ...}).
    """
    return {f'F{n+1}': tk.Frame(master, cnf=cnf, **kw) for n in range(num)}

if __name__ == "__main__":
    root = tk.Tk()
    frame_holder = get_base_frames(10, root, width=50, height=50, bg='brown')

    # Frames can be accessed through their names like so.
    print(frame_holder.get('F1'))
```

<hr>

<h3>Approach 2</h3>

<p>Here I've used class and objects. Where I made this class <code>Frames</code> though you can name it anything you want. I also added some important method like <code>cget()</code> and <code>configure()</code>, through these methods once get a value to an option and configure options for all the frames respectively. <em>There are more useful methods like <code>bind()</code> and <code>bind_all()</code> if you need those just modify this class as per your need.</em></p>

<pre class="lang-py prettyprint-override"><code>import tkinter as tk

class Frames(object):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__()
        num = cnf.pop('num', kw.pop('num', 0))
        for n in range(num):
            self.__setattr__(f'F{n+1}', tk.Frame(master, cnf=cnf, **kw))

    def configure(self, cnf={}, **kw):
        """Configure resources of a widget.

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """
        for frame in self.__dict__:
            frame = self.__getattribute__(frame)
            if isinstance(frame, tk.Frame):
                if not cnf and not kw:
                    return frame.configure()
                frame.configure(cnf=cnf, **kw)
    config = configure

    def cget(self, key):
        """Return the resource value for a KEY given as string."""
        for frame in self.__dict__:
            frame = self.__getattribute__(frame)
            if isinstance(frame, tk.Frame):
                return frame.cget(key)
    __getitem__ = cget

if __name__ == "__main__":
    root = tk.Tk()
    frame_holder = Frames(root, num=10, width=10,
                          bd=2, relief='sunken', bg='yellow')

    # Frames can be accessed through their naems like so.
    print(frame_holder.F4)
    print(frame_holder['bg'])
    frame_holder.config(bg='blue')
    print(frame_holder['bg'])
</code>```

Approach 3

If you want to have differently configured frames contained in one class, where all those frames have some method in common or some attribute in common.

import tkinter as tk

class BaseFrame(tk.Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master=master, cnf={}, **kw)

    def common_function(self):
        """This function will be common in every
        frame created through this class."""
        # Do something...

class FrameHolder(object):
    def __init__(self, master=None, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        num = kw.pop('num', len(kw))

        for n in range(num):
            name = f'F{n+1}'
            cnf = kw.get(name)
            self.__setattr__(name, BaseFrame(master, cnf))

if __name__ == "__main__":
    root = tk.Tk()

    holder = FrameHolder(root,
                    F1=dict(width=30, height=40, bg='black'),
                    F2=dict(width=50, height=10, bg='green'),
                    F3=dict(width=300, height=350, bg='blue'),
                    F4=dict(width=100, height=100, bg='yellow'),
                    )
    print(holder.F1)
    print(holder.__dict__)
```

<hr>

<h3>Approach 4</h3>

<p><em>This is the approach that OP is trying to achieve.</em></p>

<pre class="lang-py prettyprint-override"><code>import tkinter as tk

class BaseClass(tk.Frame):
    def __init__(self, master, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        cnf = [(i, kw.pop(i, None))
               for i in ('pack', 'grid', 'place') if i in kw]
        tk.Frame.__init__(self, master, **kw)
        self.master = master

        if cnf:
            self.__getattribute__(cnf[-1][0])(cnf=cnf[-1][1])

class Container(tk.Frame):
    """Container class which can contain tkinter widgets.
    Geometry (pack, grid, place) configuration of widgets
    can also be passed as an argument.

    For Example:-

    >>> Container(root, widget=tk.Button,
              B5=dict(width=30, height=40, bg='black',
                      fg='white', pack=(), text='Button1'),
              B6=dict(width=50, height=10, bg='green', text='Button2',
                      place=dict(relx=0.5, rely=1, anchor='s')))
    """
    BaseClass = BaseClass

    def __init__(self, master=None, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        wid = kw.pop('widget', tk.Frame)
        for name, cnf in kw.items():
            geo = [(i, cnf.pop(i, None))
                   for i in ('pack', 'grid', 'place') if i in cnf]
            setattr(Container, name, wid(master, cnf))
            if geo:
                manager, cnf2 = geo[-1]
                widget = getattr(Container, name)
                getattr(widget, manager)(cnf=cnf2)

if __name__ == "__main__":
    root = tk.Tk()

    Container(root, widget=Container.BaseClass,
              F1=dict(width=30, height=40, bg='black', relief='sunken',
                      pack=dict(ipadx=10, ipady=10, fill='both'), bd=5),
              F2=dict(width=50, height=10, bg='green',
                      pack=dict(ipadx=10, ipady=10, fill='both')),
              )

    Container(root, widget=tk.Button,
              B5=dict(width=30, height=40, bg='black',
                      fg='white', pack={}, text='Button1'),
              B6=dict(width=50, height=10, bg='green', text='Button2',
                      place=dict(relx=0.5, rely=1, anchor='s')),
              )

    print(Container.__dict__)
    root.mainloop()
</code>```

A lot can be done and can be modified according to one's needs, these are just some approaches that I think will work very well to automate and keep a set of frames in shape and together.

There can be multiple ways to do this or maybe something better and efficient than these, feel free to give suggestions and share something new.

Title: Nested Class factory with tkinter

Body:
I'm trying to build a script for import in my future projects.
That Script should create some tk.Frames in a tk.Frame and let me edit the created ones in a main.

I think, the best way to get there is to create a Holder_frame class and put some nested classes in.
so I could call them in my main with Holder_frame.F1.
I tried a lot of code and I ended up here making me an account.
Anyway here is where Im at:

import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    Names = []
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        frame_names = Holder_frame.Names
        for i in range(0,frames):
            frame_names.append("F"+str(i+1))
        print(frame_names)
        Holder_frame.factory()
    def factory():
        print(Holder_frame.Names)
        print(type(BaseClass))
        for idex,i in enumerate (Holder_frame.Names):
            print(i)
            class NestedClass(BaseClass):
                pass

            NestedClass.__name__ = i
            NestedClass.__qualname__ = i

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        Holder_frame.F1.tkraise()
    def raise2():
        Holder_frame.F2.tkraise()

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)

    root.mainloop()

Everything works fine, till I try to call a Frame.
(AttributeError 'Holder_frame' object has no attribute 'F1')
I think my problem is the structure but need some help to solve it.

Any suggestions?

Body:
If I'm getting it right I think you mean to have some sort of a Base class that has some configuration which a set of frames have in common like for example you want to have 10 frames of 300x400 geometry and of a brown background in common and later having another set of frames with a different configuration, which can be accessed in an organised way. Then I would say you have an interesting way but I would rather use a list or a dictionary anyway.

Here are some approaches to achieve this goal.

Approach 1

In this approach, I've created a function that returns a dictionary with all the frames created and contained in it like in format ({..., 'F20': tkinter.frame, ...})

import tkinter as tk

def get_base_frames(num, master, cnf={}, **kw):
    """
    Create list of frames with common configuration options.

    Args:
        num (int): Number of frames to be created.
        master (tk.Misc): Takes tkinter widget or window as a parent for the frames.
        cnf (dict): configuration options for all the frames.
        kw: configuration options for all the frames.

    Return:
        Dictionary of frames ({..., 'F20': tkinter.frame, ...}).
    """
    return {f'F{n+1}': tk.Frame(master, cnf=cnf, **kw) for n in range(num)}

if __name__ == "__main__":
    root = tk.Tk()
    frame_holder = get_base_frames(10, root, width=50, height=50, bg='brown')

    # Frames can be accessed through their names like so.
    print(frame_holder.get('F1'))

Approach 2

Here I've used class and objects. Where I made this class Frames though you can name it anything you want. I also added some important method like cget() and configure(), through these methods once get a value to an option and configure options for all the frames respectively. There are more useful methods like bind() and bind_all() if you need those just modify this class as per your need.

import tkinter as tk

class Frames(object):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__()
        num = cnf.pop('num', kw.pop('num', 0))
        for n in range(num):
            self.__setattr__(f'F{n+1}', tk.Frame(master, cnf=cnf, **kw))

    def configure(self, cnf={}, **kw):
        """Configure resources of a widget.

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """
        for frame in self.__dict__:
            frame = self.__getattribute__(frame)
            if isinstance(frame, tk.Frame):
                if not cnf and not kw:
                    return frame.configure()
                frame.configure(cnf=cnf, **kw)
    config = configure

    def cget(self, key):
        """Return the resource value for a KEY given as string."""
        for frame in self.__dict__:
            frame = self.__getattribute__(frame)
            if isinstance(frame, tk.Frame):
                return frame.cget(key)
    __getitem__ = cget

if __name__ == "__main__":
    root = tk.Tk()
    frame_holder = Frames(root, num=10, width=10,
                          bd=2, relief='sunken', bg='yellow')

    # Frames can be accessed through their naems like so.
    print(frame_holder.F4)
    print(frame_holder['bg'])
    frame_holder.config(bg='blue')
    print(frame_holder['bg'])

Approach 3

If you want to have differently configured frames contained in one class, where all those frames have some method in common or some attribute in common.

import tkinter as tk

class BaseFrame(tk.Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master=master, cnf={}, **kw)

    def common_function(self):
        """This function will be common in every
        frame created through this class."""
        # Do something...

class FrameHolder(object):
    def __init__(self, master=None, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        num = kw.pop('num', len(kw))

        for n in range(num):
            name = f'F{n+1}'
            cnf = kw.get(name)
            self.__setattr__(name, BaseFrame(master, cnf))

if __name__ == "__main__":
    root = tk.Tk()

    holder = FrameHolder(root,
                    F1=dict(width=30, height=40, bg='black'),
                    F2=dict(width=50, height=10, bg='green'),
                    F3=dict(width=300, height=350, bg='blue'),
                    F4=dict(width=100, height=100, bg='yellow'),
                    )
    print(holder.F1)
    print(holder.__dict__)

Approach 4

This is the approach that OP is trying to achieve.

import tkinter as tk

class BaseClass(tk.Frame):
    def __init__(self, master, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        cnf = [(i, kw.pop(i, None))
               for i in ('pack', 'grid', 'place') if i in kw]
        tk.Frame.__init__(self, master, **kw)
        self.master = master

        if cnf:
            self.__getattribute__(cnf[-1][0])(cnf=cnf[-1][1])

class Container(tk.Frame):
    """Container class which can contain tkinter widgets.
    Geometry (pack, grid, place) configuration of widgets
    can also be passed as an argument.

    For Example:-

    >>> Container(root, widget=tk.Button,
              B5=dict(width=30, height=40, bg='black',
                      fg='white', pack=(), text='Button1'),
              B6=dict(width=50, height=10, bg='green', text='Button2',
                      place=dict(relx=0.5, rely=1, anchor='s')))
    """
    BaseClass = BaseClass

    def __init__(self, master=None, cnf={}, **kw):
        kw = tk._cnfmerge((cnf, kw))
        wid = kw.pop('widget', tk.Frame)
        for name, cnf in kw.items():
            geo = [(i, cnf.pop(i, None))
                   for i in ('pack', 'grid', 'place') if i in cnf]
            setattr(Container, name, wid(master, cnf))
            if geo:
                manager, cnf2 = geo[-1]
                widget = getattr(Container, name)
                getattr(widget, manager)(cnf=cnf2)

if __name__ == "__main__":
    root = tk.Tk()

    Container(root, widget=Container.BaseClass,
              F1=dict(width=30, height=40, bg='black', relief='sunken',
                      pack=dict(ipadx=10, ipady=10, fill='both'), bd=5),
              F2=dict(width=50, height=10, bg='green',
                      pack=dict(ipadx=10, ipady=10, fill='both')),
              )

    Container(root, widget=tk.Button,
              B5=dict(width=30, height=40, bg='black',
                      fg='white', pack={}, text='Button1'),
              B6=dict(width=50, height=10, bg='green', text='Button2',
                      place=dict(relx=0.5, rely=1, anchor='s')),
              )

    print(Container.__dict__)
    root.mainloop()

A lot can be done and can be modified according to one's needs, these are just some approaches that I think will work very well to automate and keep a set of frames in shape and together.

There can be multiple ways to do this or maybe something better and efficient than these, feel free to give suggestions and share something new.


来源: stackexchange

问:
What is the default font family of a Flutter app?
How I can retrieve the current font family name for flutter app and what is the default one ?

I have tried

```<code>Theme.of(context).textTheme.
</code>```

and

```<code>Theme.of(context).
</code>```

but there is no attribute for the font family.

答:
The default fonts depend on the operating system:

Android uses the Roboto font.

iOS uses the San Francisco font (specifically, SF Pro Display).

ContentLicense: CC BY-SA 4.0

Body:
How I can retrieve the current font family name for flutter app and what is the default one ?

I have tried

Theme.of(context).textTheme.

and

Theme.of(context).

but there is no attribute for the font family.


问:
Error while loading data from BigQuery table to Dataproc cluster
I'm new to Dataproc and PySpark and facing certain issues while integrating BigQuery table to Dataproc cluster via Jupyter Lab API. Below is the code that I used for loading BigQuery table to the Dataproc cluster through Jupyter Notebook API but I am getting an error while loading the table

from pyspark.sql import SparkSession

 SparkSession.builder.appName('Jupyter BigQuery Storage').config(
  'spark.jars', 'gs://spark-lib/bigquery/spark-bigquery-latest.jar').getOrCreate()

df=spark.read.format("com.google.cloud.spark.bigquery").option(
  "table", "publicdata.samples.shakespeare").load()

df.printSchema()
```

<p>Below, is the error I'm getting</p>

```Py4JJavaErrorTraceback (most recent call last)
<ipython-input-17-789ad67053e5> in <module>()
      1 table = "publicdata.samples.shakespeare"
----> 2 df = spark.read.format("com.google.cloud.spark.bigquery").option("table",table).load()
      3 df.printSchema()

/usr/lib/spark/python/pyspark/sql/readwriter.pyc in load(self, path, format, schema, **options)
    170             return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))
    171         else:
--> 172             return self._df(self._jreader.load())
    173
    174     @since(1.4)

/opt/conda/anaconda/lib/python2.7/site-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

/usr/lib/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/opt/conda/anaconda/lib/python2.7/site-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o254.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.google.cloud.spark.bigquery. Please find packages at http://spark.apache.org/third-party-projects.html
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:639)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:190)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:164)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.google.cloud.spark.bigquery.DefaultSource
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:622)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:622)
    at scala.util.Try$.apply(Try.scala:192)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:622)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:622)
    at scala.util.Try.orElse(Try.scala:84)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:622)
    ... 13 more```

</code>```

答:
Please assign the SparkSession.builder result to a variable:

```<code>spark = SparkSession.builder\
  .appName('Jupyter BigQuery Storage')\
  .config('spark.jars', 'gs://spark-lib/bigquery/spark-bigquery-latest.jar')\
  .getOrCreate()
</code>```

Also, the reference to the public datasets is  bigquery-public-data, so please change the reading to

```<code>df = spark.read.format("com.google.cloud.spark.bigquery")\
  .option("table", "bigquery-public-data.samples.shakespeare")\
  .load()
</code>```

Body:
I'm new to Dataproc and PySpark and facing certain issues while integrating BigQuery table to Dataproc cluster via Jupyter Lab API. Below is the code that I used for loading BigQuery table to the Dataproc cluster through Jupyter Notebook API but I am getting an error while loading the table

from pyspark.sql import SparkSession

 SparkSession.builder.appName('Jupyter BigQuery Storage').config(
  'spark.jars', 'gs://spark-lib/bigquery/spark-bigquery-latest.jar').getOrCreate()

df=spark.read.format("com.google.cloud.spark.bigquery").option(
  "table", "publicdata.samples.shakespeare").load()

df.printSchema()

Below, is the error I'm getting

Py4JJavaErrorTraceback (most recent call last)
<ipython-input-17-789ad67053e5> in <module>()
      1 table = "publicdata.samples.shakespeare"
----> 2 df = spark.read.format("com.google.cloud.spark.bigquery").option("table",table).load()
      3 df.printSchema()

/usr/lib/spark/python/pyspark/sql/readwriter.pyc in load(self, path, format, schema, **options)
    170             return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))
    171         else:
--> 172             return self._df(self._jreader.load())
    173
    174     @since(1.4)

/opt/conda/anaconda/lib/python2.7/site-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

/usr/lib/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/opt/conda/anaconda/lib/python2.7/site-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o254.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.google.cloud.spark.bigquery. Please find packages at http://spark.apache.org/third-party-projects.html
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:639)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:190)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:164)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.google.cloud.spark.bigquery.DefaultSource
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:622)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:622)
    at scala.util.Try$.apply(Try.scala:192)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:622)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:622)
    at scala.util.Try.orElse(Try.scala:84)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:622)
    ... 13 more```

Body:
Please assign the SparkSession.builder result to a variable:

spark = SparkSession.builder\
  .appName('Jupyter BigQuery Storage')\
  .config('spark.jars', 'gs://spark-lib/bigquery/spark-bigquery-latest.jar')\
  .getOrCreate()

Also, the reference to the public datasets is  bigquery-public-data, so please change the reading to

df = spark.read.format("com.google.cloud.spark.bigquery")\
  .option("table", "bigquery-public-data.samples.shakespeare")\
  .load()


问:
Java "The blank final field may not have been initialized" Anonymous Interface vs Lambda Expression
I've recently been encountering the error message "The blank final field obj may not have been initialized".

Usually this is the case if you try to refer to a field that is possibly not assigned to a value yet. Example class:

```<code>public class Foo {
    private final Object obj;
    public Foo() {
        obj.toString(); // error           (1)
        obj = new Object();
        obj.toString(); // just fine       (2)
    }
}
</code>```

I use Eclipse. In the line (1) I get the error, in the line (2) everything works. So far that makes sense.

Next I try to access obj within an anonymous interface I create inside the constructor.

```<code>public class Foo {
    private Object obj;
    public Foo() {
        Runnable run = new Runnable() {
            public void run() {
                obj.toString(); // works fine
            }
        };
        obj = new Object();
        obj.toString(); // works too
    }
}
</code>```

This works, too, since I do not access obj in the moment I create the interface. I could also pass my instance to somewhere else, then initialize the object obj and then run my interface. (However it would be appropriate to check for null before using it). Still makes sense.

But now I shorten the creation of my Runnable instance to the burger-arrow version by using a lambda expression:

```<code>public class Foo {
    private final Object obj;
    public Foo() {
        Runnable run = () -> {
            obj.toString(); // error
        };
        obj = new Object();
        obj.toString(); // works again
    }
}
</code>```

And here is where I can't follow anymore. Here I get the warning again. I am aware that the compiler doesn't handle lambda expressions as usual initializations, it doesn't "replace it by the long version". However, why does this affect the fact that I do not run the code part in my run() method at creation time of the Runnable object? I am still able to do the initialization before I invoke run(). So technically it is possible not to encounter a NullPointerException here. (Though it would be better to check for null here, too. But this convention is another topic.)

What is the mistake I make? What is handled so differently about lambda that it influences my object usage the way it does?

I thank you for any further explanations.

答:
I had a similar problem:

```<code>import java.util.function.Supplier;

public class ObjectHolder {
    private final Object obj;
    public Supplier<Object> sup = () -> obj; // error

    public ObjectHolder(Object obj) {
        this.obj = obj;
    }
}
</code>```

And resolved it this way:

```<code>public Supplier<Object> sup = () -> ((ObjectHolder)this).obj;
</code>```

Neither this.obj nor ObjectHolder.this.obj worked in Eclipse (though the latter worked for the standard JDK compiler).

In your case, use this workaround, it is safe for all compilers:

```<code>((Foo)this).obj.toString();
</code>```

Another solution is to use a getter. In my example, it looks like this:

```<code>public Supplier<Object> sup = () -> getObj();

private Object getObj() {
    return obj;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've recently been encountering the error message "The blank final field obj may not have been initialized".

Usually this is the case if you try to refer to a field that is possibly not assigned to a value yet. Example class:

public class Foo {
    private final Object obj;
    public Foo() {
        obj.toString(); // error           (1)
        obj = new Object();
        obj.toString(); // just fine       (2)
    }
}

I use Eclipse. In the line (1) I get the error, in the line (2) everything works. So far that makes sense.

Next I try to access obj within an anonymous interface I create inside the constructor.

public class Foo {
    private Object obj;
    public Foo() {
        Runnable run = new Runnable() {
            public void run() {
                obj.toString(); // works fine
            }
        };
        obj = new Object();
        obj.toString(); // works too
    }
}

This works, too, since I do not access obj in the moment I create the interface. I could also pass my instance to somewhere else, then initialize the object obj and then run my interface. (However it would be appropriate to check for null before using it). Still makes sense.

But now I shorten the creation of my Runnable instance to the burger-arrow version by using a lambda expression:

public class Foo {
    private final Object obj;
    public Foo() {
        Runnable run = () -> {
            obj.toString(); // error
        };
        obj = new Object();
        obj.toString(); // works again
    }
}

And here is where I can't follow anymore. Here I get the warning again. I am aware that the compiler doesn't handle lambda expressions as usual initializations, it doesn't "replace it by the long version". However, why does this affect the fact that I do not run the code part in my run() method at creation time of the Runnable object? I am still able to do the initialization before I invoke run(). So technically it is possible not to encounter a NullPointerException here. (Though it would be better to check for null here, too. But this convention is another topic.)

What is the mistake I make? What is handled so differently about lambda that it influences my object usage the way it does?

I thank you for any further explanations.

Body:
I had a similar problem:

import java.util.function.Supplier;

public class ObjectHolder {
    private final Object obj;
    public Supplier<Object> sup = () -> obj; // error

    public ObjectHolder(Object obj) {
        this.obj = obj;
    }
}

And resolved it this way:

public Supplier<Object> sup = () -> ((ObjectHolder)this).obj;

Neither this.obj nor ObjectHolder.this.obj worked in Eclipse (though the latter worked for the standard JDK compiler).

In your case, use this workaround, it is safe for all compilers:

((Foo)this).obj.toString();

Another solution is to use a getter. In my example, it looks like this:

public Supplier<Object> sup = () -> getObj();

private Object getObj() {
    return obj;
}


问:
Converting arduino digitalRead to standard C
I'm trying to convert some arduino code to common C formatted code. I am stuck here however.

```<code>uint8_t pins[] = {13, 12, 11, 10, 8};   //PORTB (Will have 8 taken away from value to produce correct port number)
void loop() {
if(!wait){

init_pin_state(1);                      // LED ON/OFF

randomSeed(analogRead(A0));                   //
sequence[curLen] = pins[random(0,numpins)];
curLen++;
wait = true;
}
else{
init_pin_state(0)                             // Set pins to input
if(!btnDwn){                                  //
  expRd = sequence[inputCount];               // Find the value we expect from the player

  for(int i = 0; i < numpins; i++){           // Loop through the all the pins
    if(pins[i]==expRd)
      continue;                               // Ignore the correct pin
    if(digitalRead(pins[i]) == HIGH){         // Is the buttong pressed
      lastInput = pins[i];
      resetFlag = true;                       // Set the resetFlag - this means you lost
      btnDwn = true;                          // This will prevent the program from doing the same thing over and over again
    }
  }
if(PINB == (1 << (expRd-8)) && !btnDwn)        // The player pressed the right button
{
  inputTime = millis();                       //
  lastInput = expRd;
  inputCount++;                               // The user pressed a (correct) button again
  btnDwn = true;

}else{
  if(btnDwn && PINB == (0 << lastInput-8)){  // Check if the player released the button
    btnDwn = false;
    _delay_ms(20);
    if(resetFlag){                              // If this was set to true up above, you lost
      DoLoseProcess();                          // So we do the losing sequence of events
    }
    else{
      if(inputCount == curLen){                 // Has the player finished repeating the sequence
        wait = false;                           // If so, this will make the next turn the program's turn
        inputCount = 0;                         // Reset the number of times that the player has pressed a button
        _delay_ms(900);
      }
    }
  }

}
</code>```

I am trying to convert digitalRead to PIN variation with bitwise aspects. (eg PINB != 0b000000 for this case).
I have tried the above example but whenever i press the pushbutton connected to the pin the bottom if statement overides the top one. This code works in arduino though and I am unsure as to what the problem is.
Thanks for your help.

答:
For anyone that ever comes across this with the same problems.

```<code>digitalRead(pins[i]) == HIGH
</code>```

I was trying to write it as

```<code>PINB == (1 << i)
</code>```

Instead of the required

```<code>PINB == (1 << pins[i])
</code>```

It was a stupid mistake tbh

Body:
I'm trying to convert some arduino code to common C formatted code. I am stuck here however.

uint8_t pins[] = {13, 12, 11, 10, 8};   //PORTB (Will have 8 taken away from value to produce correct port number)
void loop() {
if(!wait){

init_pin_state(1);                      // LED ON/OFF

randomSeed(analogRead(A0));                   //
sequence[curLen] = pins[random(0,numpins)];
curLen++;
wait = true;
}
else{
init_pin_state(0)                             // Set pins to input
if(!btnDwn){                                  //
  expRd = sequence[inputCount];               // Find the value we expect from the player

  for(int i = 0; i < numpins; i++){           // Loop through the all the pins
    if(pins[i]==expRd)
      continue;                               // Ignore the correct pin
    if(digitalRead(pins[i]) == HIGH){         // Is the buttong pressed
      lastInput = pins[i];
      resetFlag = true;                       // Set the resetFlag - this means you lost
      btnDwn = true;                          // This will prevent the program from doing the same thing over and over again
    }
  }
if(PINB == (1 << (expRd-8)) && !btnDwn)        // The player pressed the right button
{
  inputTime = millis();                       //
  lastInput = expRd;
  inputCount++;                               // The user pressed a (correct) button again
  btnDwn = true;

}else{
  if(btnDwn && PINB == (0 << lastInput-8)){  // Check if the player released the button
    btnDwn = false;
    _delay_ms(20);
    if(resetFlag){                              // If this was set to true up above, you lost
      DoLoseProcess();                          // So we do the losing sequence of events
    }
    else{
      if(inputCount == curLen){                 // Has the player finished repeating the sequence
        wait = false;                           // If so, this will make the next turn the program's turn
        inputCount = 0;                         // Reset the number of times that the player has pressed a button
        _delay_ms(900);
      }
    }
  }

}

I am trying to convert digitalRead to PIN variation with bitwise aspects. (eg PINB != 0b000000 for this case).
I have tried the above example but whenever i press the pushbutton connected to the pin the bottom if statement overides the top one. This code works in arduino though and I am unsure as to what the problem is.
Thanks for your help.

Body:
For anyone that ever comes across this with the same problems.

digitalRead(pins[i]) == HIGH

I was trying to write it as

PINB == (1 << i)

Instead of the required

PINB == (1 << pins[i])

It was a stupid mistake tbh


问:
Is Twitter's Tweet_ID unique across twitter platform?
I'm writing a script to process and store million of tweets. The way my code works is that Tweet's ID is stored as _id for MongoDB document to make it unique across my DB.

What I observe is that Tweet ID doesn't appear to be unique and I get duplicate key error when writing tweets for different users to DB.

Documentation of snowflake (https://developer.twitter.com/en/docs/basics/twitter-ids) gives an overview how the tweet ID is generated and it appears that it should be unique across the twitter DB.

Can some confirm if the twitter's Tweet ID is actually unique across their DB?

This is how my code works:

```<code>def write_tweets_to_db(tweets):
    processed_tweets = []
    for tweet in tweets:
        processed_tweets = process_tweet(tweet)  # This is where I convert tweepy object to dict and
                                                 # set _id key to tweet ID
    for tweet in processed_tweets:
        try:
            collection.insert_one(tweet)
        except Exception as e:
            print('Error while writing tweet to DB | Error: {}'.format(e))

# Error while writing tweet to DB | Error: E11000 duplicate key error collection: [DB].[collection] index: _id_ dup key: { _id: 1235024705523863552 }

</code>```

答: Tweet IDs are indeed unique. You should always use the string variant of the ID to avoid issues with JavaScript and other languages that cannot handle large integers converting the numbers.</p>

Body:
I'm writing a script to process and store million of tweets. The way my code works is that Tweet's ID is stored as _id for MongoDB document to make it unique across my DB.

What I observe is that Tweet ID doesn't appear to be unique and I get duplicate key error when writing tweets for different users to DB.

Documentation of snowflake (https://developer.twitter.com/en/docs/basics/twitter-ids) gives an overview how the tweet ID is generated and it appears that it should be unique across the twitter DB.

Can some confirm if the twitter's Tweet ID is actually unique across their DB?

This is how my code works:

def write_tweets_to_db(tweets):
    processed_tweets = []
    for tweet in tweets:
        processed_tweets = process_tweet(tweet)  # This is where I convert tweepy object to dict and
                                                 # set _id key to tweet ID
    for tweet in processed_tweets:
        try:
            collection.insert_one(tweet)
        except Exception as e:
            print('Error while writing tweet to DB | Error: {}'.format(e))

# Error while writing tweet to DB | Error: E11000 duplicate key error collection: [DB].[collection] index: _id_ dup key: { _id: 1235024705523863552 }


问:
Increment value of array of objects redux
I need to increment quantity of item in cart if item already exists in the state array. In the reducer I got it to work but it needs to be immutable. Because of this, my component doesnt update properly.

This is the code for my reducer:

```<code>import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/types';

const initialState = [];

//Cannot mutate array in reducer

export default function(state = initialState, action){
    const { type, payload } = action;

    switch(type){
        case ADD_TO_CART:
            const newState = [...state]
            for(var i = 0; i < newState.length; i++){
                if(newState[i].item.uid === payload.item.uid){
                    newState[i].item.qty ++;
                    return [...newState];
                }
            }
            return [...state, payload];
        case REMOVE_FROM_CART:
            for(var j = 0; j < state.length; j++){
                    if(state[j].item.uid === payload.uid){
                        state[j].item.qty = 1;
                    }
            }
            return state.filter(cartItem => cartItem.item.uid !== payload.uid);

        default:
            return state;
    }
}
</code>```

I need to increment qty if item is already in the array.

答:
The issue I see is with newState[i].item.qty++;, that although you shallowly copied the array, the elements in the array still represent those of the previous state, so post incrementing it mutates the object.

To resolve this issue you should also copy each item into a new object, then update the new object reference.

The following also include a minor optimization to iterate the data once versus twice, by checking for the matching item ID as it copying the state into a new array.

```<code>let itemExists = false;
const newState = state.map(item => {
  const newItem = { ...item };
  if (newItem.item.uid === payload.item.uid) {
    itemExists = true;
    newItem.item.qty = item.qty + 1;
  }
  return newItem;
});

if (!itemExists) newState.push(payload);

return newState;
</code>```

EDIT: Alternative method

```<code>const itemIndex = state.findIndex(item => item.item.id === payload.item.id);
if (itemIndex !== -1) {
  return state.map((item, i) => ({
    ...item,
    item: {
      ...item.item,
      qty: item.item.qty + (itemIndex === i ? 1 : 0),
    }
  }));
} else {
  return [...state, payload];
}
</code>```

Body:
I need to increment quantity of item in cart if item already exists in the state array. In the reducer I got it to work but it needs to be immutable. Because of this, my component doesnt update properly.

This is the code for my reducer:

import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/types';

const initialState = [];

//Cannot mutate array in reducer

export default function(state = initialState, action){
    const { type, payload } = action;

    switch(type){
        case ADD_TO_CART:
            const newState = [...state]
            for(var i = 0; i < newState.length; i++){
                if(newState[i].item.uid === payload.item.uid){
                    newState[i].item.qty ++;
                    return [...newState];
                }
            }
            return [...state, payload];
        case REMOVE_FROM_CART:
            for(var j = 0; j < state.length; j++){
                    if(state[j].item.uid === payload.uid){
                        state[j].item.qty = 1;
                    }
            }
            return state.filter(cartItem => cartItem.item.uid !== payload.uid);

        default:
            return state;
    }
}

I need to increment qty if item is already in the array.

Body:
The issue I see is with newState[i].item.qty++;, that although you shallowly copied the array, the elements in the array still represent those of the previous state, so post incrementing it mutates the object.

To resolve this issue you should also copy each item into a new object, then update the new object reference.

The following also include a minor optimization to iterate the data once versus twice, by checking for the matching item ID as it copying the state into a new array.

let itemExists = false;
const newState = state.map(item => {
  const newItem = { ...item };
  if (newItem.item.uid === payload.item.uid) {
    itemExists = true;
    newItem.item.qty = item.qty + 1;
  }
  return newItem;
});

if (!itemExists) newState.push(payload);

return newState;

EDIT: Alternative method

const itemIndex = state.findIndex(item => item.item.id === payload.item.id);
if (itemIndex !== -1) {
  return state.map((item, i) => ({
    ...item,
    item: {
      ...item.item,
      qty: item.item.qty + (itemIndex === i ? 1 : 0),
    }
  }));
} else {
  return [...state, payload];
}


问:
How do I match numbers and create 2-dimensional array?
I have an array like so [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7]

How can I turn it into a 2-dimensional array that's based on matching numbers before the decimal?

ex.[[1.2, 1.3, 1.4], [2.2, 2.3], [3.0], [4.3, 4.4, 4.5, 4.6, 4.7]]

答:
Assuming you want empty arrays in between, you can use reduce() like this:

const numbers = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];

const grouped = numbers.reduce(
    (result, number) => {
        result[Math.trunc(number)].push(number);
        return result;
    },
    Array(Math.trunc(Math.max(...numbers)) + 1).fill().map(() => [])
);
```

<p>Result:</p>

<pre class="lang-js prettyprint-override"><code>[
    [],
    [1.2,1.3,1.4],
    [2.2,2.3],
    [3],
    [4.3,4.4,4.5,4.6,4.7]
]
</code>```

Body:
Assuming you want empty arrays in between, you can use reduce() like this:

const numbers = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];

const grouped = numbers.reduce(
    (result, number) => {
        result[Math.trunc(number)].push(number);
        return result;
    },
    Array(Math.trunc(Math.max(...numbers)) + 1).fill().map(() => [])
);

Result:

[
    [],
    [1.2,1.3,1.4],
    [2.2,2.3],
    [3],
    [4.3,4.4,4.5,4.6,4.7]
]


问:
OpenGL texture loading issue in Android device
We are creating a cube on which we are loading textures. It is working fine in the emulator and in an HTC Desire device but in another device (LG Optimus,HTC Desire) the textures are not being loaded. Let us know if any one has solved this issue.</p>

答: I'll bet my hat that it's the texture dimensions. The emulator for some reason supports (and some of the examples use) odd dimensions like 192 x 192 which certain hardware will not support. Try a texture with dimensions that are a power of 2 like 128 x 128, or 256 x 256 etc.</p>


问:
Pattern for templating arguments for existing Terraform resources
I'm using the Terraform GitHub provider to define GitHub repositories for an internal GitHub Enterprise instance (although the question isn't provider-specific).

The existing github_repository resource works fine, but I'd like to be able to set non-standard defaults for some of its arguments, and easily group other arguments under a single new argument.

e.g.

github_repository's private value defaults to false but I'd like to default to true

Many repos will only want to allow squash merges, so having a squash_merge_only parameter which sets allow_squash_merge = true, allow_rebase_merge = false, allow_merge_commit = false

There are more cases but these illustrate the point. The intention is to make it simple for people to configure new repos correctly and to avoid having large amounts of config repeated across every repo.

I can achieve this by passing variables into a custom module, e.g. something along the lines of:

Foo/custom_repo/main.tf:

```<code>resource "github_repository" "custom_repo" {
  name                 = ${var.repo_name}
  private              = true
  allow_squash_merge   = true
  allow_merge_commit   = ${var.squash_merge_only ? false : true}
  allow_rebase_merge   = ${var.squash_merge_only ? false : true}
}
</code>```

Foo/main.tf:

```<code>provider "github" {
 ...
}

module "MyRepo_module" {
  source            = "./custom_repo"
  repo_name         = "MyRepo"
  squash_merge_only = true
}
</code>```

This is a bit rubbish though, as I have to add a variable for every other argument on github_repository that people using the custom_repo module might want to set (which is basically all of them - I'm not trying to restrict what people are allowed to do) - see name and repo_name on the example. This all then needs documenting separately, which is also a shame given that there are good docs for the existing provider.

Is there a better pattern for reusing existing resources like this but having some control over how arguments get passed to them?

答:
We created an opinionated module (terraform 0.12+) for this at https://github.com/mineiros-io/terraform-github-repository

We set all the defaults to values we think fit best, but basically you can create a set of local defaults and reuse them when calling the module multiple times.

fun fact... your desired defaults are already the module's default right away, but to be clear how to set those explicitly here is an example (untested):

```<code>locals {
  my_defaults = {
     # actually already the modules default to create private repositories
     private = true

     # also the modules default already and
     # all other strategies are disabled by default
     allow_squash_merge = true
  }
}

module "repository" {
  source  = "mineiros-io/repository/github"
  version = "0.4.0"

  name = "my_new_repository"

  defaults = local.my_defaults
}
</code>```

not all arguments are supported as defaults yet, buts most are: https://github.com/mineiros-io/terraform-github-repository#defaults-object-attributes

Body:
I'm using the Terraform GitHub provider to define GitHub repositories for an internal GitHub Enterprise instance (although the question isn't provider-specific).

The existing github_repository resource works fine, but I'd like to be able to set non-standard defaults for some of its arguments, and easily group other arguments under a single new argument.

e.g.

github_repository's private value defaults to false but I'd like to default to true

Many repos will only want to allow squash merges, so having a squash_merge_only parameter which sets allow_squash_merge = true, allow_rebase_merge = false, allow_merge_commit = false

There are more cases but these illustrate the point. The intention is to make it simple for people to configure new repos correctly and to avoid having large amounts of config repeated across every repo.

I can achieve this by passing variables into a custom module, e.g. something along the lines of:

Foo/custom_repo/main.tf:

resource "github_repository" "custom_repo" {
  name                 = ${var.repo_name}
  private              = true
  allow_squash_merge   = true
  allow_merge_commit   = ${var.squash_merge_only ? false : true}
  allow_rebase_merge   = ${var.squash_merge_only ? false : true}
}

Foo/main.tf:

provider "github" {
 ...
}

module "MyRepo_module" {
  source            = "./custom_repo"
  repo_name         = "MyRepo"
  squash_merge_only = true
}

This is a bit rubbish though, as I have to add a variable for every other argument on github_repository that people using the custom_repo module might want to set (which is basically all of them - I'm not trying to restrict what people are allowed to do) - see name and repo_name on the example. This all then needs documenting separately, which is also a shame given that there are good docs for the existing provider.

Is there a better pattern for reusing existing resources like this but having some control over how arguments get passed to them?

Body:
We created an opinionated module (terraform 0.12+) for this at https://github.com/mineiros-io/terraform-github-repository

We set all the defaults to values we think fit best, but basically you can create a set of local defaults and reuse them when calling the module multiple times.

fun fact... your desired defaults are already the module's default right away, but to be clear how to set those explicitly here is an example (untested):

locals {
  my_defaults = {
     # actually already the modules default to create private repositories
     private = true

     # also the modules default already and
     # all other strategies are disabled by default
     allow_squash_merge = true
  }
}

module "repository" {
  source  = "mineiros-io/repository/github"
  version = "0.4.0"

  name = "my_new_repository"

  defaults = local.my_defaults
}

not all arguments are supported as defaults yet, buts most are: https://github.com/mineiros-io/terraform-github-repository#defaults-object-attributes


问:
Compile ExcelDNAUnpack
I've learned Excel VBA programming in the last few months and I can say that I'm now proficient at it.  However, recently I was given an add-in with a .xll extension.  I currently know little about producing .dll/.xll files; but I'm going to learn.

I found this thread Possible to view source code or decompile XLL Excel add in, which points me to github to get some source code.

The README.md tells me how to call the command ExcelDnaUnpack.exe.  However, this command is not in the package. I guess I'm expected to compile the source code and produce it.

How should I do this?

答:
You don't necessarily need to compile the ExcelDnaUnpack project in order to use it. You can download the compiled version (ExcelDnaUnpack.exe) in the Releases tab of the repository.

There you'll find a file called ExcelDnaUnpack.{version}.zip which contains the ExcelDnaUnpack.exe. Extract the .zip file on your machine and run it.

If did want to build it from source, (as of this writing) all you need is Visual Studio 2017 or 2019, with .NET Framework 4.0 or higher installed.

Title: Compile ExcelDNAUnpack


问:
gradient property in img tag
I am trying to gradient my image but it never shows

.asdf img  {
 background: rgb(2,0,36);
background: linear-gradient(0deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 35%, rgba(0,212,255,1) 100%);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asdf text-center tx-white">

  <img style="height: 200px;" class="w-100 shadow-sm bd" src="{{url($xd->banner)}}"alt="">

</div></code>```

what is the correct way to show the gradient on the image?

答:
you can do it as background-image, not as img.

.asdf img {
object-fit: cover;
}

.asdf .img { background-image:
    linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
 url('https://cdn.the-scientist.com/assets/articleNo/66864/aImg/35078/foresttb-l.jpg');
 width: 80%;
    height: 500px;
    background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asdf text-center tx-white">

    <div class="w-100 shadow-sm bd img" ></div>

  </div></code>```

updated, linear-gradient with img tag:

img {
 max-width: 100%;
  }

  .hero-image {
 max-width: 100%;
 width: 800px;
 margin: auto;
  }

  .hero-image::after {
 display: block;
 position: relative;
 background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0, #fff 100%);
 margin-top: -150px;
 height: 150px;
 width: 100%;
 content: '';
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="hero-image">
    <img src='https://cdn.the-scientist.com/assets/articleNo/66864/aImg/35078/foresttb-l.jpg' />
  </div>
  </code>```

Title: gradient property in img tag

Body:
I am trying to gradient my image but it never shows

.asdf img  {
 background: rgb(2,0,36);
background: linear-gradient(0deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 35%, rgba(0,212,255,1) 100%);
            }

  banner)}}"alt="">

what is the correct way to show the gradient on the image?

Body:
you can do it as background-image, not as img.

.asdf img {
object-fit: cover;
}

.asdf .img { background-image:
    linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
 url('https://cdn.the-scientist.com/assets/articleNo/66864/aImg/35078/foresttb-l.jpg');
 width: 80%;
    height: 500px;
    background-size: cover;
}

<div class="asdf text-center tx-white">

    <div class="w-100 shadow-sm bd img" ></div>

  </div>

updated, linear-gradient with img tag:

img {
 max-width: 100%;
  }

  .hero-image {
 max-width: 100%;
 width: 800px;
 margin: auto;
  }

  .hero-image::after {
 display: block;
 position: relative;
 background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0, #fff 100%);
 margin-top: -150px;
 height: 150px;
 width: 100%;
 content: '';
  }

 <div class="hero-image">
    <img src='https://cdn.the-scientist.com/assets/articleNo/66864/aImg/35078/foresttb-l.jpg' />
  </div>


问:
Determining binary/text file type in Java?
Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?</p>

OwnerDisplayName: gsmd

Body: See http://en.wikipedia.org/wiki/Magic_number_(programming)

OwnerDisplayName: MarkusQ

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ben Blank


问:
Display paragraph
I insert the below paragraph into the database .However while displaying it is displayed as (which is not desired one):

The use of this website is subject to the following terms of use: • The content of the pages of this website is for your general information and use only. It is subject to change without notice. • Neither we nor any third parties provide any warranty or guarantee as to the accuracy,

Desired paragraph view:
The use of this website is subject to the following terms of use:

•   The content of the pages of this website is for your general information and use only. It is subject to change without notice.
•   Neither we nor any third parties provide any warranty or guarantee as to the accuracy.

How can we achieve this in asp.net/C#

答:
You may need to substitute your line feed/carriage return symbols with br tags before you put the text in the control. Or, possibly put the br tag into your paragraph text when its stored in the database.

To substitute, you can use String.Replace()

The character codes can be found here http://www.asciitable.com/

Look for character codes 10 and 13.  You should check the text you're attempting to substitute, to find out if both codes are in the string, or just one of them.

Title: Display paragraph


问:
Cannot connect two ECS services via Service Discovery
I am new to AWS and I am trying to deploy simple app to AWS ECS. I have two simple docker containers, running in ECS Fargate:

‘Frontend’: Vue Js app, which makes a single request to backend;

‘Backend’: Django app, which serves the request;

Both services were launched within the same cluster, in default VPC and the same, single public subnet. For ‘Backend’ I configured Service Discovery: Namespace – test, Service Discovery Name – backend. Security group configured to allow All Traffic.

So, the problem is when frontend makes request:

```<code>axios.get('http://backend.test:8000/api/get-test/')
</code>```

I got error: Failed to load resource: net::ERR_NAME_NOT_RESOLVED  backend.test:8000/api/get-test/

However, executing in AWS Cloud9 command: dig +short backend.test returns correct private IP of the backend container.

When I change request to something like

```<code>axios.get('http://172.17.3.85:8000/api/get-test/')
</code>```

where 172.17.3.85 is valid private IP of the backend container, I got following error:

GET http://172.17.3.85:8000/api/get-test/ net::ERR_CONNECTION_TIMED_OUT

However, if I spin out EC2 instance in the same VPC and subnet and SSH to it, I can ping backend container, and requests -

```<code>curl -v http://172.17.3.85:8000/api/get-test/
</code>```

as well as

```<code>curl -v http://backend.test:8000/api/get-test/
</code>```

return desired response.

The only case when everything is working as expected is when the request is like

axios.get('http://3.18.59.133:8000/api/get-test/'),

where 3.18.59.133 is valid Public IP of the backend container.

I would appreciate any suggestion where look further or how to connect two containers via service discovery as right now I am out of ideas.

答:
Based on the discussion in comments and description of the problem, the  reason is that the Frontend’: Vue Js app executes on the client side, for example, in the browser.

This explains all the issues described and discussed:

axios.get('http://backend.test:8000/api/get-test/') does not work as on the client side you can't resolve privte hosted zone.

axios.get('http://172.17.3.85:8000/api/get-test/') does not work because the 172.17.3.85 is valid only in the VPC, not on the client's network.

spin out EC2 instance in the same VPC and subnet and SSH works because private hosted zones can be resolved inside VPC.

axios.get('http://3.18.59.133:8000/api/get-test/') works because public IP can be used on the clinet side, unlike private IPs.

Body:
I am new to AWS and I am trying to deploy simple app to AWS ECS. I have two simple docker containers, running in ECS Fargate:

‘Frontend’: Vue Js app, which makes a single request to backend;

‘Backend’: Django app, which serves the request;

Both services were launched within the same cluster, in default VPC and the same, single public subnet. For ‘Backend’ I configured Service Discovery: Namespace – test, Service Discovery Name – backend. Security group configured to allow All Traffic.

So, the problem is when frontend makes request:

axios.get('http://backend.test:8000/api/get-test/')

I got error: Failed to load resource: net::ERR_NAME_NOT_RESOLVED  backend.test:8000/api/get-test/

However, executing in AWS Cloud9 command: dig +short backend.test returns correct private IP of the backend container.

When I change request to something like

axios.get('http://172.17.3.85:8000/api/get-test/')

where 172.17.3.85 is valid private IP of the backend container, I got following error:

GET http://172.17.3.85:8000/api/get-test/ net::ERR_CONNECTION_TIMED_OUT

However, if I spin out EC2 instance in the same VPC and subnet and SSH to it, I can ping backend container, and requests -

curl -v http://172.17.3.85:8000/api/get-test/

as well as

curl -v http://backend.test:8000/api/get-test/

return desired response.

The only case when everything is working as expected is when the request is like

axios.get('http://3.18.59.133:8000/api/get-test/'),

where 3.18.59.133 is valid Public IP of the backend container.

I would appreciate any suggestion where look further or how to connect two containers via service discovery as right now I am out of ideas.


问:
Change Blazor offline chrome window style
Can we change the style of the window that host Blazor offline apps, Like changing title bar color or set an icon or change default window back color.</p>

答:
yes - in the manifest.json - see https://pwa-workshop.js.org/1-manifest/#manifest-fields

example:

```<code>{
  "name": "myapp",
  "short_name": "myapp",
  "start_url": "./",
  "display": "standalone",
  "background_color": "#B4ECF9",
  "theme_color": "#F00BAA",
  "icons": [
    {
      "src": "/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    },
    {
      "src": "/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}
</code>```

Body:
yes - in the manifest.json - see https://pwa-workshop.js.org/1-manifest/#manifest-fields

example:

{
  "name": "myapp",
  "short_name": "myapp",
  "start_url": "./",
  "display": "standalone",
  "background_color": "#B4ECF9",
  "theme_color": "#F00BAA",
  "icons": [
    {
      "src": "/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    },
    {
      "src": "/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}


问:
How to use @Autowired annotation two or more different Component class for same service?
For example, have a class like as follows.
First XService service in class A is not null but second XService service in AmountValidator is null.I get NullPointerException I try to create bean new it works and then I get same exception when call AmountValidateService outsideRestService in XService.
How can I  use XService everywhere that I use @Autowired annotation.

My main class:

```<code>@Service
 class A extends AbstractA implements  IA {
 @Autowired
 XService service; //first autowired definition. code go to check() method. service not null now.

public doSometing(){
    validator.check();
    service.methodA();
    super.AbstractMethod();
  }
}
</code>```

Validator class used in class A :

```<code> class Validator<T> implements IValidator<T> {
         public void check(){
             rule.check(); // rule have a implements IValidator eg: amountValidator, dateValidator class
          }
        }
</code>```

AmountValidator added to rule in class Validator.

```<code>@Component
class AmountValidator implements IValidator<T>{
@Autowired
XService service; // code comes here service is null. same service class mentioned above class A.

@Override
public void check(){
     service.validateAmount(); // nullPointerException.
  }
}
</code>```

My main Service

```<code>@Component
class XService {
@Autowired
AmountValidateService outsideRestService;

public validateAmount(){
    outsideRestService.validate(); // nullPointer when create XService with the `New` keyword
  }
}
</code>```

答:
All classes annotated with @Component, @Service are considered special classes which are instantiated by Spring automatically via DI, instantiating them with new defeats the purpose of DI.

These special classes are named Spring Beans.

Every time the application starts, the framework instances all Spring Beans, and all @Autowired fields are injected by Spring automatically. But the Spring Beans must be defined somewhere in the class path. Else you will receive a NoSuchBeanDefinitionException

As an attempt to answer the question, since I don't have a stack trace nor all the Spring Bean definitions:

When you instantiate XService using new XService() your new instance will not actually initialize the field AmountValidateService outsideRestService, effectively leaving it as null.

You may set the field yourself but as I mentioned earlier, it defeats the purpose of DI

Your question is not complex, it is incomplete.

Body:
For example, have a class like as follows.
First XService service in class A is not null but second XService service in AmountValidator is null.I get NullPointerException I try to create bean new it works and then I get same exception when call AmountValidateService outsideRestService in XService.
How can I  use XService everywhere that I use @Autowired annotation.

My main class:

@Service
 class A extends AbstractA implements  IA {
 @Autowired
 XService service; //first autowired definition. code go to check() method. service not null now.

public doSometing(){
    validator.check();
    service.methodA();
    super.AbstractMethod();
  }
}

Validator class used in class A :

 class Validator<T> implements IValidator<T> {
         public void check(){
             rule.check(); // rule have a implements IValidator eg: amountValidator, dateValidator class
          }
        }

AmountValidator added to rule in class Validator.

@Component
class AmountValidator implements IValidator<T>{
@Autowired
XService service; // code comes here service is null. same service class mentioned above class A.

@Override
public void check(){
     service.validateAmount(); // nullPointerException.
  }
}

My main Service

@Component
class XService {
@Autowired
AmountValidateService outsideRestService;

public validateAmount(){
    outsideRestService.validate(); // nullPointer when create XService with the `New` keyword
  }
}