text:
Q: Возможность програмирования на планшете Здравствуйте. Ничего не понимаю в программировании, но хочу начать обучатся. Подскажите, возможно ли программирование на планшете?
К компьютеру пока не имею доступа.

A: Для разработки Android-программ на языке программирования Java есть IDE для android-устройств - AIDE. Возможности ее довольно скромны, по сравнению с десктопными средствами разработки и для начального обучения это тоже не самый лучший вариант, но под платформу Android - лучшее из того, что есть. Ссылка на Google Play
C другими языками программирования на платформе Android все несколько печально. Есть инструменты для работы с С\С++, но начинать учиться программированию на этих языках крайне не рекомендуется.
Так же есть некие инструменты - DeuterIDE, список поддерживаемых языков впечатляет (40 штук) и Run The Code (20 языков), но что это такое и насколько пригодно для использования сказать не могу, не пользовался.

A: Если речь именно об обучении программированию, а не о серьёзной разработке на планшете, можно посмотреть на TouchDevelop от Microsoft. Он реализован прямо в браузере, интерфейс изначально проектировался для мобильных платформ. Внутри использует JavaScript, но вам об этом знать пока необязательно (ой, уже поздно).
Возможности у него, конечно, скромные. И полученные знания очень слабо привязываются к конкретному языку, поэтому этого вам хватит до ухода с уровня "абсолютный начинающий".

Далее вы, вероятно, захотите работать с реальными языками, и тут уже будут проблемы, поскольку они приспособлены для работы с полноценной клавиатурой, на которой удобно набирать произвольный текст, богатый на пунктуацию. На планшетах пунктуация обычно запрятана в отдельный раздел клавиатуры. Каждый раз на него переключаться это боль. В какой-то мере помогает "хакерская клавиатура" (Hacker's keyboard, см. Google Play), делая клавиатуру чуть более похожей на обычную (более полная раскладка)...
Так уж сконструированы используемые нынче (нормальные, не эзотерические) языки. Всем нужна пунктуация. Даже Ruby, в котором из известных мне языков её меньше всего, без пунктуации далеко не уехать.
Возможным спасением мог бы стать редактор, умеющий расставлять пунктуацию (большую её часть хотя бы) самостоятельно, примерно как это делает Parinfer на основе отступов строк (количества пробелов в начале каждой строки), но это уже далеко не для начинающих, да и ни одна реализация, адаптированная под тачскрины мне пока неизвестна. Впрочем, в связи с успешным переносом ClojureScript в браузер, могут возникнуть!

Короче, проблема не в том, что это неудобно. А в том, что инструментов никто не делает, чтобы это стало удобным.
Для современных сред разработки считается уже почти требованием выполнение крупных преобразований над кодом. Если реализовать и более мелкие и хорошенько разложить по интерфейсу... теоретически, это может быть удобно. Но этим мало кто занимается.

A: Купите планшет на Windows установите IntelliJ IDEA + JDK и будет вам счастье. У меня так супруга долгое время изучала Java.


text:
Q: Location of config files in project c++ I was wondering whether there is a convention for storing config files in c++. At the moment I am storing the config files in the same directory as the source code that uses them. When building I make sure via the CMakeLists to copy them to the correct location so I can just access them in  a relative way (e.g. "config.cfg" iso "/foo/bar/config.cfg) for convenience.

A: The practice for config files is non portable and operating system dependent.  You have also to ask yourself if your configuration is defined per installation/system or per user.
In general, it is a very bad idea to store config in the same directory as your execuable, at least once the developpement is finished.  In general executables may be shared between several users and should therefore for security reasons be located in directories that are write-protected for everybody but the system administrator.
For unix/linux, you could for example consider:

*

*/etc  or a subfolder thereof, if your configuration is per installed system,

*~/ if it's user defined configuration.  The usual practice would be to start the filename with a dot.  This article will tell you more.

For windows systems, you should consider:

*

*the usual approach now, goes to the registry.  Of course, this uses the windows api and is fully non portable.

*a subfolder of C:\ProgramData or C:\Users\All users\AppData\Local if your configuration is per installed system,

*a subfolder of C:\Users\%USERNAME%\AppData\Local for the users's own configuration.
This SO questions shows how to find the right folders.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create BigQuery materialized view using Cloud Deployment Manager I can create native and external tables, as well as views in BigQuery using Deployment Manager, however, there doesn't seem to be any way to create a materialized view. Page at:  https://cloud.google.com/bigquery/docs/materialized-views-intro says its still in beta - is it typical for GCP beta features to have no support in Deployment Manager?
Is there a workaround for this? Only thing I can think of is using a Job resource https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert and specifying a DDL query like: CREATE MATERIALIZED VIEW ... but I don't think Deployment Manager will track and manage the resource correctly.
Edit: for anyone else, this works even though not documented:
- name: test-mv
  type: bigquery.v2.table
  properties:
    datasetId: experiments
    tableReference:
      datasetId: experiments
      tableId: test_mv
    materializedView:
      query: "select test, COUNT(*) as counter from experiments.test group by test"

A: According to Google Cloud Deployment Manager documentation bigquery.v2.table resource type is actually leveraging tables REST object as a part of BigQuery API inventory.
Having said this, I assume that you can fully rely on tables.insert method as per Bigquery guidelines here:

Call the tables.insert method with a defined materializedView resource
  as part of your API request. The materializedView resource contains a
  query field.

"materializedView": {
    "query": "select product_id,sum(clicks) as
                sum_clicks from project-id.my_dataset.my_base_table
                group by 1"
  }

Defining appropriate materializedView property in the initial deployment configuration or Python/Jinja template.
I haven't tested yet the mentioned above API functionality, but once you have any further doubts with the implementation I'll try to dig deeper.


text:
Q: How to make resource pack textures for items? I'm new to this, so please bear with me. I've been trying to make a resource pack for a map I'm designing. I've been able to change the block textures, but when I try to change an item texture or one of a plant (wheat), it either gives me the pink and black texture error, or an annoying white block around the item.
Usually, If I do clinch the texture, the parts I wish to be transparent are not. I've tried several programs for adding transparency, but they've all returned the classic texture error. I'm really confused as to why. Can anyone help me understand, then fix it?

A: Ok, so this will be pretty hard... anyway so, I'm just gonna tell you what I'd do.
So first I'd get a copy of the default Minecraft resource pack. Then when you go into the folder just change the textures and such.
Some warnings:
One, Being that some blocks such as grass use special textures, Just drawing all over it will look odd and not look how you want to all the time. (depends on what colour you want it.)
Two, tying to make costume sounds will be very hard. Since 1.7 they changed the way sounds work. However there are ways to fix this, there are some programs that will do this for you. But that is known be a little hard!
Three, When you have finished the resource pack remember to put it into %appdata%/.minecraft/resourcepacks then select it in game. and start game and test it out!
Oh and if you look hard enough you will find every thing you can change, E.g the image that comes up when you put on a pumpkin, or the look of a enchanted item. (the purple flashy bits.)
Hope this helps somewhat, But if it didn't then... i have my excuses, My first post :3
Oh and i was just tying to say everything that might help. since as i don't know how good you are at it at all so i just acted like you needed to know!

A: The site that I use for texture editing is http://minecraft.novaskin.me/texturepacks  it is very in editing textures of items and its very simple to use!
Hope this helps! =)


text:
Q: Why zone is always nil while implementing NSCopying? It may be simple question, but why implementing NSCopying protocol in my class, I get zone == nil
- (id)copyWithZone:(NSZone *)zone
{
    if (zone == nil)
        NSLog(@"why this is allways nil");

    (...)
}

This is called using this method for copy array with objects.
[[NSArray alloc] initWithArray:myArray copyItems:YES]];

A: A NULL zone just means 'use the default zone'. Zones aren't used by the modern Objective C runtime anymore and cannot be used with ARC at all.
See documentation

A: NSZone was deprecated a long time ago. The fact that it's still in method signatures (e.g. +allocWithZone: and -copyWithZone:) are for backwards compatibility.

A: Kevin's and Robin's answer is the most accurate.  Oscar's answer is pretty close to correct.  But neither the Gnustep documentation nor logancautrell's reasons for the existence of zones is quite correct.
Zones were originally created -- first NXZone, then NSZone -- to ensure that objects allocated from a single zone would be relatively contiguous in memory, that much is true.  As it turns out, this does not reduce the amount of memory an app uses;  it ends up increasing it slightly, in most cases.
The larger purpose was to be able to mass destroy a set of objects.
For example, if you were to load a complicated document into a document based application, tear-down of the object graph when the document was closed could actually be quite significantly expensive.
Thus, if all the objects for a document were allocated from a single zone and the allocation metadata for that zone was also in that zone, then destruction of  all objects related to the document would be as cheap as simply destroying the zone (which was really cheap -- "here, system, have these pages back" -- one function call).
This proved unworkable.   If a single reference to an object in the zone leaked out of the zone, then your app would go BOOM as soon as the document was closed and there was no way for the object to tell whatever was referring to it to stop.   Secondly, this model also fell prey to the "scarce resource" problem so often encountered in GC'd system.  That is, if the object graph of the document held onto non-memory resources, there was no way to clean up said resources efficiently prior to zone destruction.
In the end, the combination of not nearly enough of a performance win (how often do you really close complex documents) with all the added fragility made zones a bad idea.   Too late to change the APIs, though, and we are left with the vestiges.

