text:
Q: Can you use variable and/or functions from a separate Python file in LaTeX? I am considering learning LaTex, and my choice will depend on how I might be able to use it with Python.
I am aware of PythonTeX, which lets you use Python code within a LaTeX document.
But is there a way to write the code in a separate .py file, and the somehow import the functions and variable to a LaTeX document to use the results? These results can be int, float or matplotlib plots.
It would be practical to keep the text and the Python code separate but use the results without manually copy/pasting them into the LaTeX document.

A: I'm not entirely sure how to answer that so let me start from the very start.
Fundamentally, Latex is a language that allows you two define, format, and write text documents. You don't have objects and functions like in most programming languages. In the end, it is compiled to a static document.
Therefore, I'm not sure why you are interested in a python integration.
You could write a Python program that generates a static tex file, which is then compiled to a pdf (if you use pdflatex). But that is cumbersome and more work than writing the latex file in the first place.
There might be an edge case where dynamic programming elements are useful, but tex does support some basic programming capabilities. SO, I don't really see how it could be useful.
Besides the question of usefulness, I understand that some people use Python to generate data/plots for their documents.
Most people I know, generate plots/data with python and then import the plots or csv files in latex. There is no copy/pasting involved.
I've seen that PythonTex is designed for cases where you would like to add pyhton code to your document, which is fine. However, as it is in most programming languages, I wouldn't recommend having one large file containing all the code. It's just bad practice.
But, if you use separate tex file anyway, there is no benefit over having separate python and tex files. You can automate the compilation process with  MAKE or CMAKE (or any other building environment of your choice).
To answer your question, I don't think there is a Python integration in Latex besides PythonTex. I don't think that you could use an \import or \include command within the pycode environment. (I haven't tested it though).
SO I don't see how you can do it from a latex side. Having said that, you might be able to import from a file with Python code within a latex document. (see here).
If I can give you a personal advice: I would recommend learning Latex, if you write a large document (book, thesis, ..) or publications (conferences or journals). Latex looks generally better and is more stable than MS Word/Libreoffice/Openoffice. YES, it is awkward to learn and has a steep learning curve. But it works well.
I, personally, use it for most of my documents in personal and professional life.
I use MAKE files to compile my documents (which includes: running simulations written in C, executing R files, generate tables and plots, and finally compile tex).
It works well.

A: The sagetex package gives you access to a computer algebra system, Sage, as well as Python programming. It will let you use string data from an external Python file as seen in my answer to  Can we import Python file in latex?. I am unable to get it to pass variables or functions, however, from an external file. The ability to pass a string of LaTeX code is quite useful. I take that approach (not using an external file) in many problems. See my approach to plotting the  Cantor function where the output string is created using Python and Sage and inserted via \sagestr. This gives you LaTeX quality plots for your data. A similar idea of creating a Trig table here using Python/Sage to create the string quickly and easily gets the heavy lifting  done.
With respect to matplotlib see here; its not done using an external file though. It's easy enough to use Python within LaTeX, for example, blurring an image. In an integrated environment though you can combine Sage calculations plus Python programming to increase the accuracy of a tikz plot. Since you're getting a CAS, sagetex gives you even more tools for mathematical programming.
The Cocalc platform "supports running Python, SageMath, R Statistical Software, Julia, and more in the same project as your LaTeX document.", It also supports pythontex and sagetex. There's also a lot of support for Python even if you aren't going to use LaTeX.
You can do a lot with Python raw strings from an external Python file. When working with Python is easy from within LaTeX, however, I think working with Python using external files would be a bit cumbersome.


text:
Q: Generating Functions To Deal With I've been working on producing a closed-form generating function for the
coefficients $a_n = \binom{n}{2}.$ I was wondering what might be a good
procedure to start on this. I get that
$$\sum_{n=0}^{\infty} x^n = x^0 + x^1 + x^2 + ... = \frac{1}{1-x}$$
by the convergence of geometric series. However, I'm wondering what might be
the proper steps to get LHS to look like $\sum_{n=0}^{\infty} \binom{n}{2}x^n.$
Unfortunately, I have a general lack of familiarity with discrete math, so any
help would be greatly appreciated.

A: Differentiate term-by-term twice:
$$
\begin{aligned}
\frac{d}{dx} \sum_{n=0}^\infty x^n
&= \sum_{n=1}^\infty n x^{n-1} \\
\frac{d^2}{dx^2} \sum_{n=0}^\infty x^n
&= \sum_{n=2}^\infty n(n-1) x^{n-2}.
\end{aligned}
$$
Next, since $a_n = \binom{n}{2} = \frac{n(n-1)}{2}$ and $a_0 = a_1 = 0$, we have
$$
\begin{aligned}
\sum_{n=0}^\infty a_n x^n
&= a_0 + a_1 x + \sum_{n=2}^\infty \frac{n (n - 1)}{2} x^n \\
&= \frac{x^2}{2} \sum_{n=2}^\infty n (n-1) x^{n-2} \\
&= \frac{x^2}{2} \frac{d^2}{dx^2} \sum_{n=0}^\infty x^n \\
&= \frac{x^2}{2} \frac{d^2}{dx^2} \frac{1}{1-x} \\
&= -\frac{x^2}{\left(1 - x\right)^3}.
\end{aligned}
$$

A: You know that $\dbinom{n}{2} = \dfrac{n(n-1)}{2}$.
Start with the geometric series formula: $$\displaystyle\sum_{n = 0}^{\infty}x^n = \dfrac{1}{1-x}.$$
Next, differentiate both sides with respect to $x$: $$\displaystyle\sum_{n = 1}^{\infty}nx^{n-1} = \dfrac{1}{(1-x)^2}.$$
Note that the $n = 0$ term disapears since $x^0 = 1$ is a constant. Now, you got the $n$ factor, but you still need the $n-1$ factor. So differentiate again to get: $$\displaystyle\sum_{n = 2}^{\infty}n(n-1)x^{n-2} = \dfrac{1}{(1-x)^3}.$$
This is almost what you need. Can you figure out how to manipulate both sides to get $$\displaystyle\sum_{n = 0}^{\infty}\dfrac{n(n-1)}{2}x^n = ?$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: session_is_registered results in 404 - nginx I'm having a problem with nginx it seems, I'm trying to use this code:
<?php session_start();
if(!session_is_registered(sessionvalue)){
header("location: login.php");
}
?>

Which is part of some simple login, as soon as I insert this in the page that is to be protected, I can't open it anymore and receive 404 Not Found. If I remove that bit of code it works without any hitch.
//Edit:
Turned out I was over PHP 5.4.0 so code has been changed to:
if(!isset($_SESSION['sessionvalue'])

But the error persists, 404 not found.

A: Try /login.php instead of login.php
Also "Location", not "location".


text:
Q: Dynamic memory allocaion in c++ I came across two similar statements but could not exactly find the diference between them. The statements are:
int *p = new int(75);
int *p = new int[75];

Can anyone help me in knowing the difference between the above two statements.

A: The first returns a pointer to the integer with value of 75, but the second returns a pointer to the array of 75 integers, which don't have a value.


text:
Q: How to convert image from (32,32,3) to (1,3072)? (Regarding image classification)
What is the easiest way to convert a 32x32x3 image to a 1x3072 array such that 1024 are red, 1024 are green and 1024 are blue?

A: img = img.transpose(2, 0, 1)  # Depends on your original order
img = img.reshape(1, -1)

See:

*

*numpy.transpose

*numpy.reshape

A: using numpy: (arr is the image array)
swapped = np.swapaxes(arr,0,2)
flattened = swapped.flatten()

your array will be in flattened
Swapping between the first axis and the last, and then flattening the result.


text:
Q: Tensors in matrix multiplication algorithms Fast matrix multiplication algorithms, be it the Winograd and Coppersmith algorithm or any further improvement of it, extensively use tensors. In fact, the entire construction is based on tensor analysis. My question is WHY TENSORS? How do tensors help? The following links provide details of the algorithms:
http://www.cs.umd.edu/~gasarch/TOPICS/ramsey/matrixmult.pdf
http://issac-symposium.org/2014/tutorials/ISSAC2014_tutorial_handout_LeGall.pdf
Thanks!

A: Actually, matrix multiplication can be seen as a bilinear map
$$K^{n\times k}\times K^{k\times m}\rightarrow K^{n\times m},$$
where $K$ is the ground field.
Such a bilinear map can be expressed as a tensor of order 3 of format $(nk)\times (km)\times (nm)$ (any bilinear map $K^{\ell_1}\times K^{\ell_2}\rightarrow K^{\ell_3}$ can be represented by a tensor of format $\ell_1\times\ell_2\times\ell_3$).
The number of (non-commutative) multiplications required to compute the bilinear map then corresponds to the rank of this tensor of order 3. This number of multiplications corresponds to the "order" of recursive algorithms to compute this bilinear map. For instance, Strassen's algorithm corresponds to a rank 7 decomposition of the tensor associated to the multiplication of $2\times 2$ matrices, leading to a general algorithm for multiplying $n\times n$ matrices with complexity $O(n^{\log_2(7)})$.
You may be interested in the following classical reference that explains well this relationship: the book "Algebraic Complexity Theory" by Burgisser, Clausen and Shokrollahi.


text:
Q: Need help implementing object constructor I need an object constructor, but I"m cofused with how classes, types, collecitons etc work in VBA
The object supposed like this:
obj
    name
        value = ""
        tag = "name"
    id
        value = ""
        tag = "id"
    address
        value = ""
        tag = "address"

    ...

    nthProp
        value = ""
        tag = "nthProp"

Where value is an empty string to populate later and tag is a string that is the same as the property name.


text:
Q: How can I call Test class ctor with params? I have unit test class and a static main entry method.
I know this is how I run the test class from my main method:
public class SingleJUnitTestRunner {

    public static void main(String... args) throws ClassNotFoundException
    {

        String[] classAndMethod = args[0].split("#");

        Request request = Request.method(Class.forName(classAndMethod[0]), classAndMethod[1]);

        Result result = new JUnitCore().run(request);

        System.exit(result.wasSuccessful() ? 0 : 1);
    }
}

Is there a way to call a test-calls ctor with params and then run the tests?

A: I took a look at the Junit source code and came up with this:
public static void main(String... args) throws ClassNotFoundException {
    String[] classAndMethod = args[0].split("#");
    Object[] parameters = new Object[] {"constructor parameter"};

    Class<?> className = Class.forName(classAndMethod[0]);
    String methodName = classAndMethod[1];

    Request request = createRequest(parameters, className, methodName);

    Result result = new JUnitCore().run(request);

    System.exit(result.wasSuccessful() ? 0 : 1);
}

private static Request createRequest(Object[] parameters, Class<?> className, String methodName) {
        Description method = Description.createTestDescription(className, methodName);
        return new ConstructorParameterRequest(className, parameters).filterWith(method);
}

Custom Request class so that we can use our own runner:
public class ConstructorParameterRequest extends Request {

    private Class<?> clazz;
    private Object[] parameters;

    public ConstructorParameterRequest(Class<?> clazz, Object[] parameters) {
        this.clazz = clazz;
        this.parameters = parameters;
    }

    @Override
    public Runner getRunner() {
        try {
            return new ConstructorParameterRunner(clazz, parameters);
        } catch (Throwable e) {
            return new ErrorReportingRunner(clazz, e);
        }
    }

}

Custom Runner class which creates the test class with constructor parameters. validateConstructor has to be overriden because BlockJUnit4ClassRunner checks for a zero argument constructor:
public class ConstructorParameterRunner extends BlockJUnit4ClassRunner {

    private Object[] parameters;

    public ConstructorParameterRunner(Class<?> clazz, Object[] parameters) throws InitializationError  {
        super(clazz);
        this.parameters = parameters;
    }

    @Override
    protected void validateConstructor(List<Throwable> errors) {
        validateOnlyOneConstructor(errors);
    }

    @Override
    protected Object createTest() throws Exception {
        return getTestClass().getOnlyConstructor().newInstance(parameters);
    }

}


text:
Q: hide divs and remember on page change/refresh I have 3 divs on a page:
header-div
fixed_menu_div
page_cont

here is the CSS the divs have:
#header-div {
    top:0;
    left:0;
    display:inline;
    float:left;
}

#page_cont {
    margin-left:200px;
    height:80%;
}