A: Zone is a legacy from the old days when computers had 8 megs or less of RAM.
Check this out (3.1.2 Memory Allocation and Zones):
http://www.gnustep.org/resources/documentation/Developer/Base/ProgrammingManual/manual_3.html
There is also a good discussion of this over on cocoa builder (well it was on the cocoa dev mailing list) from about 10 years ago. This is exactly what @bbum was saying.
http://www.cocoabuilder.com/archive/cocoa/65056-what-an-nszone.html
Apparently this used to be documented in the Apple docs, but it was changed at some point since 2007-06-06.
http://www.cocoadev.com/index.pl?NSZone

A: NSZone is now an undocumented class because it is quite old, its purpose was to allocate objects on the heap using the same set of virtual memory pages. However it is mostly not used anymore, but since it was used before, that parameter is still there for backwards compatibility.


text:
Q: Swapping positive and negative values in Notepad++? I have a list of numbers in notepad++ that I need X value +- signs swapped. Trying to create a expression or script to make it happen. List like this:
<Polygon Type="Field">
      <Point X="-2" Y="424" />
      <Point X="698" Y="-278" />
      <Point X="477" Y="-499" />
      <Point X="1" Y="-4" />
      <Point X="-2664" Y="-2486" />
      <Point X="-2817" Y="-2322" />

Need to change X values only to be like this:
<Polygon Type="Field">
      <Point X="2" Y="424" />
      <Point X="-698" Y="-278" />
      <Point X="-477" Y="-499" />
      <Point X="-1" Y="-4" />
      <Point X="2664" Y="-2486" />
      <Point X="2817" Y="-2322" />

Any suggestions?

A: Congrats on your first question. You can read more about this here: https://www.regular-expressions.info/replaceconditional.html
Find string is X="(-)?(\d+)"
Replace string is X="(?1:-)\2"
Key here is the replacement conditional which has the syntax (?xyyy:zzz). If the capture group x is fulfilled, then it replaces with yyy, otherwise zzz. So, dash with nothing, and nothing with dash.


text:
Q: Compute matrix determinant for matrix with $\lambda$ on diagonal and $\mu$ elsewhere Given $n\in \mathbb N$, how can I compute the determinant of $(a_{ij})_{1\leq i,j \leq n} \in \mathcal M_{n\times n}(\mathbb R)$ where, for each $1\leq i,j\leq n:$ $$a_{ij}= \begin{cases} \lambda &i=j \\ \mu & i\neq j \end{cases}$$
The only (or the only easy) way to do this I think involves using Laplace's formula, expanding along any row. But doing this everything gets too messy, I can't express it in a good way. I tried to get a recursive relation and prove it via induction but didn't get anywhere. Is there an easier way? Any hints appreciated.

A: Let $A$ be the matrix:
$$\begin{pmatrix}
\lambda & \mu & \mu & \cdots & \mu \\
\mu & \lambda & \mu & \cdots & \mu \\
\mu & \mu & \lambda & \cdots & \mu \\
\vdots & \vdots & \vdots && \vdots \\
\mu & \mu & \mu & \cdots & \lambda \\
\end{pmatrix}$$

Consider:
$$\begin{pmatrix}
\lambda & \mu & \mu & \cdots & \mu \\
\mu & \lambda & \mu & \cdots & \mu \\
\mu & \mu & \lambda & \cdots & \mu \\
\vdots & \vdots & \vdots && \vdots \\
\mu & \mu & \mu & \cdots & \lambda \\
\end{pmatrix}
\begin{pmatrix}1\\1\\1\\\vdots\\1\end{pmatrix}
=
\begin{pmatrix}\lambda+(n-1)\mu\\\lambda+(n-1)\mu\\\lambda+(n-1)\mu\\\vdots\\\lambda+(n-1)\mu\end{pmatrix}
=
\left[\lambda+(n-1)\mu\right]
\begin{pmatrix}1\\1\\1\\\vdots\\1\end{pmatrix}$$
Hence, $\left[\lambda+(n-1)\mu\right]$ is an eigenvalue of $A$.

Consider:
$$\begin{pmatrix}
\lambda & \mu & \mu & \cdots & \mu \\
\mu & \lambda & \mu & \cdots & \mu \\
\mu & \mu & \lambda & \cdots & \mu \\
\vdots & \vdots & \vdots && \vdots \\
\mu & \mu & \mu & \cdots & \lambda \\
\end{pmatrix}
\begin{pmatrix}1\\0\\0\\\vdots\\-1\end{pmatrix}
=
\begin{pmatrix}\lambda-\mu\\0\\0\\\vdots\\\mu-\lambda\end{pmatrix}
=
\left[\lambda-\mu\right]
\begin{pmatrix}1\\0\\0\\\vdots\\-1\end{pmatrix}$$
Hence, $\left[\lambda-\mu\right]$ is an eigenvalue of $A$.
One can construct other eigenvalues using this method, so in total we will have $(n-1)$ eigenvalues which are $\left[\lambda-\mu\right]$.

$$\det A = \prod \lambda_k = \left[\lambda+(n-1)\mu\right]\left[\lambda-\mu\right]^{n-1}$$

A: Let $v$ be a column vector of ones. Then $vv^T$ is a matrix of ones, and the matrix of interest can be expressed as $\mu (vv^T)+(\lambda-\mu)I_n.$ The determinant of this rank-one matrix can then be found in a number of ways e.g. using the matrix determinant lemma, considering the eigenvalues, etc.


text:
Q: How can a single configuration be shared between projects in a solution? I have a solution (S) in Visual Studio containing 3 projects, I'll call them CL, WPF, and CFG;

*

*S.CL is a project for a console application.

*S.WPF is a project for a WPF application.

*S.CFG is a project that contains the config file.

I have created a settings file with user scope and public visibility. Both of these projects use the same settings.
S.CL only needs to read these settings.
S.WPF is a form to edit these settings, so it requires read and write. It contains a save button connected to an event handler.
S.CFG app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="S.CFG.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <S.CFG.Properties.Settings>
            <setting name="ExampleSetting" serializeAs="String">
                <value>ExampleValue</value>
            </setting>
        </S.CFG.Properties.Settings>
    </userSettings>
</configuration>

S.CL Execute.cs:
namespace S.CL
{
    public class Execute
    {
        public static void Main(String[] args)
        {
            Console.WriteLine(S.CFG.Properties.Settings.Default.ExampleSetting);
        }
    }
}

S.WPF MainWindow.xaml.cs:
namespace S.WPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            S.CFG.Properties.Settings.Default.ExampleSetting = "New value";
            Console.WriteLine(S.CFG.Properties.Settings.Default.ExampleSetting);
        }
    }
}

So, steps to reproduce:
Run S.CL out> ExampleValue
Run S.WPF out> New value
Run S.CL out> ExampleValue

On the last run of S.CL, the output should have been "New value".
I can confirm that S.WPF also gets the newest value every time it runs. In my full application, the form displays the newest value in a text box before hitting save.
So far I've managed to find out the S.WPF creates a folder with this new app.config in the user's AppData folder. S.CL uses it's built in copy of the default config, whereas S.WPF uses it's built in copy of the default config until it writes, where it then creates a local copy that only that executable accesses.
I just want to be able to persist these settings between these 2 executables. I have thought about other ways of doing this, another would be to keep an XML file of settings in the root directory of both executables and just parse this file but I would rather using Visual Studio's app.config/Settings.Settings functionality to do this (if possible).
Thanks in advance!

A: instead of adding the app.config files to each project, you could have one app.config file in your solution and link this one file to both of the projects, as described here: Share code with Add as Link.
Edit:
If you want to be able to load an external app.config, you can check follow the instructions of this post,


text:
Q: How to upgrade a GPO force-installed Chrome Extension? We develop a network security product, incorporating a chrome extension, currently installed by the ExtensionInstallForcelist value in GPO.
One of our product features is that surfing the Internet/intranet is separated in to several trust zones - and the chrome extension is responsible for making the switch between different browser windows running in different zones. Sometimes, the update_url in the CRX will not be accessible to browsers running in all trust zones. Since Chrome "imports" the extension upon the first installation from the CRX location specified in the initial XML file, I am at a loss as to how to upgrade the extension when our software is upgraded. So far I am only seeing the following options:

*

*manually edit each user's "Preferences" file and Extensions\ directories under Chrome's AppData location (this to me is hackish, unstable and I would rather avoid it...)

*Use a static file:/// url as the update_url in the manifest.json (but this has the limit of a specific drive, directory and file having to be present)

*manually edit the master_preferences file to install and/or upgrade our extension (this is strongly discouraged by google, here: https://support.google.com/chrome/a/answer/188453?hl=en
Does anyone have any experience with deploying Chrome extension for corporate applications and upgrading them in a way I missed (after much, much digging...)?
Thanks :-)

A: We ended up using a hardcoded file:/// url as the update_url as we could not find a better way of doing it (we chose not to publish the extension on the chrome appstore).


text:
Q: Differences in display of parameters between GNU Radio 3.7 and 3.8 I am porting multi-rtl to GNU Radio 3.8. I've actually done all the porting and I already have a program that works. Now only a few cosmetic changes are missing, such as new examples. When I wanted to make a new example, I realized that the block is displayed for me differently than in the picture. Here is this picture from documentation (original program):

Here is how this block is displayed for me (in my ported program):

It's even expected behavior. Here are parameters of this block (they're generated for each n in this way):
-   id: sync_gain${n}
    label: "Ch${n}: Sync RF Gain (dB)"
    category: Synchronization
    dtype: real
    default: 10
    hide: ${"$"}{ 'part' if nchan > ${n} else 'all' }
-   id: freq${n}
    label: "Ch${n}: Frequency (Hz)"
    category: RF Options
    dtype: real
    default: 100e6
    hide: ${"$"}{ 'none' if nchan > ${n} else 'all' }
-   id: gain${n}
    label: "Ch${n}: RF Gain (dB)"
    category: RF Options
    dtype: real
    default: 10
    hide: ${"$"}{ 'part' if nchan > ${n} else 'all' }
-   id: gain_mode${n}
    label: "Ch${n}: Gain Mode"
    category: RF Options
    dtype: bool
    default: False
    hide: ${"$"}{ 'part' if nchan > ${n} else 'all' }
    options: [ False, True ]
    option_labels: [ Manual, Automatic ]
-   id: id_string${n}
    label: "Ch${n}: ID string"
    dtype: string
    default: "${n}"
    hide: ${"$"}{ 'part' if nchan > ${n} else 'all' }

The only parameter with the hide option set to none is "Ch $ {n}: Frequency (Hz)" so it's also only parameter that is displayed "outside". It's normal. However, I do not understand why the equivalent of this code in gnuradio 3.7 is displayed differently. Here's GNU Radio 3.7 code that I think is equivalent:
<param>
  <name>Ch$(n): Sync RF Gain (dB)</name>
  <key>sync_gain$(n)</key>
  <value>10</value>
  <type>real</type>
  <hide>\#if \$nchan() > $n then 'part' else 'all'#</hide>
  <tab>Synchronization</tab>
</param>
<param>
  <name>Ch$(n): Frequency (Hz)</name>
  <key>freq$(n)</key>
  <value>100e6</value>
  <type>real</type>
  <hide>\#if \$nchan() > $n then 'none' else 'all'#</hide>
  <tab>RF Options</tab>
</param>
<param>
  <name>Ch$(n): RF Gain (dB)</name>
  <key>gain$(n)</key>
  <value>10</value>
  <type>real</type>
  <hide>\#if \$nchan() > $n then 'part' else 'all'#</hide>
  <tab>RF Options</tab>
</param>
<param>
  <name>Ch$(n): Gain Mode</name>
  <key>gain_mode$(n)</key>
  <value>False</value>
  <type>bool</type>
  <hide>\#if \$nchan() > $n then 'part' else 'all'#</hide>
  <option>
    <name>Manual</name>
    <key>False</key>
  </option>
  <option>
    <name>Automatic</name>
    <key>True</key>
  </option>
  <tab>RF Options</tab>
</param>
<param>
  <name>Ch$(n): ID string</name>
  <key>id_string$(n)</key>
  <value>"$(n)"</value>
  <type>string</type>
  <hide>\#if \$nchan() > $n then 'part' else 'all'#</hide>
</param>

Why are they displayed differently?

A:
Why are they displayed differently?

Probably some bug in your gnuradio 3.7 version. I just tested it with gnuradio 3.7.13.5 and the displayed block is similar to your gnuradio 3.8 example.

If you want to see all parameters change 'part' to 'none'. See also https://wiki.gnuradio.org/index.php/YAML_GRC#Parameters


text:
Q: Mailchimp API - Method to get list of campaigns per user I am using the Mailchimp API to collect info about list members (per email), and campaigns. However, I am not seeing a method to collect a list of campaigns that were sent to a specific email/list member.
Am I missing something?

A: First get list of all campains. And in loop of campains, and check if user exists in list. mailchimp provide api ti check if user contains in list.


text:
Q: Set merge strategy on AndoridManifest when using gradle and library projects I have a gradle project that uses a library with a minSdkVersion set to api level 11. My application has a minSdkVersion of 9. When compiling I get the following error.
Main manifest has <uses-sdk android:minSdkVersion='9'> but library uses minSdkVersion='11'

I have seen a similar question titled manifest-merging-failed-android-studio but the solution was to change the library to have the same minSdk version. If you dont have control over the library that isnt possible.
The library is only used in situations where the minSdkVersion is higher than 11 so actual use isnt an issue.
Is there anyway to get the advantages manifest merging and let the library have a higher minSdk than your main project?
Workarounds that I have thought of but havent found a way to do.

*

*Set priority if manifests conflict

*Ignore minsdk for library projects

*Remove minSdk from arr before merging starts


text:
Q: How to do client certificate based authentication in SparkJava without reverse proxy or Tomcat I am aware of how to secure a connection: http://sparkjava.com/documentation.html#secure
But this does not enable client certificate-based authentication (I am trying to implement Estonian identity card user authentication)
After research I found a link where it is said that it cannot be done in Spark: https://groups.google.com/forum/#!topic/sparkjava/dnCKl-W018A
Fortunately it is an old post.
How do to this with SparkJava embedded Jetty container?


text:
Q: Ansible file processing / blockinfile module in Windows I want to udpate block of multiline text in a file in Windows via ansible. Have used blockinfile
but it works only on Linux machines. Are there any alternative for this module ? Or any other way to do this? There is win_lineinfile but I have around  20 lines to be added.
Any help is very much appreciated!!

A: Currently there is no module that allows a block of lines to be written on a Windows host.
You may want to use win_shell module and Out-File cmdlet of Powershell as a workaround


text:
Q: Combing multiple rows with same ForeignKey fields through query Current Model.objects.all() creates:

 FK Column  Column1  Column2  Column3
  Zone 1        19      23       67
  Zone 2        45      12       76
  Zone 1        23      98       34
  Zone 2        12      56       23

Expected Results:

 FK Column  Column1  Column2  Column3
  Zone 1        42      101       111
  Zone 2        57      68        99

The FKs are automatically combined into a single row.
which query should I use exactly for achieving this?

A: You can do this with a .values(..) together with an .annotate(..) and .order_by(..):
Model.objects.values(
    'fk_column'
).annotate(
    sumcol1=Sum('col1'),
    sumcol2=Sum('col2'),
    sumcol3=Sum('col3'),
).order_by('fk_column')

This will result in a QuerySet of dictionaries. Each dictionary contains an 'fk_column', 'sumcol1', 'sumcol2', and 'sumcol3'. These parameters can then be processed further.


text:
Q: Node SASS issue | npm install node-sass I faced a problem while I was trying to install SASS. When I enter this line to the terminal:
npm install node-sass

VSCode shows me this error. I researched some topics here but not any answers did solve my problem. Can you help me with this? btw I use a MacBook.

Actually it should install SASS but as you see I am just facing with this error message.


text:
Q: Calc formulas show up in English, how can I use them in my native language? I'm a brazilian user and after update to ubuntu 11.10, my LibreOffice (that here is called Broffice) is having some formulas in english and it has always being in portuguese.
Like Sum always was Soma, and so on.

A: If the option to use formulas in English is disabled and you're still not seeing formulas in your language, it might be due to this bug.

A: There is an option in Calc to use the English formulas (it's really handy as most documentation is in English). Please check that it is disabled:


text:
Q: GeoServer with viewparams returns ORA-00907: missing right parenthesis I am trying to call a JSON request from geoserver which has an Oracle NG Layer.  I have one parameter in the call:
viewparams=customer:One Customer

The parameter value has to have a space in it.  I cannot get it to work, and am getting the following error:
<ServiceExceptionReport version="1.2.0" xsi:schemaLocation="http://www.opengis.net/ogc http://schemas.opengis.net/wfs/1.0.0/OGC-exception.xsd"><ServiceException>
      java.lang.RuntimeException: java.io.IOException
java.io.IOException
null
ORA-00907: missing right parenthesis

</ServiceException></ServiceExceptionReport>

This is the url:
http://pc121212:8085/geoserver/sf/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sf:view_ae&viewparams=customer:One%20Customer&outputFormat=JSON

When I go into "Edit SQL View" for the layer in GeoServer, this is the query:
select * from view_ae
where customer = %customer%

The parameter in GeoServer is added with the following values:
Name = customer
Default value = 'One Customer'
Valid Regular Expression = ^[\w\d\s]+$

Does anyone know what is wrong?

A: Fixed after tip by @user30184 to look at the logs!
VERY IMPORTANT: Do not put quotes around the default value on your parameter in the "Sql view paremeters" section.
These are the two changes required:

*

*Place single quotes around the parameter in the "Sql Statement" section:
select * from view_ae
where customer = '%customer%'

*In the "Sql view paremeters" section, On your Sql view parameter, DO NOT include single quotes around the Default Value, if not you will get an error as mentioned in my comments above.  This is how it should look:
Default value = One Customer
Once you do those two changes, the issue is resolved.  Hope someone finds this post useful.


text:
Q: Selenide: How to open Chrome browser with extensions I've faced with a problem that I'm not able to open Chrome with any extension. I've already added an extension but don't know how to run it properly with Selenide framework. Could you please help me
@BeforeClass
public static void setUp() {
   Configuration.browser = "chrome";
   System.setProperty("selenide.browser", "chrome");
   ChromeOptions options = new ChromeOptions();
   options.addExtensions(new File("src/main/resources/uBlock Origin.crx"));
        }

A: Selenide : http://selenide.org/2018/01/12/selenide-4.10/
You can set custom capabilities in Configuration, and Selenide will use them when opening a browser:
Configuration.browserCapabilities = new DesiredCapabilities();
Configuration.browserCapabilities.setCapability(SOME_CAP, "SOME_VALUE_FROM_CONFIGURATION");

Also you can set custom webdriver like in @dangi13 answer:
WebDriverRunner.setWebDriver(myDriverWithExtension);

A: I do not know how to do it in selenide but you can add extension in selenium like this  :
public static WebDriver getChromeDriverWithAdblockCrx() {
          System.setProperty("webdriver.chrome.driver", "src//main//resources//chromedriver.exe");
          DesiredCapabilities capabilities = new DesiredCapabilities();
          ChromeOptions options = new ChromeOptions();
          options.addExtensions(new File("src//main//resources//uBlock Origin.crx"));
          capabilities.setCapability(ChromeOptions.CAPABILITY, options);

          return new ChromeDriver(capabilities);
    }

Hope that helps you:).