#fixed_menu_div {
    width:200px;
    height:80%;
    float:left;
    left:0;
    overflow-x:none;
    overflow-y:scroll;
    position:fixed;
}

i want to have links on the header_div and fixed_menu_div which will hide them and save the state (show or hide) if the page is changed on refreshed and then make the page_cont div 100% wide

A: You can store the state of you divs (show/hide) in a cookie and reevaluate the cookie on page load/refresh.
Here is a link to help you manipulate cookies with js : w3schools.com/js/js_cookies.asp

A: You need to store the visible state of your elements in database using ajax calls. Cookies can be cleaned so I wont recommend that.
You can then use the following methiod to show and hide the elements.
$(document).ready(function(){
   $('#page_cont').css('width','100%');
   //retrive the values from database with 1 as visible and 0 as invisible
   setVisibility(1,0,1);
});

function setVisibility(header_div_visibility,page_cont_visibility,fixed_menu_div_visibility){
    (header_div_visibility===1)?$('#header-div').show():$('#header-div').hide();
    (page_cont_visibility===1) ? $('#page_cont').show():$('#page_cont').hide();
    (fixed_menu_div_visibility===1) ? $('#fixed_menu_div').show():$('#fixed_menu_div').hide();
}


text:
Q: Show function is equal to series How do we show that the equation:
$$f(x) = \frac{9}{(x-1)(x+2)^2}$$
is equal to the series:
$$\sum_{n=0}^{\infty}[(-1)-\frac{{(-1)}^{n}}{2^{n+1}} - \frac{3(-1)^n(n+1)}{2^{n+2}}]x^n$$
I have tried differentiating it, but i feel that it is an incorrect approach. I am confused on the method which is required to be taken to solve this problem. The approach required to be taken for this problem is sufficient :)
This is part 2 of my question: Find constants of function - Partial fraction decomposition
Thank you!

A: Hint.  Use partial fractions to write
$$\frac{9}{(x-1)(x+2)^2}=\frac{A}{x-1}+\frac{B}{(x+2)^2}+\frac{C}{x+2}$$
for constants $A,B,C$, then use known series for the terms on the right hand side.

A: Use the results of your previous question.
Then,
$$f(x) = \frac{A}{(x-1)} + \frac{B}{(x+2)} + \frac{C}{(x+2)^{2}} $$
and use the fact that:
$$
 \frac 1{a-x} = \sum_{n=0}^\infty a^{-n-1}x^n\\
\frac 1{(a-x)^2} = \sum_{n=0}^\infty (n+1)a^{-n-2}x^n.
$$

A: You already know partial fraction decomposition. Now consider $\frac{1}{x+a}=\frac{1}{a}\frac{1}{1+\frac{x}{a}}$ and expansion of geometric and binomial series.


text:
Q: How to correctly analyse a reduction in variance, and a trend towards a desired value over time? I have a dataset consisting of some integer values collected over a series of five games, and was hoping someone might be able to recommend an appropriate test to determine whether:

*

*the interquartile range of this data decreases with each subsequent data point

*the mean/median of this data gradually approaches a desired value of my choosing