A: @sers, @dangi13 Thanks a lot!
But capabilities were not added from Configuration.browserCapabilities. I wrote the following code:
@BeforeClass
public static void setUp() {
Configuration.browser = "chrome";
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("src/main/resources/uBlock Origin.crx"));
Configuration.browserCapabilities = new DesiredCapabilities();
Configuration.browserCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
}

It is known issue that is mentioned on github: https://github.com/codeborne/selenide/issues/676
As workarond I'm using the following option:
@BeforeClass
public static void setUp() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
Configuration.browser = "chrome";
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("src/main/resources/uBlock Origin.crx"));
WebDriver webDriver = new ChromeDriver(options);
setWebDriver(webDriver);
}


text:
Q: service restart with buildozer cant find class? i have tried many solutions and followed many guides but i cant get it to work i have a minimal code example here.
this is my main.py:
import kivy
import platform
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button

from multiprocessing.dummy import Process
from kivy.uix.widget import Widget
import jnius
from kivy.clock import Clock
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class fscreen(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class theapp(App):
    def build(self):
        self.cnt = 0
        self.screenm = ScreenManager() #(transition=FadeTransition())
        self.fscreen = fscreen()
        screen = Screen(name = "first screen")
        screen.add_widget(self.fscreen)
        self.screenm.add_widget(screen)
        return self.screenm

    def change(self, *args):
        self.cnt += 1
        self.fscreen.ids.lb.text = str(self.cnt) + ' hello '
        print(str(self.cnt) + ' hello ')
    def label_update(self):
        Clock.schedule_interval(self.change, 1)

    def on_start(self):
        from kivy import platform
        if platform == "android":
            self.start_service()
        Process(target=self.label_update).start()

    @staticmethod
    def start_service():
        from jnius import autoclass
        service = autoclass("org.pck.ser.Serviceser")
        mActivity = autoclass("org.kivy.android.PythonActivity").mActivity
        service.start(mActivity, "")
        return service

if __name__ == "__main__":
    theapp = theapp()
    theapp.run()

this is a my kv file:
<fscreen>
    Label:
        id:lb
        size: root.width*0.1, root.height*0.05
        pos: root.width*0.45,root.height*0.3

and this is my service.py same folder as main.py:
import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from jnius import autoclass

PythonService = autoclass('org.kivy.android.PythonService')
PythonService.mService.setAutoRestartService(True)

while True:
    print('hello')
    time.sleep(1)

this is the buildozer.spec
[app]

# (str) Title of your application
title = ser

# (str) Package name
package.name = ser

# (str) Package domain (needed for android/ios packaging)
package.domain = org.pck

# (str) Source code where the main.py live
source.dir = .

requirements = python3,kivy==2.0.0,kivymd==0.104.2,numpy,pillow,kivy_garden.mapview,requests,charset_normalizer,chardet,idna, urllib3,certifi,plyer==2.0.0,sqlite3,pickle-mixin,kivygradient,jnius,android
services = ser:service.py

and i have this output from buildozer android debug deploy run logcat i have cleaned modified versions and did a lot of things but same thing i dont know what i am missing
04-16 02:42:04.993 18517 18610 I python  :  Traceback (most recent call last):
04-16 02:42:04.994 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/app/main.py", line 57, in <module>
04-16 02:42:04.994 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/ser/armeabi-v7a/kivy/app.py", line 949, in run
04-16 02:42:04.995 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/ser/armeabi-v7a/kivy/app.py", line 944, in _run_prepare
04-16 02:42:04.995 18517 18610 I python  :    File "kivy/_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
04-16 02:42:04.995 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/app/main.py", line 44, in on_start
04-16 02:42:04.996 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/app/main.py", line 50, in start_service
04-16 02:42:04.996 18517 18610 I python  :    File "/home/odr/Desktop/dev/MobileApps/foreground_test/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/ser/armeabi-v7a/jnius/reflect.py", line 229, in autoclass
04-16 02:42:04.996 18517 18610 I python  :    File "jnius/jnius_export_func.pxi", line 26, in jnius.jnius.find_javaclass
04-16 02:42:04.997 18517 18610 I python  :    File "jnius/jnius_utils.pxi", line 91, in jnius.jnius.check_exception
04-16 02:42:04.997 18517 18610 I python  :  jnius.jnius.JavaException: JVM exception occurred: Didn't find class "org.pck.ser.Serviceser" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/org.pck.ser-KtQcSSOANf-UBQoqXEY3dA==/base.apk"],nativeLibraryDirectories=[/data/app/org.pck.ser-KtQcSSOANf-UBQoqXEY3dA==/lib/arm, /data/app/org.pck.ser-KtQcSSOANf-UBQoqXEY3dA==/base.apk!/lib/armeabi-v7a, /system/lib, /system/vendor/lib]] java.lang.ClassNotFoundException
04-16 02:42:04.997 18517 18610 I python  : Python for android ended.

A: I fixed some lines and cleaned my buildozer:
this is the complete working version of my buildozer.spec:
[app]

# (str) Title of your application
title = ser

# (str) Package name
package.name = ser

# (str) Package domain (needed for android/ios packaging)
package.domain = org.pck

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,db,ttf,wav

# (list) List of inclusions using pattern matching
source.include_patterns = cache/*.png,fonts/cello-sans/*.ttf,fonts/fondation/*.ttf

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
#requirements = python3,Kivy-Garden==0.1.1,futures==2.1.6,requests==1.2.3,certifi,urllib3,chardet,idna
#requirements = python3,kivy==2.0.0,kivymd==0.104.2,numpy,pillow,kivy_garden.mapview,requests,charset_normalizer,chardet,idna, urllib3,certifi,plyer==2.0.0,sqlite3,pickle-mixin,kivygradient,jnius,android
requirements = python3,kivy==2.0.0,kivymd==0.104.2,numpy,pillow,kivy_garden.mapview,requests,charset_normalizer,chardet,idna, urllib3,certifi,plyer==2.0.0,sqlite3,pickle-mixin,kivygradient,android

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements = kivy.garden.mapview

# (str) Presplash of the application
#presplash.filename = presplash.png

# (str) Icon of the application
#icon.filename = icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY
services = Worker:service.py

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
android.permissions = INTERNET, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, FOREGROUND_SERVICE

# (int) Target Android API, should be as high as possible.
#android.api = 27

# (int) Minimum API your APK will support.
#android.minapi = 21

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 19b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_gradle_repositories =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

#
# Python for android (p4a) specific
#

# (str) python-for-android fork to use, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =

#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.7.0

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

this is main.py:
import kivy
import platform
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from jnius import autoclass
from multiprocessing.dummy import Process
from kivy.uix.widget import Widget
import jnius
from kivy.clock import Clock
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class fscreen(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class theapp(App):
    def build(self):
        self.cnt = 0
        self.screenm = ScreenManager() #(transition=FadeTransition())
        self.fscreen = fscreen()
        screen = Screen(name = "first screen")
        screen.add_widget(self.fscreen)
        self.screenm.add_widget(screen)
        return self.screenm

    def change(self, *args):
        self.cnt += 1
        self.fscreen.ids.lb.text = str(self.cnt) + ' hello '
        print(str(self.cnt) + ' hello ')
    def label_update(self):
        Clock.schedule_interval(self.change, 1)

    def on_start(self):
        from kivy import platform

        if platform == "android":

            self.start_service()
            print('service started')
        Process(target=self.label_update).start()

    #@staticmethod
    def start_service(self):
        from android import mActivity
        context =  mActivity.getApplicationContext()
        SERVICE_NAME = str(context.getPackageName()) + '.Service' + 'Worker'
        service = autoclass(SERVICE_NAME)
        print(SERVICE_NAME)
        service.start(mActivity,'')
        return service
        print('returned service')

if __name__ == "__main__":
    theapp = theapp()
    theapp.run()

and this service.py:
import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from jnius import autoclass
import time

PythonService = autoclass('org.kivy.android.PythonService')
PythonService.mService.setAutoRestartService(True)

while True:
    print('this is my service and its running')
    time.sleep(1)

and this is the cat after adb logcat -s Worker:
04-16 03:38:08.882 26990 27006 I Worker  : this is my service and its running
04-16 03:38:09.884 26990 27006 I Worker  : this is my service and its running


text:
Q: Show that the symplectic group $\mathrm{Sp}(2n,\mathbb{C})$ is a closed sub group of $\mathrm{Gl}(2n,\mathbb{C})$ I have to show that the symplectic group
$$\mathrm{Sp}(2n,\mathbb{C}):=\{A\in M(2n,\mathbb{C})\mid AJA^{T}=J\},$$
where $J$ denotes the symplectic matrix, is a closed matrix Lie group, e.g. its a closed subgroup of $\mathrm{Gl}(2n,\mathbb{C})$. I have already shown that its a subgroup of $\mathrm{Gl}(2n,\mathbb{C})$.
In order to show thats its closed, I was considering the determinant:
$$\mathrm{det}:\mathrm{Gl}(2n,\mathbb{C})\to\mathbb{C},$$
which is obviously continuous (bec. polynomial). If one looks than at the restriction
$$\mathrm{det}\vert_{\mathrm{Sp}(2n,\mathbb{C})}:\mathrm{Sp}(2n,\mathbb{C})\to\mathbb{C}$$
which is also a conitnuous map, we have that
$$\mathrm{det}\vert_{\mathrm{Sp}(2n,\mathbb{C})}^{-1}(\{-1,1\})=\mathrm{Sp}(2n,\mathbb{C})$$
and since $\{-1,1\}$ is closed in $\mathbb{R}$, we know by continuity that $\mathrm{Sp}(2n,\mathbb{C})$ is closed.....
Is this right and/or enough to show closedness?


text:
Q: Сумма элементов матрицы в блоках Прочитать действительную А матрицу размером n x n. Для заданного m, такого, что n%m = 0, найти матрицу В размерности n/m х n/m, элементы которой являются суммой элементов матрицы А в блоках размера m x m.
Вывести на экран матрицу А и матрицу В.
Нужны два варианта: с заполнением матрицы с клавиатуры и с заполнением случайными числами.
Изучены только самые простые вещи на новичковом уровне: арифм. операции, условные операторы, циклы, списки. Библиотеки не изучены вообще, с помощью NumPy делать не вариант.
Я не могу разобраться с индексами и циклами: как сделать так, чтобы с помощью циклов просуммировать элементы в последовательных блоках, и потом обнулять сумму при переходе к следующему блоку. Ну и соответственно нужно записывать все эти значения в новую матрицу, но я даже не могу для начала вывести эти самые значения.
n = int(input("Матрица А. n = "))
m = int(input("Матрица B. m = "))

matrix = []
for i in range(n):
    row = []
    for j in range(n):
        row.append(int(input('m[{0}][{1}]= '.format(i+1,j+1))))
    matrix.append(row)
print()
for i in range(n):
    for j in range(n):
        print(matrix[i][j],end=' ')
    print()

s = 0
for i in range(0,n,m):
    for j in range(0,n,m):
        slag_block = matrix[i][j]
        s += slag_block
        slag_block = 0
    print(s)
print(s)

A: Например, так:
import random
n = 4
m = 2

matrix = [[random.randint(1,10) for x in range(n)] for y in range(n)]

for i in range(n):
    for j in range(n):
        print(matrix[i][j],end=' ')
    print()

s = [[0 for x in range(n//m)] for y in range(n//m)]

for i in range(n):
    for j in range(n):
        s[i // m][j // m] += matrix[i][j]

print(s)

Если же делаете обход по первой матрице с шагом m, то внутри цикла должны быть ещё два с range(m)  (здесь второй цикл я заменил на sum по срезу)
r = 0
for i in range(0,n,m):
    c = 0
    for j in range(0,n,m):
        for k in range(m):
            s[r][c] += sum(matrix[i + k][j:j+m])
        c += 1
    r += 1

A: У меня получилось так реализовать эту задачу "Сумма матриц":
a = []
c = []
n, m = map(int, input().split())
for i in range(n):
    b = []
    for j in range(m):
        b.append(int(input()))
    a.append(b)
for i in range(n):
    d = []
    for j in range(m):
        d.append(int(input()))
    c.append(d)
for i in range(n):
    for j in range(m):
        c[i][j] += a[i][j]
for i in c:
    print(i)


text:
Q: Module not found: Can't resolve 'fs' - Calling function I have a NextJS project in which one component is using getStaticProps and getStaticPaths to get a list of files:
The getAllBlogPosts function is in another file (see below)
import { GetStaticPaths, GetStaticProps } from "next";
import { useRouter } from "next/router";
import BlogSummaryPage from "../index";
import { getAllBlogPosts } from "../_functions";
import { BLOGPOSTS_PER_PAGE } from "../../../config/blogposts";

const BlogPage = ({ blogposts }: any) => {
  const router = useRouter();
  const { num = 1 } = router.query;
  return <BlogSummaryPage blogposts={blogposts} page={Number(num)} />;
};

const getStaticPaths: GetStaticPaths = async () => {
  const blogposts = getAllBlogPosts();
  let pageCount = Math.ceil(blogposts.length / BLOGPOSTS_PER_PAGE);
  const paths = [];
  while (pageCount) {
    paths.push({ params: { num: `${pageCount}` } });
    pageCount -= 1;
  }

  return {
    paths,
    fallback: false,
  };
};

const getStaticProps: GetStaticProps = async () => {
  const blogposts = getAllBlogPosts();
  return {
    props: {
      blogposts,
    },
  };
};

export { getStaticProps, getStaticPaths };

export default BlogPage;

In another file:
import fs from "fs";
import matter from "gray-matter";
import { IBlogpost } from "./_types";

const getAllBlogPosts = (): Array<IBlogpost> => {
  const blogpostFilenames = fs.readdirSync("blogposts");
  const blogposts = blogpostFilenames
    .reverse()
    .filter((filename) => filename !== `template.md`)
    .map((fileName) => {
      const readBlogFile = fs.readFileSync(`blogposts/${fileName}`, "utf-8");
      const {
        data: { date, image, imgAlt, imgHeight, imgWidth, slug, summary, title },
        content,
      } = matter(readBlogFile);
      return {
        content,
        date,
        image,
        imgAlt,
        imgHeight,
        imgWidth,
        slug,
        summary,
        title,
      };
    });

  return blogposts;
};

export { getAllBlogPosts };

When doing a yarn build I'm getting the following error message:
yarn run v1.22.18
$ next build
info  - Checking validity of types
info  - Creating an optimized production build
Failed to compile.

./pages/blog/_functions.ts
Module not found: Can't resolve 'fs' in '/home/george/code/myblog/pages/blog'

I'm only calling the getAllBlogPosts function from these two functions. Using yarn dev everything works as expected. I want to keep it in a separate file, because in the future other pages will use it.
Any tips on how to fix this? Ty!

A: Having a module with shared functions inside the 'pages' directory seems like a bad idea. NextJS will assume that every file in 'pages' should be compiled as if it was a page.
I just created a tiny server with a shared function to read a text file using fs, and called that from getStaticProps/getStaticPaths/getServerSideProps with no issues. I was having trouble getting the error at all. Then I simply copied the shared module (which I'd put above the pages directory) into 'pages' and got exactly your error.


text:
Q: Spring boot 1.5.8 with jakson 2.10.0 object mapping issue i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.
when i am passing request body on springboot controller having propertyname cityCode
sample json
{
cityCode:DEL
}

when adding jsonproperty mapping works fine
@JsonProperty("cityCode")
private String cityCode;

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is
{
cityCode:DEL
}

it assing
object{cityCode=null}

please let me know if there is any property which i need to add on spring boot
because in most of my scenario i don't want to add @JsonProperty annotation to class fields
EDIT:
I enable log.level to trace i saw some message related to jackson
POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.
EDIT2:
Adding Sample Model Class
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}

on the controller method is being passed as
@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest

A: I haven't tried but maybe you can try changing the naming strategy to lowerCamelCase:
@JsonNaming(PropertyNamingStrategy.lowerCamelCase.class)
public class City {
    private String cityCode;
}

A: You might want to give this a try as an app property to configure Jackson globally.
spring.jackson.property-naming-strategy=LOWER_CAMEL_CASE

A: I have used one java api on spring-boot application where object mapper naming strategy is being set to upper_camel_case.
since that class imported on App.java(@SpringBootApplication) upper_camel_case strategy being applied globally.
to fix this globally imposed upper_camel_case strategy i have override the object mapper configuration on App.java and removed
objectMapper.setPropertyNamingStrategy(new UpperCamelCaseStrategy());

now i am able to use default naming strategy on application.


text:
Q: Butterknife does not work with Include tag I have a CoordinatorLayout where I have my Button:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom|end">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="16dp"
        android:layout_marginRight="16dp"
        android:src="@drawable/icon"
        app:fabSize="normal"/>

</android.support.design.widget.CoordinatorLayout>

And then I have the Activity xml where I include the Button:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    ...

        <include
            android:id="@+id/fabHere"
            layout="@layout/fab_here"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

</LinearLayout>

And here I have a fragment with Butterknife:
public class MyFragment extends Fragment {
....
@BindView(R.id.fab) FloatingActionButton fab;

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.my_fragment, container, false);
            ButterKnife.bind(this, view);

            return view;
    }
...
 }

But if I start the App this appears:
java.lang.IllegalStateException: Required view 'fab' with ID 2131624072 for field 'fabHere' was not found. If this view is optional add '@Nullable' (fields) or '@Optional' (methods) annotation.
I tried to add the '@Nullable' and '@Optional' annotations, but it does not work

A: The MainActivity,
public MainActivity extends AppCompatActivity {
    // 1. First, we declare the layout that was included as a View objects.
    @BindView( R.id.layout_1 ) View layout_1;
    @BindView( R.id.layout_2 ) View layout_2;

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        // 2. In here, we bind the included layouts
        ButterKnife.bind( this );

        // 4. Then, we create objects of the type of the IncludedLayout.
        //      In this example the layout reuse the same layout twice, so, there are two
        //      IncludedLayouts.
        IncludedLayout includedLayout_1 = new IncludedLayout();
        IncludedLayout includedLayout_2 = new IncludedLayout();

        // 5. We bind the elements of the included layouts.
        ButterKnife.bind( includedLayout_1, layout_1 );
        ButterKnife.bind( includedLayout_2, layout_2 );

        // 6. And, finally, we use them.
        includedLayout_1.displayed_text.setText(  "Hello" );
        includedLayout_2.displayed_text.setText(  "Hey!" );
    }

    // 3. We create a static class that will be an container of the elements
    //     of the included layout. In here we declare the components that
    //     hold this. In this example, there is only one TextView.
    static class IncludedLayout {
        @BindView( R.id.displayed_text ) TextView displayed_text;
    }
}

The XML of the MainActivity:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <include android:id="@+id/layout_1" layout="@layout/included_layout" />
        <include android:id="@+id/layout_2" layout="@layout/included_layout" />
</LinearLayout>

The XML of the Included Layout:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/displayed_text"/>
</LinearLayout>

That's it!
Credit : Reference

A: Simply remove the id from the include tag and the binding will work, even for the fields in the included layout.

A: Please visit Butterknife issue
The author @JakeWharton says -
Put an ID on the <include> and bind it to an arbitrary View field for each one.
Then create an object which binds the inner views

static class Something {
  @Bind(R.id.something) TextView somethingView;
}

You can then create multiple instances of that object
and call ButterKnife.bind(something1, include1) and
ButterKnife.bind(something2, include2) and so on.

Consider also just making a custom view instead of using <include> which has
proper APIs to get its children (or at least binds them to fields itself).

A: I Suggest you to use Data Binding Library provided by Google instead of Butterknife

A: Since this question is quite old.
I am able to connect to my id in include tag nowadays (2019/Oct).
Try to do something like the original question before you go deeply.
@BindView(R.id.your_button_id_inside_include_tag) Button button;


text:
Q: How to build an archived package on R 3.0.0 Recently R 3.0.0 was rolled out.  One of the requirements was that "Packages need to be (re-)installed under this version (3.0.0) of R."
The problem occurs when you have packages that have been archived.  In an OS independent way how do you build packages like uroot?  As you can see the package is archived.

A: The easiest way to build a package from the archive is to use devtools:
library(devtools)
install_url("http://cran.r-project.org/src/contrib/Archive/uroot/uroot_1.4.tar.gz")

There are three challenges:

*

*You need to have a working development environment. On windows, this means you need Rtools; on the mac, the xcode command line tools; and on linux, the appropriate development packages

*There is currently a bug in devtools which means it doesn't find the right version of Rtools on windows. A fix is on its way to CRAN.

*There's normally a good reason that a package has been put in the archive: it's likely that it does not pass R CMD check in the current version of R, so even once you've installed it, it might not work correctly. Be careful!


text:
Q: Failure when recovering from hibernation with encrypted drive on Ubuntu 20.04. Swapfile priority? I used to hibernate on my laptop whose disk is encrypted, under Ubuntu 20.04, following the instruction given in Install Ubuntu 19.10 with encrypted swap/home partitions, specifying manually the swap partition and Hibernate and resume from a swap file (except that I didn't manage to make it work before Ubuntu 20.04 because of NVIDIA drivers issues...).
But for some times, it does not work anymore: at recovering, after I type my encryption password, it hangs forever.
The first problem that I have is that I don't really know how to "debug" this issue.
Then I wonder if the problem could come from swap priority. When I compare to what is in Install Ubuntu 19.10 with encrypted swap/home partitions, specifying manually the swap partition, my priorities are in wrong order.
root@is241395:~# swapon
NAME      TYPE      SIZE USED PRIO
/swapfile file       40G   0B   -3
/dev/dm-2 partition 980M   0B   -2

It is possible that my problem is due to this. How to update these priorities (I am not sure I understand the relation with fstab)?

A: I can at least answer the question about how to change swap priorities.  You can set this manually in your /etc/fstab.  If you want to prefer using your swapfile, edit /etc/fstab for the line that contains your swapfile mount.  Looking at your link, it looks like you probably have something in the form of:
/swapfile                   none            swap    sw              0       0

Change it to:
/swapfile                   none            swap    sw,pri=1       0       0

Reboot and your machine should prefer to use the swapfile over the partition.


text:
Q: how to export a mapbox studio map as .mbtiles file So I'm guessing the answer to this is "no", but is there any way to export a map I've designed online with mapbox studio (https://www.mapbox.com/studio/) into a .mbtiles file so I can host it myself?
Honestly, I'd be willing to pay money for this (saving me the trouble of getting a world .pbf file and getting it into a postgresql db is really a pain, especially with a mediocre computer like mine)
It sounds like maybe there used to be a way to do this, but as of now it looks like they've taken away this ability.  I can see a lot of different ways to use a map I've created, but everything forces me to use mapbox as the hosting service... it seems there's no way to download a map I've created.

A: I think your assumption is correct. It does seem MapBox wants you to use their APIs and API keys.
However, there is a partial solution with raster tiles if you can fallback to that. Or you can get vector mbtiles from OSM data instead of from mapbox servers.
mapbox offline support for android/ios
I've contacted mapbox support in April 2017, and what I've been told is that although the style files that you can download from MapBox studio don't contain tiles, there's a way to have them render offline on Android/iOS.

If you would like to use Mapbox maps offline, you would need to follow the examples shown for Android or iOS, depending on your platform. Essentially, the mobile SDKs take in a style URL that points to your custom style created in Mapbox Studio, and the SDKs handle the downloading of all other resources needed to keep the map offline (fonts, icons, tilesets, etc). Check out our guide on offline maps to read more about how this works.

Links:

*

*Offline Maps with MapBox

*Mapbox Android-SDK Offline example

*Mapbox iOS-SDK Offline Example
From a quick look at the example code, it would seem that the downloading of the tiles is done within the App, but done ahead of time, for instance just after you install the app and you still have
network connectivity. I don't immediately see whether or not your Mapbox API keys are involved at all in this download, with respect to your billing concern. There is a 6000 offline tile limit per offline region.
Not for desktop: The site also mentions that offline is not an option for MapboxGl-JS, so you'd have to hack it up to make your offline region available on desktop web browsers.
mapbox studio export as mbtiles...
There was supposedly a non obvious option in settings to download your source as an mbtiles file in mapbox studio classic. A mapbox classic issue on github has a screenshot of where the button should be. It's possible that option is gone now.
That github project, https://github.com/klokantech/vector-tiles-sample,  provides links to projects/tools that can break the mbtiles file into its contained pbf files, which are a protobuf compressed format for each vectorial tile (https://github.com/mapbox/mbutil). Slightly outdated.
An approach which might otherwise work, is to cache the network requests ahead of time for each tile retrieved from MapBox, and then in your APP proxy the requests to your cache. I'm not sure whether that's against the ToS though. You'd probably have to do it programmatically with all XYZ coords you wish to cache.
Taking a dive with tippecanoe to produce vector tiles
You can create vector tiles with tippecanoe (and host them yourself). It's not MapBox, I know. But it might get your farther in the long run.
Nice short blog article about it: http://fuzzytolerance.info/blog/2017/02/02/Making-your-own-tiles-with-Tippecanoe/
The mbtiles you create, you can layer them, and possibly style them with the open source maputnik (which is somewhat like the style editor of mapbox). Then you take serve mbtiles with your own server, and plug in your style into mapboxGL-js or openlayers.
TileMill -- (.mbtiles with raster tiles) fallback
There is TileMill which is still available (but deprecated), runs on the desktop, and will allow you to create maps from shapefiles (e.g. you can get openstreetmap shapefiles for single cities at https://mapzen.com/data/metro-extracts/ ).
TileMill, will give you a mbtiles file at the end of the process. Although, that mbtiles contains raster tiles, not vector tiles. Vector tiles can be styled dynamically so it's nice on mobile when you want to accommodate various situations with fonts or adapt lighting.
Raster tiles might suffice, because in your app you probably will be able to render other interactive objects on top of that base layer. OpenLayers is one portable framework where you'd be able to do that, for instance -- allowing the user to draw objects or click points of interest that you've loaded from a database separately from the map data.
Get OSM-based vector tiles instead of mapbox
There seems to be an alternative maker of Vector tiles now, http://openmaptiles.org (used to be http://osm2vectortiles.org ).
You can go here, and download an mbtiles file for a city of your choice for instance: https://openmaptiles.org/downloads/#city , then serve that file (locally) for your app with a tile server. (or use one of the tools mentioned above to break it into the individual pbf files and read the files from local disk / memory)
With this approach, you combine a vector mbtiles from OSM, with the style you've created in mapbox studio (mapbox studio lets you download a zip file with your .json style in it), and you can still use MapBoxGL to display it.
There's Maputnik http://maputnik.com/ which you can use to edit a mapboxgl style file (the editor works with local storage). and there's presumably https://github.com/boundlessgeo/ol-mapbox-style which allows you to convert that style into a piece of code suitable for OpenLayer's style API.

A: As far as I know Mapbox does not provide map downloads. You could download vector maps directly using their vector tiles API and be charged against your vector tile count. 200K tiles are free per month. In my experimentation, 80K tiles represent about 200 sqaure km of area. So you'd run out of free tiles very quickly for large areas and would have to pay 1$ per about every 10km more of square km area. (all very approx values based on nominal observation). Also, these leaves the challenge to actually package the .mvt files into a MBTiles format.
I suggest an alternative way instead.
You can create MBTiles from any .osm.pbf file using this tool - https://github.com/systemed/tilemaker

*

*Download .osm.pbf file from Geofabric. To download for a custom area, you can use Protomaps or BBBike Extract

*Download tilemaker

*Execute the following command
tilemaker --input netherlands.osm.pbf --output netherlands.mbtiles --process resources/process-openmaptiles.lua --config resources/config-openmaptiles.json

You can read more about it in this blog post - https://blog.kleunen.nl/blog/tilemaker-generate-map

*To use the same style that you created in Mapbox Studio, you can download your style's JSON file by clicking on Share -> Download. This zip will contain your JSON file which describes all the colors, etc you customised.

If you are planning to show this MBTile on Android app, you'll just have to embed this JSON that you downloaded and the MBTiles file in the app and point the JSON to the MBTiles file. I've written how to do this in this blogpost. I tried to make the JSON work but only partly succeed after some edits. However ideally it should work since its based on the openmaptiles schema.


text:
Q: Graphing a multi variable function in MATLAB I have never used MATLAB before, so I am very lost. For my calculus class, we were tasked with finding a certain function and then using MATLAB to graph it. Finding the function was no problem. However, trying to graph it has me pulling my hair out. The function is z(x,y)= xy(x+y)(2x+y)(3x+y)(x-2y)(x-3y)(x-4y). Any help or advice is GREATLY appreciated.

A: You can define a anonymous function handle.
% define function
% .* denotes element wise multiplication
f = @(x,y) x.*y.*(x+y).*(2*x+y).*(3*x+y).*(x-2*y).*(x-3*y).*(x-4*y);

% define range and resolution for x and y
x = -20:0.5:20;
y = -20:0.5:20;

% create meshgrid for 3d plotting
[X, Y] = meshgrid(x,y);

% calculate z values (for meshgrid)
z = f(X, Y);

% plot the function
figure()
surf(x,y,z)

To explain further, since you want to calculate the z value for x and y pairs, you should use a element wise multiplication .*.
Then you have to create a meshgrid for the x and y values, to have all the possible x and y pairs in the two new matrices X and Y. Providing these to your function will calculate the corresponding z value for all these pairs. You can use these for plotting, e.g. surf.


text:
Q: Break a while(true) dependency from class A that depends on class B Consider the following class that just gets an IP and port number  :
package view;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/**
 * Server side
 * @author X
 *
 */
class ServerConnector implements ActionListener
{

    private JFrame m_frame = null;
    private JTextField m_serverIP;
    private JTextField m_serverPort; // you can use also JPasswordField
    private JButton m_submitButton;

    // location of the jframe
    private final int m_centerX = 500;
    private final int m_centerY = 300;

    // dimensions of the jframe
    private final int m_sizeX = 1650;
    private final int m_sizeY = 150;

    private String m_ip;
    private String m_port;

    private boolean ready = false;

    /**
     * Ctor
     */
    ServerConnector()
    {
        m_frame = new JFrame("Sever Side Listener");
        m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        m_serverIP = new JTextField(20);
        m_serverPort = new JTextField(20);

        JPanel gui = new JPanel(new BorderLayout(3,3));
        gui.setBorder(new EmptyBorder(5,5,5,5));
        gui.setSize(m_sizeX , m_sizeY);
        m_frame.setContentPane(gui);

        JPanel labels = new JPanel(new GridLayout(0,1));
        JPanel controls = new JPanel(new GridLayout(0,1));
        gui.add(labels, BorderLayout.WEST);
        gui.add(controls, BorderLayout.CENTER);

        labels.add(new JLabel("Server IP: "));
        controls.add(m_serverIP);
        labels.add(new JLabel("Server Port: "));
        controls.add(m_serverPort);
        m_submitButton = new JButton("Start Listening");
        m_submitButton.addActionListener(this);

        gui.add(m_submitButton, BorderLayout.SOUTH);
        m_frame.setLocation(m_centerX , m_centerY);
        m_frame.setSize(m_sizeX , m_sizeY);
        m_frame.pack();
        m_frame.setVisible(true);
    }

    public static void main(String[] args) {
        new ServerConnector();
    }

    @Override
    public void actionPerformed(ActionEvent event) {

        Object object = event.getSource();
        if (object == this.m_submitButton)
        {
            // grab all values from the connection box
            // if one of them is missing then display an alert message

            String ip = this.m_serverIP.getText().trim();
            String port = this.m_serverPort.getText().trim();

            if (ip.length() == 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter IP address !");
                return;
            }

            if (port.length() == 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter Port number!");
                return;
            }

            int s_port = 0;

            try
            {
                // try parse the Port number
                // throws exception when an incorrect IP address
                // is entered , and caught in the catch block
                s_port = Integer.parseInt(port);
            }

            catch(Exception exp)
            {
                JOptionPane.showMessageDialog(null, "Port number is incorrect!");
                return;
            }

            try
            {
                // try parse the IP address
                // throws exception when an incorrect IP address
                // is entered , and caught in the catch block
                InetAddress.getByName(ip);
            }

            catch(Exception exp)
            {
                JOptionPane.showMessageDialog(null, "IP address is incorrect!");
                return;
            }

            m_frame.dispose();
            this.m_ip = ip;
            this.m_port = port;
            ready = true;
            // new ServerGUI(ip , s_port);
        }

    }

    public boolean isReady()
    {
        return this.ready;
    }

    /**
     *
     * @return
     */
    public String[] getIPandPort()
    {
        String[] ipPort = new String[2];
        ipPort[0] = this.m_ip;
        ipPort[1] = this.m_port;
        return ipPort;
    }
}

And the would be controller class
public class ServerController {

    String m_ip;
    int m_port;

    public static void main(String args[])
    {
        ServerConnector sc = new ServerConnector();

        while (!sc.isReady())
        {
            // run
        }

        // get IP and port
        String[] ipPort = sc.getIPandPort();

        System.out.println("IP is :" + ipPort[0] + " and port is :" + ipPort[1]);

    }
}

For now ServerController is in a while(true) loop , until the user has entered the IP and Port.
How can I avoid this kind of dependency (avoid the while loop) ?

A: First of all, get rid of the while (true) loop as its only purpose will be to mess your code up.
A general solution is to get the information from the user in code that blocks program flow. A problem occurs, though if this is needed in a GUI that cannot have its event thread blocked.
One Swing solution is as we have discussed previously in your previous question: use a modal dialog to get the information. The modality of the dialog will halt the program flow in the calling code until the dialog is handled.
If you want to avoid use of modal dialogs, then another general event-driven solution is to use a observer design pattern -- have one object be notified by another when information or state has changed. This can be achieved easily with use of PropertyChangeSupport and PropertyChangeListeners, although there are other ways as well, including using the XxxxListeners available in the Swing library.
For example of listener use and MVC with Swing:

*

*Modifying independent JPanels from the JFrame

*Java keeps adding buttons! - JFrames

Edit
For example, changes marked with a // !! comment:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.InetAddress;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.SwingPropertyChangeSupport;

public class ServerController {

   String m_ip;
   int m_port;
   private static String[] ipPort;

   public static void main(String args[]) {
      final ServerConnector sc = new ServerConnector();

      sc.addPropertyChangeListener(new PropertyChangeListener() {
         @Override
         public void propertyChange(PropertyChangeEvent evt) {
            if (ServerConnector.READY.equals(evt.getPropertyName())) {
               if (sc.isReady()) {
                  ipPort = sc.getIPandPort();
                  System.out.println("IP is :" + ipPort[0] + " and port is :" + ipPort[1]);
               }
            }
         }
      });
   }
}

class ServerConnector implements ActionListener {
   public static final String READY = "ready"; //!!

   private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(this); //!!
   private boolean ready = false;
   private JFrame m_frame = null;
   private JTextField m_serverIP;
   private JTextField m_serverPort; // you can use also JPasswordField
   private JButton m_submitButton;

   // location of the jframe
   private final int m_centerX = 500;
   private final int m_centerY = 300;

   // dimensions of the jframe
   private final int m_sizeX = 1650;
   private final int m_sizeY = 150;

   private String m_ip;
   private String m_port;

   /**
    * Ctor
    */
   ServerConnector() {
      m_frame = new JFrame("Sever Side Listener");
      m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      m_serverIP = new JTextField(20);
      m_serverPort = new JTextField(20);

      JPanel gui = new JPanel(new BorderLayout(3, 3));
      gui.setBorder(new EmptyBorder(5, 5, 5, 5));
      gui.setSize(m_sizeX, m_sizeY);
      m_frame.setContentPane(gui);

      JPanel labels = new JPanel(new GridLayout(0, 1));
      JPanel controls = new JPanel(new GridLayout(0, 1));
      gui.add(labels, BorderLayout.WEST);
      gui.add(controls, BorderLayout.CENTER);

      labels.add(new JLabel("Server IP: "));
      controls.add(m_serverIP);
      labels.add(new JLabel("Server Port: "));
      controls.add(m_serverPort);
      m_submitButton = new JButton("Start Listening");
      m_submitButton.addActionListener(this);

      gui.add(m_submitButton, BorderLayout.SOUTH);
      m_frame.setLocation(m_centerX, m_centerY);
      m_frame.setSize(m_sizeX, m_sizeY);
      m_frame.pack();
      m_frame.setVisible(true);
   }

   public static void main(String[] args) {
      new ServerConnector();
   }

   @Override
   public void actionPerformed(ActionEvent event) {

      Object object = event.getSource();
      if (object == this.m_submitButton) {
         // grab all values from the connection box
         // if one of them is missing then display an alert message

         String ip = this.m_serverIP.getText().trim();
         String port = this.m_serverPort.getText().trim();

         if (ip.length() == 0) {
            JOptionPane.showMessageDialog(null, "Please enter IP address !");
            return;
         }

         if (port.length() == 0) {
            JOptionPane.showMessageDialog(null, "Please enter Port number!");
            return;
         }

         int s_port = 0;

         try {
            // try parse the Port number
            // throws exception when an incorrect IP address
            // is entered , and caught in the catch block
            s_port = Integer.parseInt(port);
         }

         catch (Exception exp) {
            JOptionPane.showMessageDialog(null, "Port number is incorrect!");
            return;
         }

         try {
            // try parse the IP address
            // throws exception when an incorrect IP address
            // is entered , and caught in the catch block
            InetAddress.getByName(ip);
         }

         catch (Exception exp) {
            JOptionPane.showMessageDialog(null, "IP address is incorrect!");
            return;
         }

         m_frame.dispose();
         this.m_ip = ip;
         this.m_port = port;
         setReady(true); //!!
         // !! ready = true;
         // new ServerGUI(ip , s_port);
      }

   }

   // !! added
   public void setReady(boolean ready) {
      boolean oldValue = this.ready;
      boolean newValue = ready;
      this.ready = ready;
      pcSupport.firePropertyChange(READY, oldValue, newValue);
   }

   //!! added
   public void addPropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.addPropertyChangeListener(listener);
   }

   //!! added
   public void removePropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.removePropertyChangeListener(listener);
   }

   public boolean isReady() {
      return this.ready;
   }

   /**
    *
    * @return
    */
   public String[] getIPandPort() {
      String[] ipPort = new String[2];
      ipPort[0] = this.m_ip;
      ipPort[1] = this.m_port;
      return ipPort;
   }
}