The data from a single game can simply be thought of as an array of integers from 1-5 inclusive, so I essentially have a nested array with five child arrays/datapoints (I wish I could collect more but it wasn't feasible, sadly).
One approach I've considered is to just plot these values and examine the trend line visually, but it doesn't feel like a very "solid" approach - I can't exactly pull a p-value out of it to reject/accept a null hypothesis, for example.
Are there any tests I could use to achieve what I'm trying to do, or maybe transform the data somehow to do so?
Many thanks in advance. Let me know if there's any other information I can provide.


text:
Q: Bitmap does not save to gallery on some android devices On some devices following code does not save the bitmap to the gallery. I was told this is a Samsung device.
Is there any improvements I can make to resolve this issue.
protected Void doInBackground(Bitmap... data) {
        try {
            if (data.length > 0 && data[0] == null) return null;
            ContentResolver resolver = mContext.getContentResolver();
            String fileName = "XF_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + ".jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + mContext.getString(R.string.app_name));
                values.put(MediaStore.MediaColumns.IS_PENDING, 1);
            } else {
                File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_PICTURES);
                if(!directory.exists()){
                    directory.mkdirs();
                }
                File file = new File(directory, fileName);
                values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
            }

            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            OutputStream output = resolver.openOutputStream(uri);
            data[0].compress(Bitmap.CompressFormat.JPEG, 100, output);
            output.flush();
            output.close();
            Log.d("myApp", "Image saved!");

        } catch (IOException e) {
            Log.d("myApp", "Image saved!" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            Log.d("myApp", "Image saved!" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


text:
Q: Would Refreshing a Sandbox Wipe Out Certain Metadata? If I have custom-setting metadata (or any other custom objects) in a partial-copy sandbox and not in production, then I refresh the sandbox, will that metadata be wiped out and have to be recreated?
I'm working on a sandbox-refresh script and trying to determine how to handle custom settings that are in the sandbox but not in production.

A: Yes. All of the customizations in your sandbox will be lost:

When you're finished with a sandbox, you can refresh it. This process replaces the current sandbox with a new copy of your production org.

All metadata customizations will be replaced with a copy of your production Salesforce instance. Data will be copied if applicable for the sandbox type, but any data existing in the sandbox will not be preserved.
Custom Settings and Custom Metadata are copied from Production upon refresh, regardless of sandbox type.

A: On top of David's answer, wanted to provide some information around your question:

I'm working on a sandbox-refresh script and trying to determine how to handle custom settings that are in the sandbox but not in production.

With any refresh as David has highlighted, you necessarily get a replica of Production for metadata (and data if it's a partial or full copy sandbox) configurations. This would mean that you will lose all your changes in the Sandbox which are not yet migrated to Production.
For your scenario, you will need to make sure that your Custom Settings are stored as metadata say in source repository. Because you will only be able to store the metadata, you will also need to ensure that the data contained in Custom Settings are also preserved.
Then once you have refreshed your Sandbox from Production, you can then write the script to migrate those Custom Setting and the related data in your new Sandbox.


text:
Q: mysql can't be opend or restarted i have a probleme with mysql: since this morning when i try to open it with
mysql -u root -p

the answer is alway
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory")

i did allready try to use
mysql restart

or
service mysql restart

but it don't do work either and this mysql.sock file dosent exist.

A: Start:
sudo /etc/init.d/mysql start

Stop:
sudo /etc/init.d/mysql stop

Restart / reload configs:
sudo /etc/init.d/mysql restart

Check run status:
sudo /etc/init.d/mysql status

Then try:
Stop the current MySQL server instance:
sudo service mysql stop

Then start MySQL:
sudo service mysql start

you may also try:
the command in terminal to use mysql interpreter:
mysql -u root -p database_name

Enter your password, then you can run your mysql commands.
Another way is to use:
mysql -u root -p database_name


text:
Q: PHP extractTo does not extract files properly on one computer, but works on the other. I'm facing a very weird problem! I'm using the method below to extract a .zip file's contents into a new folder. It works perfectly fine one my computer but does not work on another one! I have Windows XP on both computers and have installed the same wampServer on both. Everything between the two computers is the same except their CPU and RAM! My computer is a powerful one and the one where the extract process fails is a very slow computer. Is that why? How can I make sure the PHP code runs perfectly even in a slow environment?
One thing to add: the zip archive to be extracted contains one directory and some files in that directory. If I test the process with a zip file that has no directories in it, it works fine on both computers. Any ideas?!
public function extract($pluginName, $pasteLocation) {

    $zip = new ZipArchive();
    $plugin = $pasteLocation.$pluginName.".zip";

    if ($zip->open($plugin) === TRUE) {
        $zip->extractTo($pasteLocation);
        $zip->close();
        unlink($pasteLocation.$pluginName.'.zip');
        $status = "true";
        $msg = "success";
    } else {
        $status = "false";
        $msg = "error";
    }

    $result["status"] = $status;
    $result["msg"] = $msg;
    return $result;
}

A: You said it does not work in one system. Can you tell what is not working, like, are the files extracted partially? or are the files getting corrupted?
Did you tried using different directories. Does the target directory contain a file with the same name as the directory in the zip? then I guess directory creation will not work.
Also what version of php are you using?
EDIT: Did you use ZipArchive::getStatusString  function to get any generated errors ? Are you using the same source archive in both machines?
You can also try the procedure explained in comment by 'hardcorevenom' here.
You can also try this class as shown here if nothing works.


text:
Q: How to create a webview with phonegap? I just installed phonegap and am new to it.I imported the example under android folder and ran it, and it seems to show the underlying files properly. However, How do I go about importing my html/js files.I tried to look up online, but no luck so far. How do I create a project for webview in phonegap and at the same time import my js/html files.do I also have to code in android for the same or phone gap does everything for me?

A: You have to put your html, js and css files in the assets folder.
In the main activity, your refer to them as follows:
super.loadUrl("file:///android_asset/www/index.html");

As per PhoneGap Documentation - Getting Started with Android
EDIT
Regarding formating and making it fit on the screen will depend on the way you treat your html, css and js files. For example, here is an html file that fits on the screen independently on the orientation and screen size:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <title>Hello World</title>

Apache Cordova

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

What I've done was to summarize the original cordova's html, that works perfectly on the application.
More about formmating, please refer to web design questions instead of PhoneGap, once the app is up and running.


text:
Q: make axes the same length in matplotlib pyplot I want to make square independent from the axis units. I know I can set the figure dimensions equal with figure(figsize=(10, 10)) for example, and I can set the axis scale ratio equal with set_aspect('equal'), but how can I force the actual axis length to be equal, e.g., make xaxis and yaxis each 10 inches long?
EDIT Example code
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator
import numpy as np

x1 = 1
y1 = [10., 1000.]
err1 = 0.00865
x2 = 2
y2 = [9., 900.]
err2 = 0.00658

len_xaxis,len_yaxis = 5.,5. #fix here your numbers
xspace, yspace = .9, .9 # change the size of the void border here.
x_fig,y_fig = len_xaxis / xspace, len_yaxis / yspace

for i in range(2):
    plt.clf()
    #    fig = plt.figure(figsize=(6, 6))
    fig = plt.figure(figsize=(x_fig,y_fig))
    plt.subplots_adjust(left=1-xspace, right = xspace, top=yspace, bottom = 1-yspace)
    gs = gridspec.GridSpec(3, 1)
    gs.update(hspace=0., wspace=0.)
    ax1 = plt.subplot(gs[0:2, 0])

    ax1.errorbar(x1, y1[i], yerr=err1)
    ax1.errorbar(x2, y2[i], yerr=err2)

    ax1.invert_yaxis()

    plt.setp(ax1.get_xticklabels(), visible=False)  # Remove x-labels between the plots
    plt.xlim(0, 3)

    ax2 = plt.subplot(gs[2, 0], sharex=ax1)

    nbins = len(ax1.get_yticklabels())
    ax1.yaxis.set_major_locator(MaxNLocator(nbins=8, prune='both'))
    nbins = len(ax2.get_yticklabels())
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=6, prune='both'))

    plt.tight_layout()
    plt.savefig('prune_%d.png' % i)
    plt.close()

A: Play with the plt.subplots_adjust() function. Example for 5 inches instead of 10:
len_xaxis,len_yaxis = 5.,5. #fix here your numbers

xspace, yspace = .9, .9 # change the size of the void border here.

x_fig,y_fig = len_xaxis / xspace, len_yaxis / yspace
figure(figsize=(x_fig,y_fig))
plt.subplots_adjust(left=1-xspace, right = xspace, top=yspace, bottom = 1-yspace)
plot([1,2,3],[-1,3,5])


text:
Q: How to save the input values? Using VB.Net
Database Form
Server Name, Username, Password - textbox
SQL Authentication, windows Authentication - checkbox

I have Database Form, First Time i run my software, I have to give Server Name, Window or SQL Authentication mode, UserName and password. Next Time I run the software, given  data's like Server name, username, password, window or sql authentication should appear in the form.
Before I used VB6, I used the ini file for getting the username, password and servername.
vb6 code.
Dim File As String, OFLen As Double, str As String
File = App.Path & "\SQLServer.ini"
OFLen = FileLen(File)
SName = ReadIni(File, "Server", "ServerName")
UName = ReadIni(File, "UserName", "UName")
PWord = ReadIni(File, "Password", "PWord")

Dim ConnectionString As String
Set DLTConn = New ADODB.Connection
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI; Persist Security Info=False;Initial Catalog=database1;Data Source=" & SName & ""
DLTConn.Open ConnectionString

There is any option is available in the vb.net for saving the data's or i have to use the same format(ini file) in vb.net
Need vb.net code Help.

A: These instructions assume VB2008 but I believe that 2010 is similar.
As @treaschf said, right click on your project in the Solution Explorer and select properties. If a window pops up with a title "Solution '...' Property Pages" then you clicked on the solution instead of the project. In the property window click on Settings. In the name column enter "Username", leave the type as String, the scope as User and the value as empty (unless you want to enter a default). Repeat this with each property that you want to store. These steps automatically create variables that you can access using My.Settings..
So in your code-behind you can do:
My.Settings.Username = "bob"

And:
Dim username as String = My.Settings.Username

I believe that settings will automatically be saved on exit but I recommend making an explicit call after updating just in case.
My.Settings.Save()

So that will pretty much do the same as you INI file used to do. But like @treaschf said, you should really encrypt the password when saving to disk. Below is a modified version of the routine found here. http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx . I removed the System.Security.SecureString because as nice as it is it also makes life more complicated. Change the value of Entropy to anything you want, call Encrypt(string) to encrypt your text and Decrypt(string) to decrypt it. This uses DPAPI so you don't have to worry about messing with the registry, permissions and everything else.
Private Shared entropy As Byte() = System.Text.Encoding.Unicode.GetBytes("Enter some text here for entropy")
Public Shared Function EncryptString(ByVal text As String) As String
    Dim data = System.Security.Cryptography.ProtectedData.Protect(System.Text.Encoding.Unicode.GetBytes(text), _
                                                                     entropy, _
                                                                     System.Security.Cryptography.DataProtectionScope.CurrentUser)
    Return System.Convert.ToBase64String(data)
End Function
Public Shared Function DecryptString(ByVal encryptedData As String) As String
    Dim data As Byte() = System.Security.Cryptography.ProtectedData.Unprotect(System.Convert.FromBase64String(encryptedData), _
                                                                                entropy, _
                                                                                System.Security.Cryptography.DataProtectionScope.CurrentUser)
    Return System.Text.Encoding.Unicode.GetString(data)
End Function

And then to put it all together:
        My.Settings.Username = EncryptString("bob")

    Dim username As String
    If Not String.IsNullOrEmpty(My.Settings.Username) Then
        Try
            username = DecryptString(My.Settings.Username)
        Catch ex As Exception
            'There was a problem decrypting the username
        End Try
    End If

    Trace.WriteLine(username)

A: If you right-click on your project in Solution Explorer, and chose Properties, on the properties page there will be a Settings tab, in which you define the settings of your application.
These settings will be stored in an XML file, near the executable of your application. (Or in case of user-settings, in the C:\Users\username... directory.
If you name your connection string setting as DbConnectionString, you will be able to access it from code like this:
 My.Settings.DbConnectionString

However if you need to store user names and passwords, I would recommend you to store the settings in the Windows registry, and encrypt them with the System.Security.Cryptography.ProtectedData class. (Storing the password unencrypted is not recommended.)


text:
Q: context deadline exceeded - IPFS I'm trying to publish website to ipfs using below command
1. ipfs add -r my-website
2. ipfs name publish <hash of the website>

while publishing getting error as Error: context deadline exceeded. What does that mean? How to resolve it?

A: It means that it took too long (more than 1 minute) to publish the data.
The built-in timeout will be removed in the soon to be released patch release v0.5.1.

More information on why this is happening is at https://github.com/ipfs/go-ipfs/issues/7244. If you don't want to wait for the patch release, or rebuild from the latest master, then you may have to retry a few times (in my tests a few days ago publish times were on average ~30s).
Note: v0.5.0 was recently released (less than a week ago as of this post) and contained a number of large upgrades to IPNS publishing performance. While some of the performance improvements are immediately noticeable, the lions share will only occur once more of the network upgrades.
Update: go-ipfs v0.5.1 has been released


text:
Q: set-fontset-font only overrides some Unicode character ranges (OS X) If I put the following into a scratch buffer (running emacs -q on 24.4.1), I can get the symbols (those in the comment) to change by varying the font name (changing the size so that it becomes "MS PGothic-24" for example). This is nice, and seems to show set-fontset-font working as intended.
; multiset symbols (unions with stuff inside them: ⊌ ⊎
(set-fontset-font t '(#x228C . #x228E) "MS PGothic-22")

However, if I have
; greek alphabet: α β γ δ
(set-fontset-font t '(#x370 . #x3F0) "MS PGothic-22")

then I seem to be trapped in a Menlo font. If I put cursor on the character and do C-u C-x =, I get output including the following:
mac-ct:-*-Menlo-normal-normal-normal-*-12-*-*-*-m-0-iso10646-1 (#x2F9)

The rest of the output confirms that the character I'm looking at is in the given range:
        character: α (displayed as α) (codepoint 945, #o1661, #x3b1)

By contrast, the output for the union-symbols is
mac-ct:-*-MS PGothic-normal-normal-normal-*-22-*-*-*-p-0-iso10646-1 (#x43A0)


text:
Q: Get schema data types from Xerces I am using SAX2 in Xerces C++ and would like to get XML Schema data while I handle elements so that I know their type defined in the Schema. How can I accomplish this?

A: Okay, I figured out how to do this. Sparse documentation available on the subject. Apparently I need to cast the SAX2XMLReader that XMLReaderFactory::createXMLReader() returns, to a SAX2XMLReaderImpl. Then I can register an PSVIHandler implementation on that interface. I have to provide my own implementation of the PSVIHandler, as I could not find a default implementation within Xerces.
Once this implementation of PSVI is registered with the SAX2XMLReaderImpl, I then create an ContentHandler impl and pass the PSVI handler impl to its constructor. Then I register the ContentHandler with SAX2XMLReaderImpl. Then when I am parsing I can access information from PSVIHandler to get schema related info.
It all seems very clumsy and the PSVIHandler interface seems very unfriendly. Maybe there is a better way.
Here is a code snippet:
  SAX2XMLReaderImpl* parser = dynamic_cast<SAX2XMLReaderImpl*>(XMLReaderFactory::createXMLReader());
  PSVIHandler* pSchemaHandler = new MyPSVIHandler();
  DefaultHandler* defaultHandler = new MyXMLHandler(pSchemaHandler);
  parser->setContentHandler(defaultHandler);
  parser->setErrorHandler(defaultHandler);
  parser->setPSVIHandler(pSchemaHandler);


text:
Q: Structural replace to delete an exception I want to delete an exception that should have never existed. I can not find the pattern that allows the deletion in the method declarations.
This code :
public void method1(String param) throws ShouldHaveNeverExisted{
   System.out.println("Yo");
   //...
}

public void method2WithoutParam() throws ShouldHaveNeverExisted{
   System.out.println("Yo");
   //...
}

Should be transform in :
public void method1(String param){
   System.out.println("Yo");
   //...
}

public void method2WithoutParam(){
   System.out.println("Yo");
   //...
}

The following pattern retrieve what I want but I can't find the correct replacement pattern.
class $Class$ {
   $ReturnType$ $MethodName$($ParameterType$ $Parameter$) throws ShouldHaveNeverExisted;
}

A: Search pattern:
class $Class$ {
  $RetType$ $Method$($ParameterType$ $Parameter$) throws ShouldHaveNeverExisted, $ExceptionType$ {
      $SomeStatement$;
  }
}

Replacement pattern:
class $Class$ {
  $RetType$ $Method$($ParameterType$ $Parameter$) throws $ExceptionType$ {
      $SomeStatement$;
  }
}

The main caveat is to "Edit variables" and turn on "This variable is target of the search" checkbox for $Method$ variable (on every try, unfortunately). Also $SomeStatement$'s max count must be unlimited.
Then IDEA 11.0.1 does search correctly. Even for any order of exceptions in throws clause. And it even shows correct result on "Preview Replacement" button click.
But then actually just deletes methods found. :(
This seems to be a bug. Please, someone confirm.
BTW. If you're getting rid of this exception anywhere, why not just replace "throws ShouldHaveNeverExisted" with "" with regular "Edit\Find\Replace in Path Ctrl+Shift+R"?
Or you could just hit Del on exception's class and check "Safe delete (with usage search)".


text:
Q: OnClick по вложенному RecyclerView Суть очень проста. есть список RecyclerView в элементах которого есть еще свои RecyclerView . проблема в том, что при клике на главный итем, а точнее по его месту где отрисовывается вложенный RecyclerView то клик не детектится.
Как можно исправить это? Второй список нужен только в качестве отображения, клика на нем нет.

A: Вопрос дилетантский, сам дам на него ответ спустя 4 года. Не нужно вешать слушатели на родительские элементы, если хотите слушать дочерние.
Я цеплял onClick по сути на весь дочерний Recycler, чего делать не нужно было


text:
Q: condition, file exist, sample code, checking directory for file Hi everyone i'm just a beginner at .net programming and i really need some help regarding this matter, the logic of my code was "supposed" to look at every directory that a put inside the array.. then will validate if every folder have file inside that's why i used "system.io.file.exist()", sorry for the mess up code please help me...
        Dim schar As String
        Dim number As Integer
        Dim Dirs(4) As String
        Dirs(0) = "E:\_net_programs\test\sample1"
        Dirs(1) = "E:\_net_programs\test\sample2"
        Dirs(2) = "E:\_net_programs\test\sample3"
        Dirs(3) = "E:\_net_programs\test\sample4"
        Dirs(4) = "E:\_net_programs\test\sample5"
        For Each folder As String In Dirs

            Dim getDir As New DirectoryInfo(folder)
            Dim fiArr As FileInfo() = getDir.GetFiles()
            Dim fri As FileInfo
            For Each fri In fiArr

                If Not System.IO.File.Exists(folder + "\" + fri.Name) Then
                    MessageBox.Show("file does not exist. : " + folder + "\" + fri.Name)
                    Return
                Else
                    MessageBox.Show(folder + "\" + fri.Name)
                    Return
                End If

                Label1.Text = "textfile name :" & fri.Name
                Dim file As New System.IO.StreamReader(folder + "\" + fri.Name)
                schar = Trim(file.ReadLine())
                MessageBox.Show(schar)

                Do While file.Peek <> -1
                    schar = Trim(file.ReadLine())

A: To check if a directory has files, you only need this:
If getDir.GetFiles().Length = 0 Then
    MessageBox.Show(string.Format("Folder {0} doesn't have any file.", folder))
End If

Regarding your sample, you have a issue there.
First you use the GetFiles() method, to get all the files that exists within the specified folder. Why do you need to double check if they exist since they have been just checked?

A: If you are interested in only text(*.txt) files , then you should do:
    Dim Dirs(4) As String
    Dirs(0) = "E:\_net_programs\test\sample1"
    Dirs(1) = "E:\_net_programs\test\sample2"
    Dirs(2) = "E:\_net_programs\test\sample3"
    Dirs(3) = "E:\_net_programs\test\sample4"
    Dirs(4) = "E:\_net_programs\test\sample5"
    For Each folder As String In Dirs
        Dim files = IO.Directory.GetFiles(folder, "*.txt")
        If files.Count = 0 Then
            MessageBox.Show("No txt files in folder : " + folder)
            Return
        Else
            MessageBox.Show(Join(files, vbCrLf))
            Return
        End If

    Next


text:
Q: Coruppted Jenkins need to reinstall My jenkins looks like corrupted. After installing older version I tried to upgrade. When I tried
wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt-get update
sudo apt-get install jenkins

It was failed to upgrade. Then I removed jenkins using
sudo apt-get remove jenkins

And again I tried to install.It is giving
    Reading package lists... Done
Building dependency tree
Reading state information... Done
jenkins is already the newest version.
The following packages were automatically installed and are no longer required:
  libjna-java libhttpcore-java libxbean-java libargs4j-java libhttpclient-java
  libplexus-build-api-java libbackport-util-concurrent-java
  libplexus-utils-java libjffi-java libjffi-jni
  libmaven-common-artifact-filters-java libjsr305-java libcommons-jexl-java
  libplexus-bsh-factory-java libplexus-container-default-java
  libganymed-ssh2-java jenkins-cli libplexus-sec-dispatcher-java
  libcommons-net2-java libjsoup-java libmaven2-core-java libplexus-cipher-java
  libjenkins-remoting-java libeasymock-java libplexus-i18n-java
  libmaven-invoker-java libplexus-containers-java libjaffl-java libdoxia-java
  libmaven-dependency-tree-java libmodello-java libplexus-archiver-java
  libconstantine-java libmaven-scm-java libmaven-enforcer-plugin-java
  libplexus-io-java libwagon-java libcommons-vfs-java libanimal-sniffer-java
  libgoogle-collections-java libnetbeans-cvsclient-java
  libmaven-plugin-testing-java libplexus-classworlds-java libitext1-java
  libplexus-interactivity-api-java libcommons-jxpath-java jenkins-common
  libplexus-interpolation-java libclassworlds-java
  libcommons-configuration-java libjnr-posix-java libplexus-ant-factory-java
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 513 not upgraded.

But service jenkins restart command throwing
jenkins: unrecognized service

Even http://localhost:8080/ not working.
I want to install from beginning . Any suggestions?

A: You could try:
sudo dpkg -P jenkins

and then re-install


text:
Q: Continuously monitor files opened/accessed by a process lsof -p 12345  will list all the files opened by process whose pid is 12345 but only for a particular instant of time.
How can we continuously monitor a process from the start to end(until process is terminated) to list/show every single file accessed by the process during its whole lifetime?

A: The new utility fatrace will do this: https://launchpad.net/fatrace/
sudo fatrace | grep '(6514)'

Don't use the -p option, it means the opposite of what it means in lsof or other utilities.

A: Try with strace -p 12345; it should do what you are trying to achieve.
The output can be filtered to only display opened files (Dan D.'s comment):
strace -e open -p 12345

Note: you can also trace quickly running processes with strace -e open <command>.

A: This will loop re-running your command and clearing the screen each time:
watch "lsof -p 12345"

WARNING: this will miss quick file accesses and is only suitable to see long standing files


text:
Q: Correct implementation of IGrouping to be used inside longlistselector groupheader I have an ObservableCollection like the following-
    private ObservableCollection<KeyedList<int, Anime>> _grp;
    public ObservableCollection<KeyedList<int, Anime>> GroupedAnimeByGenre
    {
        get
        {
            return _grp;

        }
        set
        {
            _grp = value;
            RaisePropertyChanged("GroupedAnimeByGenre");
        }
    }

I am using this to populate a LongListSelector with grouping. The KeyedList is implemented like this-
public class KeyedList<TKey, TItem> : List<TItem>
{
    public TKey Key { protected set; get; }

    public KeyedList(TKey key, IEnumerable<TItem> items)
        : base(items)
    {
        Key = key;
    }

    public KeyedList(IGrouping<TKey, TItem> grouping)
        : base(grouping)
    {
        Key = grouping.Key;
    }
}

I have the following code to feed the ObservableCollection. Keep in mind AnimeList2 is a temporary Collection.
 var groupFinale = AnimeList2.GroupBy(txt => txt.id).Where(grouping => grouping.Count() > 1).ToObservableCollection();

 GroupedAnimeByGenre = groupFinale ;

But I am unable to convert/use groupFinale with GroupedAnimeByGenre. I am missing the extension method part as I am not well aware of the syntax. Please help

A: If you remove the ToObservableCollection() call and take just that part
var groupFinale = AnimeList2.GroupBy(txt => txt.id).Where(grouping => grouping.Count() > 1);

you'll see that the type of groupFinale is IEnumerable<IGrouping<int, Anime>>. Hence applying ToObservableCollection() will result in ObservableCollection<IGrouping<int, Anime>>. However, the type of the GroupedAnimeByGenre is ObservableCollection<KeyedList<int, Anime>>. So you need to convert IEnumerable<IGrouping<int, Anime>> to IEnumerable<KeyedList<int, Anime>> which in LINQ is performed by the Select method.
Shortly, you can use something like this
var groupFinale = AnimeList2
    .GroupBy(txt => txt.id)
    .Where(grouping => grouping.Count() > 1)
    .Select(grouping => new KeyedList<int, Anime>(grouping))
    .ToObservableCollection();

You can make such conversion easier by providing an extension method (similar to BCL provided ToArray() / ToList()) that will allow skipping the type arguments like this
public static class KeyedList
{
    public static KeyedList<TKey, TItem> ToKeyedList<TKey, TItem>(this IGrouping<TKey, TItem> source)
    {
        return new KeyedList<TKey, TItem>(source);
    }
}

Then you can use simply
var groupFinale = AnimeList2
    .GroupBy(txt => txt.id)
    .Where(grouping => grouping.Count() > 1)
    .Select(grouping => grouping.ToKeyedList())
    .ToObservableCollection();


text:
Q: How to disable video recordings on AWS Device Farm using Selenium? I couldn't find a way how to disable video recording when using selenium.
Using CLI one can do so as mentioned in this comment:
aws devicefarm schedule-run \
    --project-arn YourProjectArn \
    --app-arn YourApplicationArn \
    --device-pool-arn YourDevicePoolArn \
    --name MyTestRun \
    --test '{"type": "CALABASH","testPackageArn":"YourTestPackageArn","parameters": {"video_recording": "false"}}'

But I'd like to do so using python & selenium. Sample code:
from boto3 import client
from selenium import webdriver

def main():
    device_farm_client = client("devicefarm", region_name='us-west-2')

    test_grid_url_response = device_farm_client.create_test_grid_url(
        expiresInSeconds=666,
        projectArn="arn:aws:devicefarm:us-west-2:..."
    )

    driver = webdriver.Remote(
        command_executor=test_grid_url_response['url'],
        desired_capabilities=webdriver.DesiredCapabilities.CHROME,
    )

    driver.get('https://api.ipify.org')
    print(f"Your IP is: {driver.find_element_by_tag_name('pre').text}")

    driver.quit()

if __name__ == '__main__':
    main()

How do I update the code to disable the video recording?


text:
Q: Automatically open popup on layer add I have a polyline that needs to have a popup automatically open when the user selects the polyline layer in the layers control menu.

This method did not work for me:

var polyline = L.geoJson(myData).bindPopup("
Some Text goes here
").openPopup();

How can I do the auto popup?
Here's my current setup:
var polyline = L.geoJson(myData).bindPopup("
Some Text goes here
");

var overlaysMenuCtrl = L.Control.extend({ ... blah blah... });

map.addControl(new overlaysMenuCtrl)());

I extend the control and add a custom function to check for layers that are toggled on/off by the user:
function toggleLayer(checked, layer){
    if(checked){
        map.addLayer(layer);
    } else {
        map.removeLayer(layer);
    }
}

$(".check").change(function(){
    var layerClicked = $(this).attr("id");
//Turn layers on and off based on the ID of the radio checked
   switch(layerClicked){
    case "polyline": toggleLayer(this.checked, polyline);
    break;
    ...and other layers ...
    }
});

HTML:
<input id="polyline" type="checkbox" class="check">Polyline layer

A: There is very probably a delay between the moment you request to add your layer to the map, and when that layer is actually on map / ready to open its popup.
You could simply add an event listener (use the "add" event) that will automatically open the popup whenever the layer is added to the map:
layer.on("add", function (event) {
  event.target.openPopup();
});

Demo: https://jsfiddle.net/3v7hd2vx/101/ (use the Layers Control to add the layer to the map)

A: Run openPopup() after the polyline has been added to the map.


text:
Q: Python load dll has error - WindowsError: [Error 4250] I was sent a dll file along with a header file and a .lib file, they were compiled with C. But when I try to load the dll file with python using ctypes, I get a error that says "self._handle = _dlopen(self._name, mode)
WindowsError: [Error 4250]".
I have put the files sent to me in the python src directory, I also checked the .dll file's dependencies with visual studio's dumpbin command and it says
File Type: DLL

Image has the following dependencies:

VCRUNTIME140D_APP.dll
ucrtbased.dll
api-ms-win-core-debug-l1-1-1.dll
api-ms-win-core-errorhandling-l1-1-1.dll
api-ms-win-core-string-l1-1-0.dll
api-ms-win-core-heap-l1-2-0.dll
api-ms-win-core-memory-l1-1-2.dll
api-ms-win-core-libraryloader-l1-2-0.dll
api-ms-win-core-profile-l1-1-0.dll
api-ms-win-core-processthreads-l1-1-2.dll
api-ms-win-core-sysinfo-l1-2-1.dll
api-ms-win-core-interlocked-l1-2-0.dll
api-ms-win-core-winrt-l1-1-0.dll

Summary

    1000 .00cfg
    1000 .data
    1000 .idata
    3000 .rdata
    1000 .reloc
    8000 .text
   10000 .textbss

The code I used in python was
import ctypes
from ctypes import *
testclib =ctypes.CDLL("Impo.dll")

Do I have to link the header files and others in python as well? If so, how should I have done it? or is there something wrong with the dll file itself?


text:
Q: Meteor transition effects for auto-updating content Looking at the meteor leaderboard example, I understand how content in the view templates  is bound to functions in the javascript application file.  For example, consider this snippet from the view file which defines the "selected" class to determine which name is highlighted yellow:
<template name="player">

    {{name}}
    {{score}}

</template>

The value of {{selected}} is defined and kept up to date in this function from leaderboard.js:
Template.player.selected = function () {
    return Session.equals("selected_player", this._id) ? "selected" : '';
};

My question is: How would you add transition effects to this auto updating process?  For example, say we wanted the yellow highlighting to fade to white on the existing name, and then fade into yellow on the new name, whenever a new name was clicked.  How could we accomplish that in meteor?

A: The easiest way would be using CSS transitions. Just ensure that the element is preserved (so it isn't replaced on re-draw, just patched):
 Template.player.preserve(['.player']);

Then go nuts with the CSS transitions:
 .player {
   background-color: white;
   transition: background-color 500ms linear 0;
   -moz-transition: background-color 500ms linear 0;
   // etc
 }

 .player.selected {
   background-color: yellow;
 }


text:
Q: Conditionally changing the label of a navigation bar item to a shorter label results in incorrect alignment When switching the navigation bar item label from a longer label to a shorter one, the new, shorter, label will be aligned at the center of the old label, as in the two images below:

This is the code for the problem:
struct NavBarItemIssueView: View {
    @State private var isLargeView = true

    var body: some View {
        NavigationView {
            Text("Some text")
                .navigationBarItems(leading: Button(action: {
                    self.isLargeView.toggle()
                }) {
                    if self.isLargeView == true {
                        Text("Show small label")
                    } else {
                        Text("Small")

                    }
                })
        }
    }
}

In the app I am making I have to switch between two labels when the edit mode is enabled or disabled and this problem occurs. Is there a way to fix this alignment in swift(ui)?

A: You can set a frame on your button with minWidth that is about the width of your biggest button, then you can align the button to the leading edge:
        NavigationView {
            Text("Some text")
                .navigationBarItems(leading: Button(action: {
                    self.isLargeView.toggle()
                }) {
                    if self.isLargeView == true {
                        Text("Show small label")
                    } else {
                        Text("Small")

                    }
                }
                .frame(minWidth: 200, alignment: .leading)
            )
        }


text:
Q: test case execution is getting failed and it is throwing any error stack trace in command line I created a testcase with Protractor-cucumber framework and I have used Grunt for execution of that test case. However, at the time of execution it failed and it's not providing any error stacktrace to know why it is failing.
I've searched Google and also reviewed other Stack Overflow solutions but I didn't find a solution for this.
Config File
exports.config = {

  //seleniumAddress: 'http://localhost:4444/wd/hub',
  getPageTimeout: 60000,
  allScriptsTimeout: 500000,
  directConnect:true,

  framework: 'custom',
  // path relative to the current config file
  frameworkPath: require.resolve('C:\\...\\node_modules\\protractor-cucumber-framework'),
  capabilities: {
    'browserName': 'chrome'
  },
  ignoreUncaughtExceptions:true,
  // Spec patterns are relative to this directory.
  specs: [
    './learnFramework/utility/test.feature'
  ],

  cucumberOpts: {
    require: './learnFramework/TestCases/spec.js',
    tags: false,
    profile: false,
    'no-source': true
  },
  onPrepare: function () {
    browser.ignoreSynchronization=true;
    browser.manage().window().maximize();
  }
};

Spec File
module.exports=function(){
    this.Given(/^Open the browser and Load the URL$/,async function(){
        browser.get("https://google.com");
    });

    this.When(/^User entered the text in the search box$/,async function(){
        browser.sleep(5000);
        console.log(await browser.getTitle());
        await element(By.name("q")).sendKeys("facebook");
        browser.sleep(3000);
    });

    this.Then(/^click on search$/,async function(){
        browser.action().sendKeys(protractor.Key.ENTER).perform();
        browser.sleep(5000);
    });
}

Error Log
Running "jshint:files" (jshint) task
>> 1 file lint free.
>
Running "protractor:singlerun" (protractor) task
[00:08:29] I/launcher - Running 1 instances of WebDriver
[00:08:29] I/direct - Using ChromeDriver directly...
>
DevTools listening on ws://127.0.0.1:50146/devtools/browser/5c09d68c-f3ff-43b2-b645-0b5c098c41d9
Feature: Title of your feature
>
    I want to use this template for my feature file
>
  Scenario: Title of your scenario
  ✓ Given Open the browser and Load the URL
  ✖ When User entered the text in the search box
  - And click on search
>
Failures:
>
[00:09:03] I/launcher - 0 instance(s) of WebDriver still running
[00:09:03] I/launcher - chrome #01 failed 1 test(s)
[00:09:03] I/launcher - overall: 1 failed spec(s)
[00:09:03] E/launcher - Process exited with error code 1
>>>
>>> Test failed but keep the grunt process alive.
>
Done.

If you observe the error log "When" step has failed but there is no error stacktrace in the command line to find why it failed.
My expectation is that it should show the error stacktrace for why it has failed.

A: You need to use await on your browser actions otherwise it performs the actions synchronously.
e.g
        await browser.get("https://google.com");


text:
Q: Function annotation with two or more return parameters When I write an annotation for a function which returns one parameter, I have no problems.
def func() -> str:
    return "ok"

However, when I write an annotation with two or more parameters, my PyCharm gives me SyntaxError: invalid syntax.
def func() -> str, str:
    return "ok - 1", "ok - 2"

I think that the parameters can be combined with a tuple, but I don't think that's the best way to do it.
My question is: how can I properly annotate a function with two or more return parameters?
Please include a PEP link, if any, in your response. I looked for the answer at PEP 484 and PEP 3107 and could not find it.

A: Use typing.Tuple:
from typing import Tuple

def func() -> Tuple[str, str]:
    return 'a', 'b'

This is appropriate because, conceptually, you are actually returning a single tuple containing those values. Note:
print(type(func()))

Output:
<class 'tuple'>

Except for the empty tuple (()), parentheses are not necessary to define a tuple, which means that 'a', 'b' is created as a tuple, rather than being separate values gathered into one by the return statement.


text:
Q: Redis expire a key but don't delete? In redis, is there a way to mark a key as expired but don't actually drop it from the database? A use case for this would be to let a client know that they need to pull in fresh data from a producer of that data, but if the producer is unreachable, still have the stale data available in the cache. This would make it simpler as one would not have to leverage a separate database / redis cache for stale data and data that is meant to expire to trigger an update to the cache.

A: There's no builtin way to do that.
In order to achieve the goal, you have to do the expire work by yourself. You can save the data into a hash with last modification time:
hset key data value time last-modification-time

When you retrieve the data, you can compare the last-modification-time and current time to check if the data is stale.
When you update the value, also update the last-modification time with current time.
In order to make it easy to use, and atomic, wrap these logic into a Lua script.


text:
Q: Cannot Import MySQLdb in PyCharm, runs fine in terminal. I have problems trying to run a script which imports MySQLdb within PyCharm.
Running the script from terminal works just fine while running within PyCharm fails with
ImportError: No module named MySQLdb

I have tried this thread and it helped making things work in the terminal.
Trying to set the environment variables in the IDE though does not seem to work.
In PyCharm Run Config I set the environment variables
DYLD_LIBRARY_PATH - /usr/local/mysql/lib/libmysqlclient.18.dylib
PATH - /usr/local/mysql/lib/

but I still get the ImportError.

A: As @Dilettant pointed me to https://stackoverflow.com/a/34992894/1989141,
I realised there are two different places I was supposed to set the Python interpreter in PyCharm.
The first is in the main preferences (as in phil's solution in the link) and allows me to specify a path to a local folder for mysqldb module.
The second is in the edit configuration settings for the script I want to run. I noticed the interpreters were different.
The script was set to run with the Python 2.7.6 /System/Library/Frameworks/...... version (which I believe is the OSx pre-installed version).
In the terminal and in PyCharm general settings I am using Python 2.7.9 in /usr/local/bin/python.
Matching the script interpreter to the one in the main settings (for which I manyally added mysqldb folder) solves the ImportError. Also I removed the environment variables I set up in the Edit Configuration as they are not needed.
Hope this helps. Thanks to both @Dilettant and @julivico for their suggestions.


text:
Q: Google colab: downloading dataframes as csv or excel or google sheets I am trying to save a dataframe from my google colab code to a csv, excel, or google sheet so that i can work with it in that form. I have been successful in downloading it however the format in the excel doc is off.
I want three columns (year/mean/std) which i have in my dataframe. when I download it, it labels the columns but the data doesnt fall into place and instead all stays in the first column.
image from google colab
image of csv

A: Because you are using tab separation. You should remove sep='\t' and download again.


text:
Q: Retrieve Json file data into datatable by onchange event I am trying to access a database using a on dropdown on-change function. Then, trying to store that data into one .json file. I want to retrieve that data into a DataTable without refreshing the current page.
Issue: I am not able to store json file's data into the DataTable. The worst part is I am not getting a single error while doing this. I am sure I am making some mistake.
here is the Sample data Which get stored into json file....
{"data":[{"ID":"1","ca_nm":"Candidate1 test","ma_nm":"Deep Bhatt"},{"ID":"2","ca_nm":"Candidate2 test","ma_nm":"Deep Bhatt"},{"ID":"3","ca_nm":"Candidate3 test","ma_nm":"Deep Bhatt"}]

Here is the code from which the data is stored into the json file.
   $vi_tab = $_POST['emp_teX'];
   if($vi_tab=='1'){
  $array_return = array();
        $query1 = mysqli_query($conn,"SELECT id,name,mana_name FROM sales ORDER BY id ASC");
        while($rows = mysqli_fetch_array($query1))
        {
            $pass_array['ID'] = $rows['id'];
            $pass_array['ca_nm'] = $rows['name'];
            $pass_array['ma_nm'] = $rows['mana_name'];
            array_push($array_return, $pass_array);
        }

        $changetab = fopen('tabdata.json', 'w');
        fwrite($changetab, '{"data":');
        fwrite($changetab, json_encode($array_return));
        fwrite($changetab, "}");
        fclose($changetab);
        }

This is the ajax that I function am using:
    <script type="text/javascript">

    function OnselectionChangge(table_te){

         $.ajax({
           type: 'POST',
            url: 'changeTeam2.php',
            data: 'emp_teX='+table_te,
            datatype: 'JSON',
            success: function(outdata){
                //alert(outdata);
                if (!$.fn.DataTable.isDataTable('#dataxxx')) {
                $('#dataxxx').DataTable({

                    "ajax": 'tabdata.json',
                    "dataSrc": "data",
                    "bRetrieve": 'true',
                    "destroy": "true",
                    "searching": "false",
                    "aoColumns": [ {
                    "ID": "ID"
                    },
                     {
                     "ca_nm": "Candidate"
                     },
                    {
                    "ma_nm": "Manager"
                     }
                    ]
                });

            }
        }
        });

    }
</script>

Here is the code of the drop down,
     <select id="tea" name="tea"
       onchange="OnselectionChangge(this.value)" required>
                    <option value="">Select One Team</option>
                    <option value="1">Team One</option>
                    <option value="2">Team two</option>
                    <option value="3">Team three</option>

                </select>

Thanks for the help in advance.


text:
Q: Multiple domains and SSL Certificates with GCP's kubernetes ingress I am exposing a micro service running on GCP's kubernetes engine via Google's Ingress load balancer. According to Here the load balancer supports multiple SSL certificates for different domain namess.
However, only the first specified SSL certificate is returned and therefore I receive a Your connection is not private warning for a domain-b. I would love to make an ingress controller for several domains each with their own certificate.
The following approach fails:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: some-name
spec:
  tls:
  - hosts:
    - www.domain-a.net
    - domain-a
    secretName: domain-a-net
  - hosts:
    - www.domain-b.org
    - domain-b.org
    secretName: domain-b-org
  backend:
    serviceName: some-name
    servicePort: 443

Any idea how to correctly benefit from Google's Ingress Multi SSL?

A: Updating GCE and GKE to latest version, and then redeploying the Ingress resource helped!


text:
Q: Detecting Javascript html page modification in VB.NET Webbrowser control My VB.NET code is supposed to execute third party Javascript code in an attempt to fill in and submit a form. This process consists of five steps, and I have been able to submit the form when all the steps are kept separate (i.e. behind 5 separate consecutive button clicks). Now, what I'd like to have is one button to handle all the five steps.
The problem is that the form originally only appears after calling "webbrowser.Navigate" command, which apparently modifies the page's HTML code. I seem to be unable to detect when Javascript has finished loading the new HTML in order to fill and submit the form. I have tried a timer control to wait for a certain HTML element ID to appear, but in vain.
This question has been asked before in different forms, but at least I could not find much help from the earlier answers:
InvalidCastException with WebBrowser.IsBusy or ReadyState (VB .NET)
Detect when AJAX changes HTML in a DIV in WebBrowser
http://www.techtalkz.com/vb-net/374234-vb-net-webbrowser-control-how-capture-javascript-events-statusbar-changed-mouseclick-etc.html
Please help me.

A: Well, this is the way it normally works in the software industry: Only after you've explained the problem to others, are you in a position to sufficiently understand it - and solve it yourself.
The problem was that I had not been using System.Windows.Forms.Timer() but another (less suitable) timer class for tracking changes in the HTML code. This was the reason why Application.DoEvents() did not work. With System.Windows.Forms.Timer() I was able to create a Timer.Tick event that keeps track of the phase of the form submittal (1-5 in my example) and attempts to execute the required Javascript commands in a Try-Catch construction. If an exception is caught, Application.DoEvents() is executed instead, and the timer ensures that the same commands are attempted to be executed shortly again.
This seems to work for me.


text:
Q: How to I assign the value of one item in a tuple to another in Python? I need to sort items in a tuple using the bubble sort method for a project in my computer science class. The items are all integers.
   SwapAgain = True

    while SwapAgain == True:
        SwapAgain = False
        for item in xrange(len(mytuple)):
            if mytuple[item] > mytuple[item + 1]:
                SwapAgain = True
                temp = mytuple[item]
                mytuple[item] = mytuple[item + 1]
                mytuple[item + 1] = temp

    return mytuple

I'm trying to assign the value of one item in the tuple to another, but when I try the code above I get this error:

mytuple[item] = mytuple[item + 1]
TypeError: 'tuple' object does not support item assignment

I would have preferred to use a list, but my teacher only provided us with a specific tuple. I really appreciate any help I can get. Thanks!

A: A tuple is an immutable data type. Once you create it, you can't alter it. So doing this with a list would make sense, and you have the option to return a tuple when the sorting is done, for example:
SwapAgain = True
myList = list(myTuple)

while SwapAgain == True:
    SwapAgain = False
    for i in xrange(len(myList)):
        if myList[i] > myList[i + 1]:
            SwapAgain = True
            temp = myList[i]
            myList[i] = myList[i + 1]
            myList[i + 1] = temp

return myList # or return tuple(myList) if you want

A: tuple is fixed structure in python, as the complier told you 'tuple' object does not support item assignment. you should copy it to a new list

A: Tuple's are immutable so you can set new values or remove items, But if your teacher has specifically asked for tuple then you can create an another tuple called sorted or something where you add these new items and finally replace the original tuple with this one.

A: As the condition with you is that you have to use a tuple according to your teacher, what would be the best possible solution is that, change the tuple to a list
temp_list = list(myTuple)

perform the bubble sort on the list and then again change the sorted list to a tuple
final_tuple = tuple(temp_list)

So, finally you are going to get a sorted tuple.


text:
Q: Live streaming of .flv format movie is not working if the directory is moved into other place I can play the .flv movie after compilation through FlashDevelop but its not working if I move the whole directory into another PC or another Directory in the same PC. Your help will be much appreciated...Thanks
package

{
    import flash.display.Sprite;

    import flash.net.NetConnection;
    import flash.net.NetStream;

    import flash.media.Video;
    public class Main extends Sprite {

        private var nc:NetConnection;
        private var ns:NetStream;
        private var vid:Video;
        private var client:Object;
        public function Main () {
            // Initialize net stream
            nc = new NetConnection();
            nc.connect (null); // Not using a media server.
            ns = new NetStream(nc);
            // Add video to stage
            vid = new Video(320,240);
            addChild (vid);
            //vid.x = ( stage.stageWidth / 2) - ( vid.width / 2 );
            //vid.y = ( stage.stageHeight / 2) - ( vid.height / 2 );
            // Changed since when deployed the
           // above set the video player nearly off the screen
           // Since I am lazy, I am just going to 0 them
           // out for now. Apparently, I have a lot more
           // to learn.
          vid.x = 0;
          vid.y = 0;

          // Add callback method for listening on
          // NetStream meta data
          client = new Object();
          ns.client = client;
          client.onMetaData = nsMetaDataCallback;
          // Play video
          vid.attachNetStream ( ns );
          ns.play ( 'dancinggirl_1.flv' );
        }
        //MetaData
        private function nsMetaDataCallback (mdata:Object):void {
            trace (mdata.duration);
        }
    }
}

A: You have to specify the path where your flv is located and asure the flv is located in this relative path to your swf.
ns.play ( 'path/to/dancinggirl_1.flv' );

If you embed the swf into a HTML page. The path has to be relative to the HTML, not the swf file.


text:
Q: Compact homeomorphic non bilipschitz homeomorphic metric spaces Statement: Let $(X,d)$, $(Y,r)$ be homeomorphic compact metric spaces. Then, there exists a bilipschitz homeomorphism between the two.
Problem: As I have no clue whether the statement is true or false (I'm not well acquainted with the theory of lipschitz functions), any proof/counterexample is welcome.
Rephrasing: Define the Lipschitz distance of two metric spaces as
$$d_L(X,Y)\doteq \inf\big|\ln \mathrm{dil}(f)+\ln \mathrm{dil}(f^{-1})\big|$$
where $\mathrm{dil}(f)$ is the dilatation of $f$ and the infimum is taken over all bilipschitz homeomorphisms between X and Y. The question is now whether the Lipschitz distance between two homeomorphic compact metric spaces is always finite.
Comments: It is clear to me that not all homeomorphisms between compact metric spaces are bilipschitz: $x^3\colon [-1,1]\rightarrow [-1,1]$ is a counterexample, which, although trivial, suggests
that simply scaling the metrics won't do the trick.
Also, any homeomorphism between compact metric spaces is uniformly bicontinuous, thus any such spaces are uniformly isomorphic (where, say à la Weil, uniformities are induced by the respective metrics), which is encouraging towards an affirmative answer, yet it seems difficult to prove (disprove) the existence of any bilipschitz homeomorphism given that the spaces are effectively homeomorphic.
As I would like the statement to be true, I was wondering the following: every compact metric space is complete and second countable ($\Rightarrow$ separable), i.e. Polish, so it is embeddable in Tikhonov's cube $T\doteq I^\mathbb N$. Is there any property of $\mathrm{Homeo}(T)$ that could be of help here?

A: This is hopelessly false. Bilipschitz maps preserve a lot more structure than homeomorphisms, Hausdorff dimension for one thing.
Example 1: equip $[0,1]$ with the metric $d(x,y)=|x-y|^{1/2}$. The topology stayed the same, the Hausdorff dimension changed (it is now $2$). Hence, the new space is not  biLipschitz equivalent to the original one.
Example 2, more subtle. The planar set $\{(x,\sqrt{|x|}) : -1\le x\le 1\}$ is homeomorphic to  interval $[-1,1]$, but not biLipschitz equivalent to it. The reason is the cusp at the origin: biLipschitz maps cannot form such a thing. Indeed, biLipschitz image of a line segment is a chord-arc curve: there is a constant $M$ such that for every two points $a,b$ on the curve the arc between them has length at most $M|a−b|$ (with $ |a−b| $ being  the Euclidean distance.) This property fails for the pair $(\pm \epsilon,\sqrt{\epsilon})$.


text:
Q: What COLLATE should i set to use all kind of possible languages? I have a column called username, i want the user to be able to insert text in japanese, roman, arabic, korean, and everything that is possible, including special chars [https://en.wiktionary.org/wiki/Index:All_languages], what COLLATE should i set on my database and tables?
I'm using utf_general_ci, i'm new so i don't know if this is the best COLLATE for my needs. I need to choose the right COLLATE to avoid sql error, because i will not use preg_replace or a function to replace special chars, i will only use prepared statement to avoid SLQ injection and protect by database.

A: *

*First choice (MySQL 8.0):  utf8mb4_0900_ai_ci

*Second choice (as of 5.6):  utf8mb4_unicode_520_ci

*Third choice (5.5+):  utf8mb4_unicode_ci

*Before 5.5, you can't handle all of Chinese, nor Emoji:  utf8_unicode_ci
The numbers refer to Unicode standards 9.0, 5.20, and (no number) 4.0.
No collation is good for sorting all languages at the same time.  Spanish, German, Turkish, etc, have quirks that are incompatible.  The collations above are the 'best' general purpose ones available.
utf8mb4 handles all characters yet specified by Unicode (including Cherokee, Klingon, Cuneiform, Byzantine, etc.)
If Portuguese is the focus:
See https://pt.stackoverflow.com/ and  MySQL collation for Portugese .
Study this for 8.0 or this for pre 8.0 to see which utf8/utf8mb4 collation comes closest to sorting Portuguese 'correctly'.  Perhaps utf8mb4_danish_ci or utf8mb4_de_pb_0900_ai_ci would be best.
(Else go with the 'choices' listed above.)

A: If you are using MySQL 5.5.3 or higher, I would recommend UTF-8 character encoding utf8mb4_unicode_ci . AFAIK it supports most, if not all languages, and implements the Unicode standard for sorting and comparison. As a second choice, have a look at utf8mb4_general_ci, which may be faster but also less accurate.
See this excellent SO post for (many) more details, or check out the official MySQL doc.
Below 5.5.3, utf8_unicode_ci  is your friend.

A: COLLATION refers to ordering (as in comparisons in WHERE and ORDER BY); you should really ask about CHARACTER SET:

*

*Pre-5.5.3:  utf8 (aka utf8mb3) handles all languages, except for a few Chinese characters and Emoji.

*5.5.3 forward:  utf8mb4 - Handles everything.  Outside of MySQL, it is spelled "UTF-8".


text:
Q: Show ALV table row details on double click? Say I have a table with customers, which is shown in an alv-grid like so:
**BEFORE THIS: Set up parameters, SQL Select, Table etc.
CREATE OBJECT gr_alv_grid
    EXPORTING
        i_parent = cl_gui_custom_container=>default_screen
    EXCEPTIONS
        error_cntl_create = 1
        error_cntl_init = 2
        error_cntl_link = 3
        error_dp_create = 4
        others = 5.
   IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno.
   ENDIF.

gr_alv_grid->set_table_for_first_display(
    EXPORTING
        i_structure_name = 'ZDebcdstest'
    CHANGING
        it_outtab = lt_debis
    EXCEPTIONS
        invalid_parameter_combination = 1
        program_error = 2
        too_many_lines = 3
        others = 4
).
IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
        WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.

What I would like to have is the option to double-click on any given row and get a more detailed overview of the object contained therein, like for instance done in SE16. I have already set up an Event Handler to listen for a double click, which works, but I haven't figured out how to get all the relevant data in a row and display the chosen object in full detail.
Any help is greatly appreciated.

A: Here is the primitive sample how to make it work "like for instance done in SE16'
  METHOD handle_double_click.
    DATA: ls_sflight LIKE LINE OF gt_sflight,
          ls_layout  TYPE lvc_s_layo.

    DATA: lt_fieldcatalog TYPE lvc_t_fcat,
          ls_fieldcatalog TYPE lvc_s_fcat.

    DATA: details_outtab TYPE lvc_t_detm,
          ls_detail      TYPE lvc_s_detm,
          lt_detail_tab  TYPE lvc_t_deta,
          ls_detail_tab  TYPE lvc_s_deta.

    READ TABLE gt_sflight INDEX e_row-index INTO ls_sflight.

    ls_fieldcatalog-fieldname = 'COLUMNTEXT'.
    ls_fieldcatalog-ref_table = 'LVC_S_DETA'.
    ls_fieldcatalog-key       = 'X'.
    ls_fieldcatalog-seltext   = 'Field'.
    ls_fieldcatalog-outputlen = 30.
    APPEND ls_fieldcatalog TO lt_fieldcatalog.

    CLEAR ls_fieldcatalog.
    ls_fieldcatalog-fieldname = 'VALUE'.
    ls_fieldcatalog-ref_table = 'LVC_S_DETA'.
    ls_fieldcatalog-seltext   = 'Field value'.
    ls_fieldcatalog-outputlen = 20.
    APPEND ls_fieldcatalog TO lt_fieldcatalog.

    ls_layout-no_toolbar = 'X'.

    LOOP AT gt_fieldcat ASSIGNING FIELD-SYMBOL(<field>).
      ls_detail_tab-columntext = <field>-scrtext_l.
      ASSIGN COMPONENT sy-tabix OF STRUCTURE ls_sflight TO FIELD-SYMBOL(<col>).
      ls_detail_tab-value = <col>.
      APPEND ls_detail_tab TO lt_detail_tab.
    ENDLOOP.
    ls_detail-detailtab = lt_detail_tab.
    APPEND ls_detail TO details_outtab.

    CALL FUNCTION 'LVC_ITEM_DETAIL'
      EXPORTING
        i_title               = 'Row details'
        it_fieldcatalog       = lt_fieldcatalog
        is_layout             = ls_layout
      TABLES
        t_outtab              = details_outtab.

  ENDMETHOD.                           "handle_double_click

in the above snippet
gt_sflight - main table you wanna capture row details from
gt_fieldcat - field catalog of this table which must be populated before firing the event
if you don't know how apply this method to your ALV, search for some tutorial about event implementation.


text:
Q: Making tab completion look anywhere in the word This completion mode probably has a name, I just don't know what it is.
In Sublime Text the auto complete works in a way that the typed letters are searched for in the same order but they are not required to exactly follow each other.
For example, typing "rf" will match "runfile"
I am pasting a screencast of how Sublime completion works, and I am wondering if there is any way to make such a completion work in the linux command line.


text:
Q: Re render the main component The reason for my question is how to reload the data of the main component, Parent component, from a child component.
So for example the following is the main component
const App: React.FC = () => {
  const [isReg, setIsReg] = useState(false);
  const [cliente, setCliente] = useState(true);

  const [renderAgain, setRenderAgain] = useState(false);

  useEffect(() => {

    getItem("isRegistered").then(res => {
      if (res!=null){
        setIsReg(true);
        getItem("clientType").then(res => {
          if (res=="1"){
            setCliente(true)
          }else{
            setCliente(false)
          }
        })
      }
      else{
        setIsReg(false);
      }
    });

}, [renderAgain]);

return(
<IonApp>
<IonReactRouter>
<IonSplitPane contentId="main" when="(min-width: 4096px)">
      <Menu renderAgain={renderAgain} setRenderAgain={setRenderAgain} />
  <IonRouterOutlet id="main">

    <Route path="/" render={() => isReg ?   ( cliente ?  <HomeCliente setRenderAgain={setRenderAgain}/> : <HomeProveedor setRenderAgain={setRenderAgain}/> ) : <Inicio /> } />
    <Route path="/home" render={() =>  isReg ? (cliente ?  <HomeCliente setRenderAgain={setRenderAgain}/> : <HomeProveedor setRenderAgain={setRenderAgain}/> ): <Inicio /> } ></Route>
    <Route path="/registro" render={() => isReg ?   ( cliente ?  <HomeCliente setRenderAgain={setRenderAgain}/> : <HomeProveedor setRenderAgain={setRenderAgain}/> ) : <Registro /> } />

    <Route path="/ingresar" render={() => isReg ?   ( cliente ?  <HomeCliente setRenderAgain={setRenderAgain}/> : <HomeProveedor setRenderAgain={setRenderAgain}/> ) :<Ingresar setRenderAgain={setRenderAgain} />} />

    <Route path="/Completarinfo" render={() => <Completarinfo setRenderAgain={setRenderAgain} renderAgain={renderAgain} />}  />
    <Route path="/CompletarRubros" component={CompletarRubros} exact={true}

  </IonRouterOutlet>
  </IonSplitPane>
</IonReactRouter>
</IonApp>

);
};

As you can see in the main component's useEffect, the data saved on the device is searched. To verify if you are registered and what type of client it is.
In this way, if it is not registered, the Inicio component is rendered. Where it gives you the option to enter or register. Now, once it is started or registered, you have to go to / home, but it is necessary again to see in the useEffect of the main component if it is logged in, and for that I use the renderAgain hook, saying that you have to re-execute the useEffect from App.
const IngresarDatos = (props:{ setRenderAgain:any, setShowLoading:any, setShowAlertUsuarioContraseñaIncorrectos:any,  setShowAlertServerConnection:any, setShowAlertCompletarInfo:any, setShowAlertContraseñaCambiada:any, setShowAlertContraseñaNoIguales:any, setShowAlertBadEmail:any, setShowAlertBadCode:any}) => {

    const axios = require('axios');
    const [home, setHome]=useState(false)

    const [restaurar, setRestaurar]=useState(0)

    const password = useRef(0)
    const email=useRef("")

    if(home){

      props.setRenderAgain(true)
      return(<Redirect push={true} to="/home" />);

    }

    const validarRestauracion = () => {
      setRestaurar(3)
    }

    const ingresar = () => {
      if((email.current!= null && email.current!= undefined && email.current!="")&& (password.current!=null && password.current!= undefined )){

        props.setShowLoading(true)

        axios.get(url+"ingresar/"+email.current+"/"+password.current, {timeout: 7000})
        .then((res: { data: any; }) => {
          const resquest = res.data;
          console.log(res.data)
          if(resquest=="usuario y contraseña no válidos"){
            props.setShowLoading(false)
            props.setShowAlertUsuarioContraseñaIncorrectos(true)

          }
          else if(resquest[0].picture ==""){
            setItem("isRegistered", resquest[0].user).then(() =>{
                setItem("clientType", resquest[0].clientType).then(() =>{
                  setItem("personalInfoCompleted",false).then(() =>{
                    props.setShowLoading(false)
                    setHome(true)
                  })
                })

            });

          }
          else{
            setItem("isRegistered", email.current).then(() =>{

              setItem("fotoPersonal", resquest[0].picture).then(() =>{
                setItem("clientType", resquest[0].clientType).then(() =>{
                  setItem("personalInfoCompleted",true).then(() =>{
                    props.setShowLoading(false)
                    setHome(true)
                  })
                })
              })
            });
          }
        }).catch((err: any) => {
          // what now?
         props.setShowLoading(false)
          props.setShowAlertServerConnection(true)
      })
      }else{
        props.setShowAlertCompletarInfo(true)
      }

    }

When the data is verified, home is equal to true and therefore the following is executed:
    if(home){
      props.setRenderAgain(true)
      return(<Redirect push={true} to="/home" />);
    }

It is redirected to home, the problem is that if I don't change renderAgain, the home page won't reload unless I refresh the browser.Am I doing things right? How is it possible to reload the main component correctly so that it checks which url it should go to?

A: Don't pass the setState directly to props add a function in the main component first and then pass it to props.
in the main component :
// ...code
const handleRenderAgain = (render: boolean) => setRenderAgain(render);
// ...code
<Menu renderAgain={renderAgain} setRenderAgain={handleRenderAgain} />
// ...rest of the code


text:
Q: NInject with Generic interface I have defined one interface and one class:
public interface IRepository<T>
{
}

public class RoleRepository:IRepository<Domain_RoleInfo>
{
}

Inject here:
public RoleService
{
    [Inject]
    public RoleService(IRepository<Domain_RoleInfo> rep)
    {
        _roleRep=rep;
    }
}

How can I perform Dependency Injection With Ninject,say how to bind?
I have written a helper class as below, it works fine with non-generic interface.but how to refactor it support generic interface as above?
public class RegisterNinjectModule : NinjectModule
{
    public override void Load()
    {
        BindServices();
        BindRepositories();
    }

    private void BindServices()
    {

        FindAndBindInterfaces("RealMVC.Service.Interfaces", "RealMVC.Services");
    }

    private void BindRepositories()
    {
        FindAndBindInterfaces("RealMVC.Repository.Interfaces", "RealMVC.Repositories");
    }

    private void FindAndBindInterfaces(string interfaceAssemblyName, string implAssemblyName)
    {
        //Get all interfaces
        List<Type> interfaces = Assembly.Load(interfaceAssemblyName).GetTypes().AsQueryable().Where(x => x.IsInterface).ToList();
        IQueryable<Type> ts = Assembly.Load(implAssemblyName).GetTypes().AsQueryable().Where(x => x.IsClass);

        foreach (Type intf in interfaces)
        {
            Type t = ts.Where(x => x.GetInterface(intf.Name) != null).FirstOrDefault();
            if (t != null)
            {
                Bind(intf).To(t).InSingletonScope();
            }
        }
    }

}

A: This should work:-
Bind(typeof(IRepository<>)).To(typeof(Repository<>));

where:-
IRepository<> is an interface of the form:-
public interface IRepository<T> where T : class
{
 //...
}

Repository<> is a class of the form:-
public class Repository<T> : IRepository<T> where T : class
{
  //...
}

I hope this helps :-)

A: This should help accomplish what you are asking for.
First let us define two classes (InterfaceTypeDefinition and BindingDefinition).
InterfaceTypeDefinition holds information about a concrete type and its interfaces. The method IsOpenGeneric is define in the TypeExtensions class.
public class InterfaceTypeDefinition
{
    public InterfaceTypeDefinition(Type type)
    {
        Implementation = type;
        Interfaces = type.GetInterfaces();
    }

    /// <summary>
    /// The concrete implementation.
    /// </summary>
    public Type Implementation { get; private set; }

    /// <summary>
    /// The interfaces implemented by the implementation.
    /// </summary>
    public IEnumerable<Type> Interfaces { get; private set; }

    /// <summary>
    /// Returns a value indicating whether the implementation
    /// implements the specified open generic type.
    /// </summary>
    public bool ImplementsOpenGenericTypeOf(Type openGenericType)
    {
        return Interfaces.Any(i => i.IsOpenGeneric(openGenericType));
    }

    /// <summary>
    /// Returns the service type for the concrete implementation.
    /// </summary>
    public Type GetService(Type openGenericType)
    {
        return Interfaces.First(i => i.IsOpenGeneric(openGenericType))
            .GetGenericArguments()
            .Select(arguments => openGenericType.MakeGenericType(arguments))
            .First();
    }
}

BindingDefinition holds information about the binding between a service and a concrete implementation.
public class BindingDefinition
{
    public BindingDefinition(
        InterfaceTypeDefinition definition, Type openGenericType)
    {
        Implementation = definition.Implementation;
        Service = definition.GetService(openGenericType);
    }

    public Type Implementation { get; private set; }

    public Type Service { get; private set; }
}

Second, let us implement an extension method that retrieves the necessary information.
public static class TypeExtensions
{
    public static IEnumerable<BindingDefinition> GetBindingDefinitionOf(
      this IEnumerable<Type> types, Type openGenericType)
    {
        return types.Select(type => new InterfaceTypeDefinition(type))
            .Where(d => d.ImplementsOpenGenericTypeOf(openGenericType))
            .Select(d => new BindingDefinition(d, openGenericType));
    }

    public static bool IsOpenGeneric(this Type type, Type openGenericType)
    {
        return type.IsGenericType
            && type.GetGenericTypeDefinition().IsAssignableFrom(openGenericType);
    }
}

These classes can now be used to initialize the bindings in the module.
public class RepositoryModule : NinjectModule
{
    public override void Load()
    {
        var definitions = Assembly.GetExecutingAssembly().GetTypes()
            .GetBindingDefinitionOf(typeof(IRepository<>));

        foreach (var definition in definitions)
        {
            Bind(definition.Service).To(definition.Implementation);
        }
    }
}

A: If you import the Ninject conventions extension, its GenericBindingGenerator should be able to help you. It adds support for generic interfaces.

A: Just a question on your FindAndBindInterfaces method: inside the foreach don't you have a "closure" problem on the intf variable? I'm still not sure I understood how the closure issue works.
Anyway, just to be safe, I think that you should change your foreach into something like:
foreach (Type intf in interfaces)
    {
        var tmp = intf;
        Type t = ts.Where(x => x.GetInterface(tmp.Name) != null).FirstOrDefault();
        if (t != null)
        {
            Bind(intf).To(t).InSingletonScope();
        }
    }


text:
Q: Updating a state inside a React function Is it possible to update the react state inside a function, and see the results in other components?
The example below is an App.js in a create-react-app file. I want to update the content of the h1 tags when I edit the textarea. I've simplified the example as far as I can.
Only newData3 and newData4 reflect the content of the textarea.
newData1 and newData2 only render "this.newData1() =" and "newData2="
import React, { Component } from 'react';
class App extends Component {
  state = {
    data:'AA',
    newData: 'AA AA'
    }
  newData1=()=>{this.state.data + " " + this.state.data}
  render() {
    const newData2=()=>{this.state.data + " " + this.state.data}
    return (

this.newData1() = {this.newData1()}

newData2={newData2()}

newData3={this.state.data + " " + this.state.data}

newData4={this.state.newData}

      <textarea
      value={this.state.data}
      onChange={(e) => {
        this.setState({data:e.target.value}) ;
        this.setState({newData:e.target.value + ' ' + e.target.value})
      }}
        />

    );
  }
}

export default App;

A: You need to write like this. Sandbox https://codesandbox.io/s/ywzoq8oqmx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

    class App extends Component {
      constructor(props) { // Set state initial value in constructor function
        super(props)
        this.state = {
          data: 'AA',
          newData: 'AA AA'
        }
      }
      newData1() { return (this.state.data + " " + this.state.data) } // This can use arrow funtion, but still need return
      render() {
        const newData2 = () => { return (this.state.data + " " + this.state.data) } // this need return
        return (

newData1={this.newData1()}

newData2={newData2()}

newData3={this.state.data + " " + this.state.data}

newData4={this.state.newData}

            <textarea
              value={this.state.data}
              onChange={(e) => {
                this.setState({ data: e.target.value });
                this.setState({ newData: e.target.value + ' ' + e.target.value })
              }}
            />

        );
      }
    }

    export default App;

A: You have to remove the brackets of newData1 and newData2 to make implicit the return statement:
newData1 = () => this.state.data + " " + this.state.data
and
const newData2 = () => this.state.data + " " + this.state.data
I hope this helps you.

A: Yes it's possible. In onChange of textArea call function like below. Keep in mind that when you declare a function inside the component you need to do either bind the function in constructor or use an arrow function like
Below code uses Arrow function:
  handleTextArea = e => {
      this.setState({data:e.target.value, newData:e.target.value + ' ' + e.target.value
      });
 }

   <textarea value={this.state.data} onChange={this.handleTextArea} />

Below code uses regular function with binding In constructor
     constructor(props){
         super(props);
         this.handleRextArea = this.handleTextArea.bind(this);
     }

     handleTextArea(e) {
      this.setState({data:e.target.value, newData:e.target.value + ' ' + e.target.value
      });
 }

   <textarea value={this.state.data} onChange={this.handleTextArea} />

And in render when call other component just pass state value as props to the component and access the props value in other component in h1 tag like
      render(){

             <textarea value={this.state.data} onChange={this.handleTextArea} />
              <OtherComponent data={this.state.data} />

      }

Now in Other component display data like

{this.props.data}

Please not you should always bind function in constructor only but not anywhere else in the component. Also no need to see multiple setStates to update two different values instead use single setState as I mentioned in my code

A: https://codesandbox.io/s/042j0lwn0
So the answer to your question Yes you can use the components state to render the result in other components. You were already close!
You didn't correctly implement the newData1 and newData2 functions.
I have made your code slightly better by adding some small changes:

*

*Used setstate once

*Destructured your state values

*stored your target.value in a const

*showed you how to use arrow function inside render()

*showed you how to use newData1 as class Method

Good luck! :)
 import React, { Component } from "react";
    import ReactDOM from "react-dom";
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: "AA",
          newData: "AA AA"
        };
      }

      // method definition
      newData1() {
        return this.state.data + " " + this.state.data;
      }

      render() {
        // please desturucture!
        const {
          state: { data, newData }
        } = this;

        // arrow function
        const newData2 = () => data + " " + data;

        return (

this.newData1() = {this.newData1()}

newData2={newData2()}

newData3={data + " " + data}

newData4={newData}

            <textarea
              value={data}
              onChange={e => {
                // store the value in a const
                const value = e.target.value;

                // use setState once and use the ... to make a shallow copy
                this.setState({
                  ...this.state,
                  data: value,
                  newData: value + " " + value
                });
              }}
            />

        );
      }
    }

    export default App;

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);