text:
Q: What is causing this syntax error with CREATE TABLE in Python SQLite3? I'm trying to create a method which creates a table if not exists.
When I try to execute this method, it returns
sqlite3.OperationalError: near "TEXT": syntax error

The method:
def create_table_if_exists(self):
    self.conn.execute(
        "CREATE TABLE IF NOT EXISTS products(NAME TEXT, URL TEXT" #"
        "ESHOP1 TEXT, CENA1 TEXT, DOPRAVA1 TEXT, STAV1 TEXT, "
        "ESHOP2 TEXT, CENA2 TEXT, DOPRAVA2 TEXT, STAV2 TEXT, "
        "ESHOP3 TEXT, CENA3 TEXT, DOPRAVA3 TEXT, STAV3 TEXT, "
        "ESHOP4 TEXT, CENA4 TEXT, DOPRAVA4 TEXT, STAV4 TEXT, "
        "ESHOP5 TEXT, CENA5 TEXT, DOPRAVA5 TEXT, STAV5 TEXT)"
    )
    self.conn.commit()

Error:
    'CREATE TABLE IF NOT EXISTS products(NAME TEXT, URL TEXT, '
sqlite3.OperationalError: near "TEXT": syntax error

I can't realize where could be the problem. Do you have any advices?

A: The problem is the missing closing paren at the end. The error is, for some reason, only showing you the first line of the query.
For multi line strings, I would recommend using the multi-line ''' quotes to make it easier to read.  That, plus proper indentation of your SQL statements, will avoid this sort of syntax errors in the future.
def create_table_if_exists(self):
    self.conn.execute(conn.execute('''
        CREATE TABLE IF NOT EXISTS products(
            NAME TEXT,
            URL TEXT,
            ESHOP1 TEXT, CENA1 TEXT, DOPRAVA1 TEXT, STAV1 TEXT,
            ESHOP2 TEXT, CENA2 TEXT, DOPRAVA2 TEXT, STAV2 TEXT,
            ESHOP3 TEXT, CENA3 TEXT, DOPRAVA3 TEXT, STAV3 TEXT,
            ESHOP4 TEXT, CENA4 TEXT, DOPRAVA4 TEXT, STAV4 TEXT,
            ESHOP5 TEXT, CENA5 TEXT, DOPRAVA5 TEXT, STAV5 TEXT
        )
    ''')
    self.conn.commit()


text:
Q: Free jqGrid 4.9.0 - How to get the original value of an inline editing for the row I'm currently trying to do an inline editing for a given row in the grid.  Since the double click opens all the columns that are "editable" on a given row, the "save" operation is sending back to the server the entire values to be updated, not just those who got actually changed.
In order not to send the server redundant updates, I would like to "compare" the values before the update and after.  So that I can only send the server the columns who actually got changed.
What is the best way to achieve that, and how do I get the original row values in order to make the comparison.
Thank you,

A: I find the question interesting. I post below an example of the implementation of your requirements. I didn't wrote the problem in the common case to make the code a little shorter. I suggest you to define serializeSaveData callback used by inline editing. You can specify it inside of inlineEditing parameter of the grid for example (see the documentation):
inlineEditing: {
    serializeSaveData: function (postData) {
        var data = $.extend({}, postData), // make copy of input data
            p = $(this).jqGrid("getGridParam"),
            savedRow = p.savedRow, iColByName = p.iColByName, colModel = p.colModel,
            i, l = savedRow.length, prop, oldData, cm, iCol, v;
        for (i = 0; i < l ; i++) {
            // below we suppose that idname of postData is deafult - id
            // to make the code more simple.
            // One can use p.prmNames.oper or p.keyName in more common case
            if (savedRow[i].id === postData.id) {
                oldData = savedRow[i];
                for (prop in oldData) {
                    if (oldData.hasOwnProperty(prop)) {
                        iCol = iColByName[prop];
                        if (iCol !== undefined && colModel[iCol] != null) {
                            cm = colModel[iCol];
                            v = oldData[prop];
                            if (cm.formatter === "date" && (cm.formatoptions || {}).sendFormatted !== true) {
                                v = $.unformat.date.call(this, v, cm);
                            }
                            if (v === data[prop]) {
                                delete data[prop];
                            }
                        }
                    }
                }
            }
        }
        return data; // object with oper, id and modified propertied
    }
}

The above code examine the data which will be send to the server after editing and remove all properties which are not modified. The server code should of cause don't interpret the data as NULL values.


text:
Q: Azure Blob: How to grant a mobile app limited access to user-specific data I have a mobile app (Xamarin Android & iOS) that connects to a website (ASP.NET MVC). Some of the content for the mobile app (files & images) comes from an Azure Blob store that currently has public read-access enabled.
I am building an authentication module for the app (OAuth, with username/password). Is it possible to somehow build authentication into my Azure Blob account as well, so that a user would only have access to their specific files?  I know that I could use the website as an intermediary (ie. user authenticates and connects to website, websites connects to azure & retrieves data and returns it to app) but this will add an extra step of lag as opposed to just connecting to Azure Blob directly.
I see that Azure Blob supports a shared access signature (SAS) tokens. Is it possible to generate a SAS token just for the subset of files relevant to that user? I imagine the workflow would be:

*

*mobile app authenticates to website api

*website generates and return SAS token for blob access

*mobile app connects to azure blob directly using SAS token.

Would that even be a good idea? Any other suggestions?

A: From what I understand of your scenario, you could use either Azure AD or SAS for authentication/authorization to Blob storage. The key will be to organize your users' data by container, so that you can restrict access to that container. This type of design will align best with how authorization is handled in Azure Storage today.
So for example, you would create a container for user1's data, another container for user2's data, and so on.
If you are already using Azure AD to authenticate and authorize your users for your application, then you may be able to simply assign an RBAC role that is scoped to the user's container for each user. For example, you can assign the Storage Blob Data Contributor role to user1 for container1, then do the same for user2 on container2. See Use the Azure portal to assign an Azure role for access to blob and queue data for information about how to do this in the Azure portal; you can also use PowerShell or Azure CLI.
Note that an RBAC role cannot be scoped to an individual blob, but only at the container level or above.
If you determine that you need to use SAS, you can create a SAS for each user that is restricted to their container. If your users are already authenticating/authorizing to your application with Azure AD, then you probably don't need to use SAS. The SAS would be useful in the case where you need to grant access to a user that is not otherwise authenticated.


text:
Q: Can I use single variable for method that returns 2 parameters I have a simple question - can I use single value assignment while method returns 2 values (val and error)?
resp := http.Get("http://www.google.com/")

A: The number of operands on the left side of the assignment must match the number of values returned by the function.
You can use the blank identifier to ignore a return value:
resp, _ := http.Get("http://www.google.com/")

It's bad practice to ignore errors like this.

A: From Go language specification :

A tuple assignment assigns the individual elements of a multi-valued
  operation to a list of variables. There are two forms. In the first,
  the right hand operand is a single multi-valued expression such as a
  function call, a channel or map operation, or a type assertion. The
  number of operands on the left hand side must match the number of
  values.

For instance, if f is a function returning two values,
x, y = f() assigns the first value to x and the second to y.

The blank identifier provides a way to ignore right-hand side values
  in an assignment:

_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value


text:
Q: matmul input operand 1 has amismatch in its core dimension error 0 when trying to run sklearn linear regression The error is ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)(size 8758 is different from 1)
import os
import pickle
from sklearn.linear_model import LinearRegression
import numpy as np
import sys
import time

def BowtoArray(bow):
    bow = bow.split(",") #the bag of words will always be a string of numbers separated by commas
    final = [int(i) for i in bow]
    final = np.array(final)
    return(final)

TruthModel = pickle.load(open("TruthAI.p","rb"))
BiasModel = pickle.load(open("BiasAI.p","rb"))
BOW = sys.argv[1] #the bag of words is passed into terminal

BOW = BowtoArray(BOW)

BOW = BOW.reshape(-1,1)
Score = [TruthModel.predict(BOW), BiasModel.predict(BOW)]

f = open("pyTest.txt", "w")
f.write(str(Score))
f.close()

sys.exit()