text:
Q: What is the best way to get directory path for wp-config.php? I am developer of the plugin mapsmarker.com which also offers several APIs which can be accessed directly (eg www.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-geojson.php?marker=1)
For these APIs I initially wrote the absolut directory path to a file with the following function on plugin install:
file_put_contents(dirname(__FILE__).'/leaflet-wp-path.php', '<?php define(\'WP_PATH\',\''.ABSPATH.'\'); ?>');

In the API-files, the file leaflet-wp-path.php the got included by the following code:
include_once(dirname($_SERVER['SCRIPT_FILENAME']).'/leaflet-wp-path.php');
include_once(WP_PATH.'wp-config.php');
include_once(WP_PATH.'wp-includes/wp-db.php');
global $wpdb;
...

I then noticed that on some hosting providers these kind of operation is not supported, causing the plugin install to fail.
Therefore I switched to another method for determing the directory-path to wp-config.php:
//info: construct path to wp-config.php with fallback for subdirectory installations
$wp_path = $_SERVER["DOCUMENT_ROOT"];
if ( file_exists($wp_path . '/wp-config.php') ) {
    include_once($wp_path.'/wp-config.php');
    include_once($wp_path.'/wp-includes/wp-db.php');
} else {
    $wp_plugin_path_modified = explode(DIRECTORY_SEPARATOR, dirname(__FILE__),-3);
    $wp_path = implode(DIRECTORY_SEPARATOR, $wp_plugin_path_modified);
    include_once($wp_path.'/wp-config.php');
    include_once($wp_path.'/wp-includes/wp-db.php');
}
if ( !file_exists($wp_path . '/wp-config.php') ) {
    echo __('Error: Could not construct path to wp-config.php - please check http://mapsmarker.com/path-error for more details.','lmm') . '
Path on your webhost: ' . $wp_path;
} else {
...

This worked fine even on hosts that don´t allow the function file_put_contents() because the directory path is
determined from the current dirname of the API-File.
Now I got a bug report from a user, telling me that this method doesnt work on his host. He writes:

This is the example of the one of icon link. Looks entire plugin links are not correct. Only one thing is working now, it is admin panel configuration. Also it is making markers, but not showing in browsers.
On Windows Web Host
http://XXXXX/wordpress/wp-content/plugins/D:/Hosting/5465771/html/wordpress/wp-content/plugins/leaflet-maps-marker/img/logo-mapsmarker.png
On Linux Web Host
http://XXXXX/wordpress/wp-content/plugins/D:/inetpub/vhosts/XXXXX/httpdocs/wordpress/wp-content/plugins/leaflet-maps-marker/img/logo-mapsmarker.png

Does anyone know a better method for determing the directory path to wp-config.php to support this kind of hosting configuration?

A: I came up with this solution.
This function checks in each directory level starting from the directory of the current file for the file wp-config.php.
<?php
    function find_wp_config_path() {
        $dir = dirname(__FILE__);
        do {
            if( file_exists($dir."/wp-config.php") ) {
                return $dir;
            }
        } while( $dir = realpath("$dir/..") );
        return null;
    }
?>

To actually include the file you can use this:
if ( ! function_exists('add_action') ) {
    include_once( find_wp_config_path()  . '/wp-load.php' );
}

This can also be found here:
How to determine wordpress base path when wordpress core is not loaded

A: I guess it sounds silly, but could you work your way up from the plug-in directory?
if ( file_exists('../../../wp-config.php') ) :
    include_once '../../../wp-config.php';
;

I'm sure someone else will probably have a more elegant solution.

A: For the record, the question asks how to do the wrong thing, even in the time it was asked you should not have used direct access to any of the plugin files, but used probably a uniqly crafted URL parameter like my_plugin_param that its usage will indicate that the plugin is supposed to do whatever is needed. To detect it the plugin should hook on the init action and check if the URL contains my_plugin_param. Once done that way you do not need to bootstrap WordPress as it was already done.
While wp-config.php should be either in WordPress root, or one directory above it, plugins might be installed outside of the WordPress directories. While not especially popular setup, it can be done.

A: it's not my code, found somewhere on stack, but try this:
function FindWPConfig($dirrectory){
global $confroot;
foreach(glob($dirrectory."/*") as $f){
    if (basename($f) == 'wp-config.php' ){
        $confroot = str_replace("\\", "/", dirname($f));
        return true;
    }
    if (is_dir($f)){
        $newdir = dirname(dirname($f));
    }
}
if (isset($newdir) && $newdir != $dirrectory){
    if (FindWPConfig($newdir)){
        return false;
    }
}
return false; }
    if (!isset($table_prefix)){
        global $confroot;
        FindWPConfig(dirname(dirname(__FILE__)));
        include_once $confroot."/wp-load.php";
}

A: The following doesn't exactly answer what's being asked in the context of the question, but it does answer exactly what's in the title of the question.
For those who are looking for a way to get the path to wp-config.php from within WordPress, the following works fine.
This is how WP CLI does it:
Source
function locate_wp_config() {
    static $path;

    if ( null === $path ) {
        $path = false;

        if ( getenv( 'WP_CONFIG_PATH' ) && file_exists( getenv( 'WP_CONFIG_PATH' ) ) ) {
            $path = getenv( 'WP_CONFIG_PATH' );
        } elseif ( file_exists( ABSPATH . 'wp-config.php' ) ) {
            $path = ABSPATH . 'wp-config.php';
        } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
            $path = dirname( ABSPATH ) . '/wp-config.php';
        }

        if ( $path ) {
            $path = realpath( $path );
        }
    }

    return $path;
}


text:
Q: change the color of the frame I was making slides using WinEdt. I took codes from someone. I want to change the color of the frames appearing in the slides. I tried using different themes but no success. Can anybody help me. Thanks a lot for help. Here is my code. I want to change the color blue to some other color in addition to change of background color.
\documentclass[ucs,10pt]{beamer}

\usepackage{amsthm}

\usepackage{colortbl}

\usepackage{hyperref}

\usepackage{beamerthemesplit}
\usepackage{bibentry}
\usepackage{color}
\date{}
\PassOptionsToClass{t,hyperref={pdfpagelabels=false,plainpages=false}}{beamer}
\providecommand\thispdfpagelabel[1]{}
\mode<presentation>
 \usepackage{array}
 \setlength{\arrayrulewidth}{0.6pt}
\usecolortheme{Blue}
\usetheme{Antibes}
\useinnertheme{rounded}
\setbeamercolor{itemize item}{fg=orange}
\setbeamercovered{transparent}
\newtheorem{defi}{Definition}
\renewenvironment{definition}{\begin{defi}}{\end{defi}}
\newtheorem{defis}{Definitions}
\renewenvironment{definitions}{\begin{defis}}{\end{defis}}
\newtheorem{facte}{Fait}
\renewenvironment{fact}{\begin{facte}}{\end{facte}}
\newtheorem{coro}{Corollaire}
\renewenvironment{corollary}{\begin{coro}}{\end{coro}}
\newtheorem{theo}{Theorem}
\renewenvironment{theorem}{\begin{theo}}{\end{theo}}
\newtheorem{Remark}{Remark}[section]
\newtheorem{exa}{Example}
\renewenvironment{example}{\begin{exa}}{\end{exa}}
\newcommand{\bea}{\begin{eqnarray}}
\newcommand{\eea}{\end{eqnarray}}
\newcommand{\bee}{\begin{eqnarray*}}
\newcommand{\eee}{\end{eqnarray*}}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}
\newcommand{\ba}{\begin{array}}
\newcommand{\ea}{\end{array}}
\newcommand{\bi}{\begin{itemize}}
\newcommand{\ei}{\end{itemize}}
\newcommand{\bc}{\begin{center}}
\newcommand{\ec}{\end{center}}
\newcommand{\bfr}{\begin{flushright}}
\newcommand{\efr}{\end{flushright}}
\newcommand{\f}{\frac}
\usepackage{rotating}

A: You can modify the colours like this:
\documentclass{beamer}
\usetheme{Antibes}

\setbeamercolor{palette primary}{bg=red!80!black}
\setbeamercolor{palette secondary}{bg=red!70!black}
\setbeamercolor{palette tertiary}{bg=red!60!black}
\setbeamercolor{palette quaternary}{bg=red!50!black}

\setbeamercolor{background canvas}{bg=gray!50!white}

\begin{document}
    \begin{frame}
        \frametitle{test}
        test
    \end{frame}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: KeyError on a certain word I am trying to use Naive Bayes for spam-ham classification.
training_set['E_Mail'] = training_set['E_Mail'].str.split()
vocabulary = []
for email in training_set['E_Mail']:
 for word in email:
     vocabulary.append(tuple(word))

vocabulary = list(set(vocabulary))

word_counts_per_email = {unique_word: [0] * len(training_set['E_Mail']) for unique_word in vocabulary}

for index, email in enumerate(training_set['E_Mail']):
 for word in email:
   word_counts_per_email[word][index] += 1

I am getting a word error repeteadly on here:
word_counts_per_email = {unique_word: [0] * len(training_set['E_Mail']) for unique_word in vocabulary}

for index, email in enumerate(training_set['E_Mail']):
 for word in email:
   word_counts_per_email[word][index] += 1

The error message is just this:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-1706354aaff0> in <module>()
     3 for index, email in enumerate(training_set['E_Mail']):
     4   for word in email:
----> 5     word_counts_per_email[word][index] += 1

KeyError: 'hafta'

'hafta' is the first word of the pandas dataframe and the trainng dataset.
I tried the solution on this issue that seemed similar to mine but it didn't work out.
I will appreciate any hint to get this over, thank you.

A: My guess is that this line vocabulary.append(tuple(word)) should be changed to vocabulary.append(word) since your version might put letters instead of words into vocabulary and therefore word_counts_per_email.
In case this doesn't work, I suggest looking into contents of vocabulary/ word_counts_per_email so you can determine what went wrong.


text:
Q: Problem with coding a function that returns the maximum integer from even positions of a string Make a function that receives a string containing only digits and may also be an empty string, which returns an integer value which is the maximum of all the digits that are in the EVEN POSITIONS of the original string.
If the empty string, the function should return -1.
For example:
max_even_pos("123454321") returns 5, because 5 is the maximum of 1,3,5,3,1, which are the digits in the original string in even positions.

# My code
def max_even_pos(st):
    if not st:
        return -1          ### This line satisfies the empty list condition
    for i in range(len(st)):  ### Problem I have. Trying to find
                                    ## the max integer from even positions
        num_list = [i]         # assigns elements to the list
        if i%2 == 0:             # checks if elements are even
            return max(num_list)      # result

My only problem is trying to get the code to find the greatest integer in the even position of the original string. I think "num_list = [i]" causes the error, but I am unsure how to change this so it executes properly.
As of right now, it outputs 0 for all cases

A: Your current code ensures that num_list has no more than a single element.  When you hit the first even index, 0, you stop and return that index, without regard to the input value.  You have several errors to correct:

*

*Put the return after the loop.  You have to get through all of the input before you can return the required value.

*Accumulate the values with append.  Your current code keeps only the last one.

*Accumulate the input values; i is the position, not the value.  I believe that you want st[i]
Also look into better ways to iterate through a list.  Look at for loops or list slicing with a step of 2.  If you are ready for another level of learning, look up list comprehension; you can reduce this function to a one-line return.

A: @Prune is correct. Maybe comparing the lines below to your original will help you for next time....
test_string = "123454321"
def max_even_pos(st):
    num_list = []
    if not st:
        return -1
    for i in range(len(st)):
        if i%2 == 0:
            num_list.append(st[i])
    return max(num_list)

print(max_even_pos(test_string))


text:
Q: How to generate pdf with PHP using wkhtml2pdf? How I write PHP to generate PDF from PHP page using wkhtml2pdf ? I am looking for only an example also my server is Linux at godaddy how I can decide which kind of Linux ?
Other suggestions that wkhtml2pdf are welcome

A: I would recommend a VPS from digitalocean or a VPS from the provider you desire with root access. I used Debian and CentOS without problems. As for today, use the binary from the site because it contains the patched QT version and will eliminate the issues with zoom feature.
I created a gist with minimal sample code to output pdf file to browser here https://gist.github.com/alpenzoo/b3d4b2ae144d00fe2b8d442d03d7fd50


text:
Q: CanvasRenderingContext2D drawImage() not correctly working in Chrome I am currently working on a web-application. As part of it I am creating SVG-images internally. When it comes to rendering, I used the approach provided in this question in order to convert the svg to a bitmap and displaying it on a canvas: https://stackoverflow.com/a/23667012/5767042
Most of the times this works fine, however sometimes it does not render the SVG image. Using the chrome DevTools, I was able to confirm that the object being passed to drawImage() (in the example below this would be imageBitmap) is the same in every call, however sometimes it gets rendered and sometimes it does not. I don't understand this behaviour at all.

var svgStr = "<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"100\" height=\"100\" shape-rendering=\"crispEdges\" stroke-linecap=\"square\"><line x1=\"0\" y1=\"0\" x2=\"50\" y2=\"50\" stroke=\"rgb(0,0,0)\" stroke-width=\"4\"\/><line x1=\"0\" y1=\"50\" x2=\"50\" y2=\"0\" stroke=\"rgb(0,0,0)\" stroke-width=\"4\"\/><\/svg>";

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var imageBitmap = new Image();
imageBitmap.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr);
console.log('drawing bitmap');

ctx.drawImage(imageBitmap, 0, 0);
<canvas id="myCanvas" width="200" height="100"></canvas>

Am I using drawImage() in a wrong way? I had the same behaviour in Firefox, Edge doesn't work at all. I also tested it on three different machines, no difference.

A: You need to wait until the image is finished loading. For that you can use the .onload handler of the image, which is called when it's loaded.

var svgStr = "<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"100\" height=\"100\" shape-rendering=\"crispEdges\" stroke-linecap=\"square\"><line x1=\"0\" y1=\"0\" x2=\"50\" y2=\"50\" stroke=\"rgb(0,0,0)\" stroke-width=\"4\"\/><line x1=\"0\" y1=\"50\" x2=\"50\" y2=\"0\" stroke=\"rgb(0,0,0)\" stroke-width=\"4\"\/><\/svg>";

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var imageBitmap = new Image();
imageBitmap.src = 'data:image/svg+xml;base64,' + window.btoa(svgStr);

function drawBitmap() {
  console.log('drawing bitmap');

  ctx.drawImage(imageBitmap, 0, 0);
}

imageBitmap.onload = drawBitmap;
<canvas id="myCanvas" width="200" height="100"></canvas>


text:
Q: Java RTSP get contents Can I download the contents from an RTSP url in java? Just like we can get contents of an HTTP url as an InputStream...
Thanks
Chris

A: Java uses "protocol handlers" to determine how to retrieve the resource identified by a URL.  It's not limited just to the HTTP/HTTPS.
Apparently the Java Media Framework API can access RTSP resources.  I don't know if it installs a protocol handler for RTSP or if it uses some different strategy.  Google for Java Media Framework RTSP for all the details.


text:
Q: How to see cut off inline js in chrome dev tools I have a problem to check the inline js hiding behind the ... in chrome dev tools. When I put "$0" in the console it gets me exactly the same js as text with the cut off lines indicated by the "..."
How do I get the full inline code?


text:
Q: ¿Cómo crear una aplicación que se adapte a todas las pantallas? Creo que esto es una pregunta novata, pero por alguna razón no he podido encontrar una solución a esto.
¿Cómo creo una aplicación que se visualice bien todas las vistas en diferentes resoluciones de pantalla?
¿Debo crear una carpeta para cada tipo de pantalla como las imágenes? ¿Este es un enfoque correcto? ¿O todo esto se soluciona con los contenedores?
Soy bastante malo para este tema del diseño, espero alguien me pueda ayudar.

A: En javahispano hay una buena traducción correspondiente al original de la documentacion de Android.

Resumen y puntos mas importantes:
Android 1.6 (API de nivel 4).

A la hora de desarrollar una aplicación Android deberemos tomar varias decisiones muy importantes, como puede ser, el nivel de API mínimo que vamos a soportar y el tamaño de pantalla de los dispositivos para los que nuestra aplicación va a estar optimizada.
Lo mismo sucede respecto al tipo de pantallas que la aplicación va a tener en cuenta. Una de las ventajas de Android es que cualquier fabricante puede diseñar un teléfono, con las características que desee y utilizar como sistema operativo Android. También, permite, que no sólo sea un sistema operativo móvil, ya que puede utilizarse en múltiples dispositivos, relojes, tabletas, televisiones, etc. Sin embargo, el desarrollador tendrá que pensar qué tipo de dispositivos y tamaños va a querer que puedan utilizar su aplicación. Para ello, vamos a ver qué mecanismos nos ofrece Android para poder utilizar nuestra aplicación en distintas pantallas.
Los rangos de tamaño de pantalla que vamos a poder manejar son:
small: para pantallas pequeñas.
normal:
large: para dispositivos con pantallas grandes.
xlarge: para el resto de los dispositivos con pantallas más de 7 pulgadas.

Crear recursos para pantallas distintas.

Por defecto, trabajando con dps y el atributo "wrap_content", Android redimensiona los layouts de nuestra aplicación, ajustándoles a la pantalla del dispositivo. Esto será suficiente para casi todos los casos. Sin embargo, puede, que en pantallas grandes, queramos aprovechar el mayor espacio para variar la distribución, poder separar más los elementos, ampliarles, etc, o en pantallas pequeñas tener que ajustar nuestro diseño a la disminución del espacio disponible. Para ello, es necesario crearnos un layout para cada grupo de tamaño que queramos que muestre un aspecto distinto. Estos layouts, hay que guardarles dentro de la carpeta resources. Para cada tamaño, crearemos una carpeta del tipo "layout-xlarge/", "layout-small/", etc.

Android 3.2 (API de nivel 13).

A partir de Android 3.2 (Api 13), estos grupos son deprecados, a favor de las nuevas técnicas de manejo de pantallas, que se basan en el ancho de la misma y que veremos más adelante.
Igualmente, tenemos cuatro grupos generales para la densidad:
ldpi: (low) para densidades bajas
mdpi: (medium): densidades entre 130 y 180 dpis aproximadamente.
hdpi: (high) para pantallas con densidades altas.
xhdpi: (extra high) para pantallas con más de 270 dpis aproximadamente.

Trabajar con layouts para tablets a partir de Android 3.2

Todo lo referente a los cuatro grupos de tamaños de pantallas es sólo vigente hasta Android 3.2. A partir de esta versión, se ha creado un nuevo sistema de gestión de los tamaños de pantalla, basándose en el ancho o alto de las mismas, siempre expresado en dp.
Tenemos disponibles los siguientes nuevos calificadores de recursos para crear nuestras carpetas contenedoras de los layouts:

*

*swdp: Por ejemplo, sw600dp o sw720dp. El tamaño que vamos a necesitar en el layout, indicado por la dimensión más corta del área de pantalla disponible. Es decir, el menor ancho o alto posible para la pantalla.
  Si nos creamos un layout dentro del recurso "res/layout-sw600dp", este se usará por el sistema, siempre y cuando la pantalla, da igual en la orientación en que esté, alcance los 600 dp.

*wdp: indica el ancho mínimo disponible en dp para poder utilizar los recursos. Si cambiamos la orientación se buscará un nuevo recurso que se corresponda con el nuevo ancho. Por ejemplo, w720dp.
  hdp: Por ejemplo, h720dp o h1024dp. Igual que el anterior, pero en este caso, se controla el tamaño de la altura de la pantalla.

A: La respuesta a esto es usar el Constraint layout, que permite realizar layouts que se adaptan a cualquier tamaño.
De lo contrario con este método tendrías que crear varios layouts, este método en un futuro se descartara.


text:
Q: Flask request.get_json(force=True) when using JavaScript only raises BadRequest? I have looked at these Stack Overflow links Flask request.get_json() raise BadRequest, Get raw POST body in Python Flask regardless of Content-Type header, and How to get POSTed JSON in Flask?; however, they don't answer my problem. When I use Postman, Python, or curl, my flask code works; however, when I use JavaScript, it doesn't work and I get the BadRequest error. April does print at first; however, the error pops up on the web page. When I try to run json.loads(request.data, strict=False) I get this jinja2 error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I think it might be the Javascript code I am using. Is it possible that concurrently running the request and the form submission might be the problem?
routes.py
@app.route('/calendar/', methods=['GET', 'POST'])
def calendar():
if request.method == 'POST':
    data = request.get_json(force=True)
    print(data['month'])
if form.validate_on_submit():
    pass

html
<form action="" onsubmit="myFunction()" method="POST">
</form>

function myFunction() {
    var data = "{\"month\":\"April\"}";

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function() {
          if(this.readyState === 4) {
           console.log(this.responseText);
          }
    });
    xhr.open("POST", window.location.href);
    xhr.setRequestHeader("Content-Type", "application/javascript");
    xhr.setRequestHeader("Cookie", "session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjoiNmM5MmIxNmFkYWIyMWZmZjk3MWE4MmJkZTViNTc1M2ZmMDNiY2MxNyJ9.Xo0X5Q.bzl4ihYLaHjUqmiIc6WCwFUOP_8");

    xhr.send(data);
}

EDIT#####

content = request.get_json(silent=True)
    print(content['month'])

prints None

A: I ended up adding to an existing form:
$("#form").submit( function(eventObj) {
                $("<input />").attr("type", "hidden")
                .attr("name", "month")
                .attr("value", "April")
                .appendTo("#form");
            return true;
            });

A: $(document).on('click','#texthide',function(){

        var text = $("#textVal").val();
        var font = $("#font_text").val();
        var color = $("#color_text").val();
        var start_text = $("#start_text").val();
        var end_text = $("#end_text").val();
        var vid_id = new_d
        console.log(text);
        $('body').addClass('addLoader');
        $.ajax({
            url: '/videos/test_text',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            datatype: "json",
            // data: $('#formtext').serialize(),
            data: JSON.stringify(

            {   text: $("#textVal").val(),
                font: $("#font_text").val(),
                color:  $("#color_text").val(),
                start_text: $("#start_text").val(),
                end_text: $("#end_text").val(),
                video_id: new_d
            })

            // onComplete:function(data){
            //     $('body').removeClass('addLoader');
            // }
        });
    });

    @videos.route("/test_text", methods = ['POST'])

    def test_text():

        data = request.get_json("")
        print(data)

        return "success!"


text:
Q: How do I make an Adobe Flash/Flex Chart Component "from scratch" (with AS3/MXML)? I'm interested in creating a Adobe Flash UI component for charting/graphing. I'm not interested in a library to do the charting; rather, I'm looking for books, articles, or open-source projects from which I could learn to develop a charting component (ie. one that extends the Sprite logical base class if done in pure ActionScript 3.0 Flash, or perhaps UIComponent/ChartBase/CartesianChart if done in Flex).
Please tell me some resources, books and stuff that I could use to create this component "from scratch".
See also Adobe Flash: Making an Interactive Charting UI Component "from scratch" (without Flex) for the specific case of a non-Flex charting component. That is, in Flash with pure ActionScript 3.0.

A: The best and easiest graphics framework I've seen is degrafa .
Here is a brief comparison between degrafa and the native drawing api.
I believe that much of the way degrapha does things has been worked into the new flex 4 (but still in beta) framework.
For specific charts Axiis is an open source data visualization framework built using degrafa.
For creating components these MAX presentations should jump start you:
Creating new components in flex 3.
Diving deep with the flex component lifecycle.

A: I've tried it myself and didn't think it was the hassle to do it from scratch. My best advice to you is to use Flex built in chart controls. But if you prefer to do it manually so the first thing to do is to do some rectangles, if you want to do a bar chart.
 http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Graphics.html

A: Take a look at Open Flash Chart. Nice looking charts with source code written in Flash. Even if you want to write your own, you can take a look at some code to get some ideas.

A: An interesting book that could help you is "Flex 4 fun". But the book covers only the graphics part of the problem. It could be a start...


text:
Q: Changing just one border of a cell's (top, left, etc.) thickness. Making a table, and I can't seem to figure out how to make a < t d >'s top border thickness greater than the other 3 sides even after all of the research I've done. I was hoping I could do something along the lines of  but can't figure it out. Ideas?

A: You can do

table, th, td {
   border: 1px solid black;
}

td {
   border-top: 5px solid red;
}

  This is 1st td
  This is 2nd td

  this is it
  it is this

  another this is it
  another it is this

I've made td top border 5px and red color, you can change it accordingly.
NOTE: HERE I'VE ADDED TOP BORDER THICKNESS FOR ALL . IF YOU WANT FOR FEWER THEN YOU NEED TO CREATE CLASS FOR THAT AND APPLY CSS TO IT.
POST IN COMMENT IF YOU'RE LOOKING FOR SOMETHING ELSE.
Running example


text:
Q: Android intent-filter for .kml files not working I am trying to accept ACTION_SEND for .kml files. Here's the manifest code:
<intent-filter>
  <action android:name="android.intent.action.SEND" />
  <data android:mimeType="application/vnd.google-earth.kml+xml"/>
  <data android:pathPattern=".*\\.kml"/>
  <category android:name="android.intent.category.DEAFULT" />
</intent-filter>

The app builds fine, but I tried two methods to click on .kml file:
1) test.kml attachment in Google Mail app.
2) Using a file browser, and using it to click on file name, and click on Send. It only shows Google Earth and Gmail as the receiving apps.
I tried with and without the pathPattern, no change, still does not receive any intents.
I also tried testing .txt files, using mimeType="text/*" and then my app showed up for .txt files. It just seems that the mimeType for .kml is not being recognized.
Has anyone successfully received intents for .kml files to launch their app? Any ideas?

A: Is it because you mispelled DEFAULT? (DEAFULT)


text:
Q: Cannot convert char[33] to LPCTSTR or if I typecast to LPCTSTR desired results not getting I am trying to use listbox.Addstring(); in MFC application which will take LPCTSTR.
I am passing a variable of char array that's 33 chars long.
ListBox.AddString(Adapter_List->pScanList->network[0].szSsid);

SzSsid is declared as char szSsid[33];
I am facing two problems:
1) if I typecast to LPCTSTR like
ListBox.AddString( (LPCTSTR ) Adapter_List->pScanList->network[0].szSsid );

I am not getting correct output - there are some Chinese characters displaying. I know it's some unicode problem but I am not knowledgeable about unicode.
2) if I dont typecast I get an error

Cannot convert char[33] to LPCTSTR

I am trying to build an MFC application which will display all access points. In szSsid I am able to see access point names.

A: LPCTSTR type-casting is just wrong. You may want to use an ATL conversion helper like CA2T to convert from char string to TCHAR (LPCTSTR) string, or CA2W to convert from char string to Unicode UTF-16 wchar_t string; e.g.:
// CA2T - Uses the TCHAR model (obsolete)
ListBox.AddString( CA2T(Adapter_List->pScanList->network[0].szSsid) );

or:
// CA2W - Conversion to Unicode UTF-16 (wchar_t) string
// More modern approach.
ListBox.AddString( CA2W(Adapter_List->pScanList->network[0].szSsid) );

But, more important, what is the encoding used by your char szSSid[] string? You may want to specify that encoding identifier (e.g. CP_UTF8 for UTF-8 strings) to CA2W constructor nCodePage parameter for proper conversion to Unicode UTF-16 string passed to AddString() method.


text:
Q: Flink vs Spark deployment modes on multi-node Cluster In Spark, the three cluster (not local) deployment options that I am familiar with:

*

*Standalone

*Mesos

*Yarn

There might be more cluster deployment options but I am concerned with these three. All the three above support client and cluster modes of deployment. The client mode involves the driver program being run from the edge machine itself and the cluster mode involves launching the driver in one of the worker nodes inside the cluster.
Now on the side of Flink, I only have experience with a 1 node setup which I learned from some tutorial which did not really elaborate on the ecosystem and was focussed more on code than "also" providing a big picture. I was looking at deployment options in Flink, therefore, to understand this. The documentation talks about the all the three options: Standalone, Mesos and YARN but it's not becoming clear from the docs if it supports (, what we in Spark's jargon would term as) the client mode or the cluster mode or both or some other mode.
The idea is to replace a Spark cluster with a Flink one. I want to understand the steps while I carry those out. The steps are available in the docs. The rationale behind those steps are either implicit (enough for me to not understand) or are just not there.
An explanation by Apache Flink experts/contributors would help.

A: There was recently a discussion about this topic on the Flink mailing list:
(Topic name: [DISCUSS] Semantic and implementation of per-job mode)
https://lists.apache.org/thread.html/6c688a73b281d38670a74f05d63f2858f59da1f37bc7211640de7ca8@%3Cuser.flink.apache.org%3E
Currently, all job submission from the flink CLI works like client mode in Spark.
An opt-in option to have something similar to cluster mode will probably be available in future (As it seems to be indicated on the mailing list), especially due to the rapidly increasing number of flink deployments in Kubernetes clusters.


text:
Q: createNativeQuery mapping to POJO (non-entity) I have an easy problem at the first glance:
entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla")

And I want to write select result into POJO, like this:
public class AggregateStatsDto {

    private int total;

    private long totalSum;

    // getters, setters, cosntructors
}

What the best way to achieve this?
I can use JPA 2.1 and tried to use @SqlResultSetMapping in conjuction with @ConstructorResult:
@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
        @ConstructorResult(targetClass = AggregateStatsDto.class,
                columns = {
                        @ColumnResult(name = "total"),
                        @ColumnResult(name = "totalSum")
                })
})
public class AggregateStatsDto {

        private long total;

        private int totalSum;

        // getters, setters, cosntructors
    }

Query:
AggregateStatsDto result = (AggregateStatsDto) entityManager()
    .createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla", "AggregateStatsResult")
    .getSingleResult();

But no luck. It seems that it wants @Entity anyway. But I want just a POJO.
org.hibernate.MappingException: Unknown SqlResultSetMapping [AggregateStatsResult]"

Thanks in advance!

A: I resolved my problem in following way:
This is a query:
  final Query query = Sale.entityManager().createNativeQuery(...);

Then I accessed to internal Hibernate session inside entity manager and applied scalars/resultTransformer. Thats all!
 // access to internal Hibernate of EntityManager
        query.unwrap(SQLQuery.class)
                .addScalar("total", LongType.INSTANCE)
                .addScalar("amountOfSales", LongType.INSTANCE)
                .addScalar("amountOfProducts", LongType.INSTANCE)
                .setResultTransformer(Transformers.aliasToBean(SaleStatsInfo.class));

        ...
        query.getSingleResult();

A: Put your @SqlResultSetMapping annotation in a class which is an actual entity, not in the DTO Class.  Your entity manager can not discover your mapping when you annotate a SqlResultSetMapping in a non-entity.
@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
    @ConstructorResult(targetClass = AggregateStatsDto.class,
            columns = {
                    @ColumnResult(name = "total"),
                    @ColumnResult(name = "totalSum")
            })
})
@Entity
public class SomeOtherClassWhichIsAnEntity {

A: This is not the suggested way . The more efficient way is mentioned above with @SqlResultSetMapping but in case you want something more hardcore you can access the Entity Manager's result by the object it returns .
For instance :
 Query q = getEntityManager().createNativeQuery(queryString);

Trggering that with  q.getSingleResult();brings back to u an Object of type  java.util.HashMap which you can use to access your results row by row .
For instance:
    Query q = getEntityManager().createNativeQuery(queryString);
    java.util.HashMap res =  (java.util.HashMap) q.getSingleResult();
     for (Object key : res.keySet()) {
         System.out.println(key.toString());
         System.out.println( res.get(key).toString());
     }

A: I was stuck for a while on this one. I found that the most common solution is below. Do not forget to add name of the mapping on the createNativeQuery method 2nd parameter. Your pojo should then have no annotations but will be get mapped from entity class.
//Place SqlResultSetMapping annotation in Entity class:

@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
        @ConstructorResult(targetClass = AggregateStatsDto.class,
                columns = {
                        @ColumnResult(name = "total"),
                        @ColumnResult(name = "totalSum")
                })
})
@Entity
public EntityFromExistingTableInDB{
    ...fields
}

//1st param is your query, 2nd param is the name of your mapping above
Query query = entityManager.createNativeQuery("yourQuery", "AggregateStatsResult");

A: Hibernate will fill any pojo if you privide a propper constructor.
select new Pojo(p1, p2, p3,...) from entity)
will return a list of Pojo instances.

A: I struggled a lot in this issue and finally a found a good solution.
Situation: I have a native query and I am fetching only few fields or all fields from the database table or may be I also have some operations on columns while I am fetching data from table.
Now I want to map the output of this nativequery which we get using getResultList() method into a own POJO class/non-JPA class. The output of getResultList() is a list of objects i.e. List, so we need to manually loop through and set values into our bean/pojo class. Looks at the snippet below.
So my query is this -
// This is your POJO/bean class where you have settter/getter
// methods of values you want to fetch from the database
List<YourPOJO> yourPOJOList = new ArrayList<YourPOJO>();
YourPOJO pojo = null;

StringBuffer SQL = new StringBuffer();
// I am creating some random SQL query
SQL.append("SELECT tb1.col1, ");
SQL.append(" tb1.col2, ");
SQL.append(" tb2.col3, ");
SQL.append("FROM Table1 tb1, Table2 tb2 ");
SQL.append("WHERE tb1.ID = tb2.ID       ");

qry = getEntityManager().createNativeQuery(SQL.toString());
List<Object[]> cdList = qry.getResultList();

for(Object[] object : cdList){
pojo = new YourPojo();

// Here you manually obtain value from object and map to your pojo setters
pojo.setCode(object[0]!=null ? object[0].toString() : "");

pojo.setProductName(object[1]!=null ? object[1].toString() : "");

pojo.setSomeCode(object[2]!=null ? object[2].toString() : "");

yourPOJOList.add(pojo);
}

A: ANSWER MAY BE MISSING INFORMATION
Here is the most direct way to do it in my opinion.
Declare a POJO/DTO and label it with @NativeQueryResultEntity.  Note I am using Lombok @Data to declare getters/setters here.
import com.pls.core.jpa.nativequery.NativeQueryResultEntity;
import lombok.Data;

@Data
@NativeQueryResultEntity
public class FieldsDTO{

    @NativeQueryResultColumn(index = 0)
    private String fieldA;

    @NativeQueryResultColumn(index = 1)
    private String fieldB;

    @NativeQueryResultColumn(index = 2)
    private String fieldC;
}

Then use NativeQueryResultsMapper
String queryStr = "select field_a, field_b, field_c from db.table"
Query query = entityManager.createNativeQuery(queryStr);
List result = NativeQueryResultsMapper.map(query.getResultList(), FieldsDTO.class);

That's all you should need to do.  result will be a list of FieldsDTO objects.


text:
Q: Are there limitations to how often I can concuss my opponent? In DiveKick, headshots (when your foot connects with the opponents head) are supposed to put them into a concussed state. (Limited movement/dick and kick).
However, sometimes headshots don't give the opponent a concussion (at least in my experience playing lately). Are there limits to how many consecutive rounds this can happen? Or any other prohibiting factors?

A: Mr. N's neck pillow protects him against one headshot per fight.

Mr. N's neck pillow protects him from one head shot every fight, preventing him from going into the concussed state that would normally follow a headshot. However, any subsequent head shots in the fight will concuss him as normal.
- Divekick Wiki - Mr. N

Mr. N is the only character who can cancel a headshot. Once his neck pillow is removed, there are no limits to how many times you can headshot him.


text:
Q: Is it necessary to restart tomcat when redeploy a war? I know Tomcat can reload the .war file when redeploy it, I don't need to kill the Tomcat process and restart it. I can remove the .war, wait for Tomcat to undeploy it, and copy the new .war to the web path. But, after many times of trivial update war without restart the Tomcat, is it possible that Tomcat will not release the memory effectively or cause some performance issues? Assume there is only one war application in one Tomcat instance.

A: The basic problem is that Java does currently not provide any kind of isolation between the parts of code running in a Java Virtual Machine (JVM), in the same way that an operating system does with processes.  You can kill a process without affecting another process under Windows/Linux/etc.  All you can do is ensuring that things can be garbage collected.
For Tomcat the way that WAR's are being handled - according to the various specifications - require that each war has its own classloader that is responsible for running that code.  When the WAR is undeployed the final result should be that that class loader should be garbage collected.
Unfortunately the garbage collector can only handle objects that are completely unreferenced, and there is a large set of subtle bugs that can be present in WAR code that can prohibit this, and then every redeploy cause another classloader to be created and none destroyed so you have a memory leak.   A lot of effort has gone into detecting and working around these type of bugs inside Tomcat itself, but it is close to impossible to do 100% right without JVM support.
The only cure besides fixing the WAR is to restart the JVM.
You can watch the memory usage with VisualVM even in production to see what happens over time with the Tomcat JVM.

A: Yes. It is far cleaner to stop Tomcat, deploy your new war, then restart Tomcat. One drawback is much of your application classes by default won't be loaded till a new request comes in to hit your application but its not a huge issue. Just means theres a few seconds of startup on the very first request to your new WAR. This is how we deploy wars in production.
Also allows us to setup health-checking in the logs if the new war prevents Tomcat from starting up correctly then we rollback the war knowing theres an issue, but thats a separate topic.
What About Down Time?
This might be out of scope of your question but when you want to prevent users from seeing any downtime you would run multiple instance of tomcat and deploy and restart one at a time.


text:
Q: Erro ao executar um comando Flutter Para testar se o flutter foi corretamente instalando na minha máquina Linux eu escrevi na bash o seguinte comando : flutter doctor e recebi a seguinte mensagem de retorno :

zsh: command not found: flutter

A minha tentativa foi passar o caminho para o SDK do meu Flutter export PATH=$HOME/bin:/usr/local/bin:$PATH:/home/gabriel_rc/flutter , porém não funcionou.
Como posso resolver este problema?

A: Pela mensagem de erro você está usando o zsh e não o bash.
Então edite suas variáveis de ambiente no arquivo .zshrc na raíz do seu usuário, se ele não existir, crie com:
export PATH=/home/gabriel_rc/flutter/bin:$PATH

A: 1) Abra o arquivo .bashrc que está na sua /home/gabriel_rc
2) Adicione esta linha de código por último no arquivo
export PATH="$PATH:/home/gabriel_rc/flutter/bin"

3) Salve as mudanças do arquivo e reinicie a sessão do terminal(só fechar o terminal e abrir novamente)
Veja a documentação aqui para a instalação linux


text:
Q: Generar fechas aleatorias Estoy realizando un programa que genera fechas aleatoriamente y las imprime, si la fecha cae en un día festivo, imprime un mensaje tal como: ¡Feliz Halloween!
Ahora, si el mes elegido es febrero y el día es uno que febrero no tiene, como 29, 30 o 31, se le resta 3 al día. Lo mismo con los demás meses que sólo tienen 30 días.
Pero me resulta tedioso ejecutar la función cada vez que quiero que se genere una fecha, entonces quiero que al principio del programa, me pregunte por la cantidad de fechas que quiero que se generen, y que las imprima a una lista, todas al azar.
He aquí el programa:
import random
def fechas():
#La lista de meses y días posibles

meses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
dias = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

#Elije un mes y un día al azar

m = random.choice(meses)
d = random.choice(dias)

#Si a ciertos meses se le asigna un día más alto se le resta 3 o 1 al día.

if m == "febrero" and d == 31 or d == 30 or d == 29:
    d = (d)-3
if m == "abril" and d == 31:
    d = (d)-1
if m == "junio" and d == 31:
    d = (d)-1
if m == "septiembre" and d == 31:
    d = (d)-1
if m == "noviembre" and d == 31:
    d = (d)-1

#Si la fecha coincide con una festiva, imprime un mensaje

if m == "enero" and d == 1:
    print("¡Feliz año nuevo!")
if m == "octubre" and d == 31:
    print("¡Feliz Halloween!")
if m == "diciembre" and d == 24:
    print("¡Feliz navidad!")
print(str(d) + " de " + str(m) + ".")

Quiero saber cómo hacer lo dicho anteriormente, y que automáticamente genere la cantidad de fechas que yo quiera.

A: Para facilitar un poco el tema con los días de cada mes podrías usar el módulo calendar. Usando la función monthrange cuyo segundo parámetro retorna la cantidad de días del mes (como los días de febrero para años bisiestos):
>>> import calendar
>>> calendar.monthrange(month=2, year=2017)
(2, 28)
>>> calendar.monthrange(month=2, year=2020) # Bisiesto
(5, 29)
>>> calendar.monthrange(month=12, year=2020)
(1, 31)

Por cierto, el primer parámetro es el día de la semana del primer día del mes (contando desde 0 como lunes). Con la cantidad de días del mes vas a poder validar el día correcto como verás más adelante.
Me parece que también te vas a complicar si trabajas con los meses como texto en vez de números (eso lo puedes formatear después):
>>> dias = range(1, 32) # No se incluye el 32
>>> meses = range(1, 13) # No se incluye el 13

Para los días festivos puedes mapear las fechas que quieras como tuplas del tipo (mes, dia) o (dia, mes) como prefieras:
>>> festividades = {
...   (1, 1): '¡Feliz año nuevo!',
...   (31, 10): '¡Feliz Halloween!',
...   (25, 12): '¡Feliz Navidad!'
... }

Juntando un poco todo en un script:
# -*- coding: utf-8 -*-
import calendar
from datetime import date, datetime
import random

def fechas(dia=None, mes=None):
    mensajes_festivos = {
        (1, 1): '¡Feliz año nuevo!',
        (31, 10): '¡Feliz Halloween!',
        (25, 12): '¡Feliz Navidad!'
    }
    hoy = date.today()

    # Si no hemos pasado el día o el mes en la función seleccionamos un al azar
    if not dia:
        dia = random.choice(range(1, 32))
    if not mes:
        mes = random.choice(range(1, 13))

    # Hay que usar el día válido, verifiquemos que no se pase del rango. No nos
    # interesa por ahora el primer parámetro retornado, solo la cantidad de días
    # del mes
    _, dia_maximo = calendar.monthrange(year=hoy.year, month=mes)
    if dia > dia_maximo:
        dia = dia_maximo

    # El mensaje final es una mezcla del mensaje festivo junto con el mensaje de
    # la descripción del día. Si no hay día destivo mapeado simplemente no se
    # imprime nada
    fecha = date(hoy.year, mes, dia)
    mensaje = [
        fecha.strftime('%d de %B del %Y')
    ]
    mensaje_festivo = mensajes_festivos.get((dia, mes), '')
    if mensaje_festivo:
        mensaje.append(mensaje_festivo)

    # Mostrar mensaje
    print(' '.join(mensaje))

if __name__ == '__main__':
    fechas() # Sin parámetros, dia y mes al azar
    fechas(dia=31, mes=10) # Probemos con Halloween
    fechas()
    fechas(dia=31, mes=2) # ¿31 de febrero? Hmm, no.
    fechas(dia=25, mes=12) # ¿Qué tal con Navidad?

Mi script se llama prueba.py, vamos a ejecutarlo:
$ python3 test.py
02 de May del 2017
31 de October del 2017 ¡Feliz Halloween!
20 de February del 2017
28 de Frebruary del 2017
25 de December del 2017 ¡Feliz Navidad!

Funciona pero ¡ugh!... está en inglés. Puedes usar el maravilloso babel para solucionar este problema.
$ sudo pip3 install babel
Collecting babel
  Downloading Babel-2.5.1-py2.py3-none-any.whl (6.8MB)
    100% |████████████████████████████████| 6.8MB 85kB/s
Requirement already satisfied: pytz>=0a in /usr/local/lib/python3.5/dist-packages (from babel)
Installing collected packages: babel
Successfully installed babel-2.5.1
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from babel.dates import format_date
>>> from datetime import date
>>> format_date(date(2017, 10, 31), locale='es')
'31 oct. 2017'
>>> format_date(date(2017, 10, 31), format='long', locale='es')
'31 de octubre de 2017'

¡Excelente! Ahora solo hay que agregarlo al script y tenemos todo listo (esta vez sin todos los comentarios):
# -*- coding: utf-8 -*-
import calendar
from babel.dates import format_date
from datetime import date, datetime
import random

def fechas(dia=None, mes=None):
    mensajes_festivos = {
        (1, 1): '¡Feliz año nuevo!',
        (31, 10): '¡Feliz Halloween!',
        (25, 12): '¡Feliz Navidad!'
    }
    hoy = date.today()

    if not dia:
        dia = random.choice(range(1, 32))
    if not mes:
        mes = random.choice(range(1, 13))

    _, dia_maximo = calendar.monthrange(year=hoy.year, month=mes)
    if dia > dia_maximo:
        dia = dia_maximo

    fecha = date(hoy.year, mes, dia)
    mensaje = [
        format_date(fecha, format='long', locale='es_PE')
    ]
    mensaje_festivo = mensajes_festivos.get((dia, mes), '')
    if mensaje_festivo:
        mensaje.append(mensaje_festivo)

    print(' '.join(mensaje))

if __name__ == '__main__':
    fechas() # Sin parámetros, dia y mes al azar
    fechas(dia=31, mes=10) # Probemos con Halloween
    fechas()
    fechas(dia=31, mes=2) # ¿31 de febrero? Hmm, no.
    fechas(dia=25, mes=12) # ¿Qué tal con Navidad?

Vemos ahora:
$ python3 test.py
26 de julio de 2017
31 de octubre de 2017 ¡Feliz Halloween!
9 de mayo de 2017
28 de febrero de 2017
25 de diciembre de 2017 ¡Feliz Navidad!

Todo listo.

A: En cuanto a tu código, tienes ya casi todo resuelto, lo único que deberías hacer es lo siguiente:
cant = int(input("Cantidad de Fechas a generar:"))
for i in range(cant):
  fechas()

Es decir, le solicitamos al usuario una cantidad de fechas por teclado, mediante input(), debemos convertirlo a un número entero (usando int()), por que el retorno es una cadena. Luego simplemente un ciclo for para iterar las veces solicitadas, para eso usamos range() que es un generador de secuencias y nos dará el conjunto de números de 0 a n-1. Luego simplemente invocamos tu rutina. Si quisieras guardar todos los datos en una lista, deberías hacer que fecha() retorne el texto en vez de imprimirlo por pantalla, para eso deberías asignarlos valores que imprimes a una variable y retornarla de la función, luego simplemente la vas agregando a una lista, o también podrías resolverlo todo en la función...
Algunos temas de implementación los resolvería de otra forma, veamos:

*

*Los if para poder ajustar la cantidad de días se podría resolver si previamente contamos con la lista de fechas ya generada

*Las fechas festivas se pueden manejar mejor en un diccionario para evitar también el uso de tantos if.

*Lo otro que me hace "ruido" es hacer un random sobre días y meses, por que no es una distribución uniforme, hay días que aparecen más que otros y además si eventualmente pides un año entero, es muy probable que se repitan días.

Por todo esto, te cuento como implementaría tu rutina:
from random import shuffle
import datetime

def fechas(year=2017, cantidad=1):
  base = datetime.datetime(year,1,1)
  date_list = [(d.month, d.day) for d in [base + datetime.timedelta(days=x) for x in range(0, 366)] if d.year == year]

  meses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]

  fiestas = {(1,1):"¡Feliz año nuevo!",
            (12,25):"¡Feliz navidad!",
            (10,31):"¡Feliz Halloween!"
  }

  lista_fechas = []
  shuffle(date_list)
  for _ in range(cantidad):
    f = date_list.pop()
    fiesta = fiestas.get((f[0], f[1]), "")
    fiesta = fiesta + "\n" if fiesta else ""
    lista_fechas.append("{0}{1} de {2}.".format(fiesta, str(f[1]), meses[f[0]-1]))

  return lista_fechas

cant = int(input("Cantidad de Fechas a generar:"))
print(fechas(cantidad=cant))

Algunos comentarios:
  base = datetime.datetime(year,1,1)
  date_list = [(d.month, d.day) for d in [base + datetime.timedelta(days=x) for x in range(0, 366)] if d.year == year]

Con el código anterior generamos una lista de tuplas (mes, día) de un año completo, del año que le digamos, la función recibe el parámetro year que por defecto es 2017, al finalizar en date_list vamos a tener una lista del tipo [(1,1), (1,2) ... (12,31)]. Contemplamos también los años que sean bisiestos. Para todo esto nos apoyamos en (timedelta): base + datetime.timedelta  que nos devolverá un desplazamiento, en este caso de días desde la fecha base y tomando como intervalo un range(0, 366).
Las fechas festivas las manejamos como un diccionario, cada clave se corresponde con alguna de las tuplas anteriores, de manera que si un valor aleatorio corresponde a la tupla (1,1) de manera rápida y eficiente podemos a obtener la cadena correspondiente a la festividad (1,1):"¡Feliz año nuevo!".
El otro tema distinto a tu implementación es que en vez de randomizar días y meses, usamos una rutina del módulo random: shuffle(date_list) para desordenar de forma aleatoria la lista de fechas completa. De manera que luego, simplemente iteramos hasta la cantidad de fechas pedidas y recuperamos un valor y lo quitamos de la lista mediante f = date_list.pop() con esto nos aseguramos que si pedimos 365 o 366 valores nunca obtendremos un valor repetido. Luego simplemente agregamos este valor a una lista junto el eventual mensaje de día festivo:
fiesta = fiestas.get((f[0], f[1]), "")
fiesta = fiesta + "\n" if fiesta else ""
lista_fechas.append("{0}{1} de {2}.".format(fiesta, str(f[1]), meses[f[0]-1]))

Al finalizar tendremos una lista lista_fechas que contendrá las fechas en el formato planteado en tu pregunta y eventualmente el mensaje de salutación de la festividad. (por ahora todo concatenado para respetar tu pregunta pero puedes elegir cualquier otra forma de mostrar estos datos).


text:
Q: Show/Hide & Change CSS functions are not working After a form is submitted to an <Iframe> target on the page, and after the <iframe> finishes loading, there is 1 <div> that is suppose to hide, 2 <div> that need to show and 2 CSS changes that are all suppose to trigger, but they are not.
This is a fiddle of the page:
http://jsfiddle.net/mikeef74/gzSDH/17/
This is how I currently have the script:
var submit_hit = false;

$(document).ready(function () {
    $('#iframe1').on('load', function () {
        $('#loader1').hide();
        if (submit_hit) {
            $('#form_container').hide();
            $('#mydivhide1, #mydivhide2').show();
            $('body').css("background-image", "url(images/previewbg7.jpg)");
            $('body').css("overflow-y", "auto");
        }
    }
});

$("#form_710370").validate({
    submitHandler: function(form) {
        $("#loader1").show();
        form.submit();
    }
});

});

A: If this the full code you are not making submit_hit to true, i think its need to set true  before form.submit() so the js for div1/div2 execute.
 $("#loader1").show();
   submit_hit = true;
  form.submit();

JSfiddle update


text:
Q: Alert the object I am setting an object like this:
n.name = n.name.join(String.fromCharCode(255));
n.description = n.description.join(String.fromCharCode(255));

I want to be able to alert(n); but it tells me [Object]
Is there a way to alert complete object?

A: Javascript supports adding a toString() function to your objects.  This will get called when you alert your object.  For example:
n.toString = function(){
    return this.name + '\n' + this.description;
}

then alert(n); will display whatever content your function specifies.

A: I like the var_dump in php, so I often use a function like this to dump variables
function var_dump(object, returnString)
{
  var returning = '';
  for(var element in object)
  {
    var elem = object[element];
    if(typeof elem == 'object')
    {
      elem = var_dump(object[element], true);
    }
    returning += element + ': ' + elem + '\n';
  }
  if(returning == '')
  {
    returning = 'Empty object';
  }
  if(returnString === true)
  {
    return returning;
  }
  alert(returning);
}

A: I was asking the same kind of question as Autolycus today.  I'm using jqGrid and I wanted to see what the object it created actually was.  I didn't create the object and I wanted to see what it looked like.  I know it's probably old school, but I still use alerts in javascript for some of my debugging (though I agree FireFox & Firebug are the way to go for most things).
I found an answer to what I was looking for here:  http://javascript.internet.com/debug-guide.html, which is unbelievably old.
But I tweaked it to give me what I needed and since I think it answers Autolycus's question in a new way and I think someone else might be looking here, like me, for this someday, here it is:
obj = n;
var temp = "";
for (x in obj) {
    temp += x + ": " + obj[x] + "\n";
}
alert (temp);

I apologize in advance if answering an old question is breaking some kind of rule.
all best,
ember

A: There are a couple of alternatives:
1. Use http://www.gscottolson.com/blackbirdjs/
2. Use console.log() that comes with Firebug, but requires Firefox (even if you only target only IEs, it's still wise to use Firefox and Firebug as aprt of testing of your web app development)

A: It depends what you mean by alerting the complete object.
You can't really just output every object as a string and have it make sense. To define how an object will display itself as a string we use the .toString(); method.
So try alert(n.toString()); and see if that will give you what you want. If the object is your own, then define the toString(); and have it return a string of the parameters and fields that you want to output.

A: Something like...
alert(n.name);

...I think is what you want.
If you are trying to debug, you would be better suited to using FireFox/Firebug instead of inserting a load of alerts();


text:
Q: Is $\mathbb{Q}(2^{1/6})\cong\mathbb{Q}(\sqrt2)(2^{1/6})$ true? Solving a problem I have seen that
$m_{(2^{1/6},\mathbb{Q}(\sqrt 2))}=x^3-\sqrt2$
, $[\mathbb{Q}(2^{1/6}):\mathbb{Q}(\sqrt2)]=3$
Because $m_{(2^{1/6},\mathbb{Q}(\sqrt 2))}=x^3-\sqrt2$, $$\mathbb{Q}(\sqrt2)[x]/(x^3-\sqrt2)\cong\mathbb{Q}(\sqrt2)[2^{1/6}]\cong\mathbb{Q}(\sqrt2)(2^{1/6})$$
Does this mean that $\mathbb{Q}(2^{1/6})\cong\mathbb{Q}(\sqrt2)(2^{1/6})$?

A: $\mathbb{Q}(\sqrt2)(2^{1/6})= \mathbb{Q}(\sqrt2,2^{1/6}) = \mathbb{Q}(2^{1/6})$ because $\sqrt2=(2^{1/6})^3 \in \mathbb{Q}(2^{1/6})$.


text:
Q: PL SQL iterate loop through date range I have a date range, I am trying to take one date every week through a loop
DECLARE
  start_date DATE := TO_DATE('06.01.2021', 'dd.MM.yyyy');
  end_date DATE := TO_DATE('26.05.2021', 'dd.mm.yyyy');
  active_date DATE;
  start_number NUMBER;
  end_number NUMBER;
BEGIN
  start_number := TO_NUMBER(TO_CHAR(start_date, 'j'));
  end_number := TO_NUMBER(TO_CHAR(end_date, 'j'));
  active_date := start_date;
FOR cur_r IN start_number..end_number
  LOOP
   INSERT INTO test_tbl
   SELECT snap_date FROM s_act
   WHERE
    snap_date = active_date;
    active_date := TRUNC(active_date) + 7;
COMMIT;
END LOOP;
END;

When I execute this script, only one date 06.01.2021  is written to the table through all iterations.
Where am I making a mistake? How can this be fixed?

A: You do not need PL/SQL for this and can just use a recursive sub-query:
INSERT INTO test_tbl
WITH date_range ( start_date, end_date ) AS (
  SELECT DATE '2021-01-06', DATE '2021-05-26' FROM DUAL
UNION ALL
  SELECT start_date + INTERVAL '7' DAY,
         end_date
  FROM   date_range
  WHERE  start_date + INTERVAL '7' DAY <= end_date
)
SELECT snap_date
FROM   s_act s
WHERE  EXISTS(
         SELECT 1
         FROM   date_range r
         WHERE  r.start_date = s.snap_date
       );

or a hierarchical query:
INSERT INTO test_tbl
SELECT snap_date
FROM   s_act s
WHERE  EXISTS(
         WITH date_range ( start_date, end_date ) AS (
           SELECT DATE '2021-01-06', DATE '2021-05-26' FROM DUAL
         )
         SELECT 1
         FROM   date_range r
         WHERE  r.start_date + ( LEVEL - 1 ) * INTERVAL '7' DAY = s.snap_date
         CONNECT BY r.start_date + ( LEVEL - 1 ) * INTERVAL '7' DAY <= r.end_date
       );

If you really want to use PL/SQL then you can make it much simpler and iterate by weeks rather than days (however, this will be much less efficient as you will have one INSERT per week and the associated context switch from PL/SQL to SQL compared to the SQL solution which is only a single INSERT for the entire operation and no context switches):
DECLARE
  start_date  DATE := DATE '2021-01-06';
  end_date    DATE := DATE '2021-05-26';
  active_date DATE := start_date;
BEGIN
  LOOP
    EXIT WHEN active_date > end_date;

    INSERT INTO test_tbl
    SELECT snap_date FROM s_act
    WHERE  snap_date = active_date;

    active_date := active_date + INTERVAL '7' DAY;
  END LOOP;
END;
/

db<>fiddle here

A: To me, it looks as if everything is, actually, OK with code you wrote, because active_date gets its new value:
SQL> set serveroutput on;
SQL> declare
  2    start_date   date := to_date('06.01.2021', 'dd.MM.yyyy');
  3    end_date     date := to_date('26.05.2021', 'dd.mm.yyyy');
  4    active_date  date;
  5    start_number number;
  6    end_number   number;
  7  begin
  8    start_number := to_number(to_char(start_date, 'j'));
  9    end_number   := to_number(to_char(end_date, 'j'));
 10    active_date  := start_date;
 11
 12    for cur_r in start_number..end_number
 13    loop
 14      dbms_output.put_line('Active_date = ' || to_char(active_date, 'dd.mm.yyyy'));
 15      /* Commented, as I don't have your tables nor data
 16         INSERT INTO test_tbl
 17           SELECT snap_date
 18           FROM s_act
 19           WHERE snap_date = active_date;
 20      */
 21      active_date := trunc(active_date) + 7;
 22    end loop;
 23    -- move COMMIT out of the loop!
 24    commit;
 25  end;
 26  /
Active_date = 06.01.2021
Active_date = 13.01.2021
Active_date = 20.01.2021
<snip>
Active_date = 06.09.2023
Active_date = 13.09.2023

PL/SQL procedure successfully completed.

SQL>

You said

When I execute this script, only one date 06.01.2021 is written to the table through all iterations.

This is piece of code responsible for that:
INSERT INTO test_tbl
  SELECT snap_date
  FROM s_act
  WHERE snap_date = active_date;

I interpret it as:

*

*s_act table contains rows only with snap_date equal to 06.01.2021, or

*if it contains rows with other dates, maybe they contain a time component (hours, minutes, seconds) and where condition prevents them to be inserted. If that's so, try with
where trunc(snap_date) = active_date

and see what happens.


text:
Q: How to make a "global variable" with a table? In my program, I need to use a "global variable" which is D[M] (where M is a constant defined in the preprocessor directives)
The problem is that in the function I have in the program, the prototype isn't using D[M] (while the function is using it)
So I thought "If they call it a global variable, it means that the table is a constant, right ?" but I can't find a way to make a constant (#define) with a table (#define D[M] or #define D[])
Do you guys know what did they (my professor) meant by saying "The program use a global variable D, which is a table of M integers" ?
Here's my program if it can help (it's mostly french but i think it's understandable) :
http://pastebin.com/0WfRxa3e
(The purpose of this program is to find wether or not ' n ' (or ' u ' in the function) is a prime number + if it's a perfect number)
It's not finished yet as I wanted to check if the "while" condition worked as I wanted to..
Thanks a lot !

A:
The program use a global variable D, which is a table of M integers.

This is probably what is meant:
#define M 10
int D[M] = {0};
int main() {
  D[0] = 42; // can access array here, because it's a global variable
  return 0;
}

If they call it a global variable, it means that the table is a constant, right?

Global variables are not necessarily constant (read-only).
Note that preprocessor macros (#define ...) and constants (static const int ...) are not quite the same thing.
For further reading:

*

*https://en.wikipedia.org/wiki/Global_variable

*http://en.cppreference.com/w/c/language/scope

*http://en.cppreference.com/w/c/language/storage_duration

*http://en.cppreference.com/w/c/language/const

*Static, define, and const in C


text:
Q: readFileSync can't find file from URL I'm trying to download a file (without saving it) and convert it, but readFileSync throws an error that the file can't be found: "Error: ENOENT: no such file or directory, open 'https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt'"
Code:
var path = require('path');
const fs = require('fs');
const https = require('https');

const file_x = 'https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt';
var filename = path.basename(file_x);

const FileBuffer = fs.readFileSync(file_x);
const fileParam = {
    value: FileBuffer,
    options: {
      filename: filename,
      contentType: 'application/octet-stream'
    }
};

console.log(fileParam);

And I get the error the file can't be found... The URL is working OK, do I need to do something else to download from URL ?

A: Did you try looking for similar questions? For example, readFileSync not reading URL as file. There it is clearly stated that the fs API only deals with local files.
You will need to use the https module to stream the file.

A: The package fs only reads files, not URLs. Alternatively, you can use a package like axios. Axios allows you to make HTTP requests within node.js.
Example usage:
const axios = require('axios');
axios.get('https://s3.amazonaws.com/appforest_uf/f1631452514756x615162562554826200/testdoc.txt').then(response => {
    console.log(response);
    ...
});


text: Q: How to transfer sessionStorage to next tab I am using sessionStorage to store a value and when I open link in next tab sessionStorage automatically deleted. So can anyone tell me how to transfer sessionStorage to next tab. And I don't want  use localStorage.


text:
Q: Python route finder for aviation I made an app that besides all other things try to find a valid route between 2 airports.
I have all the required data in a sqlite3 database witch i query and plot in a basemap embeded in PyQt5 with signals live.
My problem is i can't find the algorithm to make all possible variations(with disqualify some, as all possibilies are enormous ) and store them to output the final valid routes.
Dijkstra's algorithm i think can't implemented as any time a route can reach a dead end.
My main problem is the algorithm and its implementation and not the data so don't hesitate and write any data required for any possible algorithm.
The algorith hints are:

*

*I have a starting waypoint.

*I find all routes that includes this starting point(disqualifying oposite headings)(each route have various waypoints).

*Find next waypoint for each route.

*Now this waypoint can be connected to other route and so on.

*Routes then tested and disquilyfied by various variants or reaching dead ends.

*Continue until you reach to the final(target waypoint).

*Output the somehow stored route(s)

What i got so far with stack issues:
##finding base direction##
base_radians = math.atan2(self.dest_coord[0]-self.dep_coord[0], self.dest_coord[1]-self.dep_coord[1])
base_degrees = math.degrees(base_radians)
print(base_degrees)
if base_degrees < 0 :
    base_heading = 'W'
else:
    base_heading = 'E'
### finding all routes connected to first waypoint###
self.cursor.execute("select DISTINCT ats_ident,seq_num from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",('ATV','LGGG',base_heading))
sub_ats_idents = self.cursor.fetchall()
#### for each route find next waypoints###
for i in sub_ats_idents:
    self.cursor.execute("select wpt1_ident,wpt2_ident from dafif_ats where ats_ident = ? and ats_icao = ?  and direction = ? and seq_num >= ? ORDER BY seq_num ASC",(i[0],'LGGG',base_heading,i[1]))
    each_wpt_combo = self.cursor.fetchall()
    #### for each next waypoint find possible routes###
    for x in each_wpt_combo:
        self.cursor.execute("select DISTINCT ats_ident,seq_num from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",(x[0],'LGGG',base_heading))
        each_ats = self.cursor.fetchall()
        print(each_ats)
        #### for each subroute plot waypoints###
        for z in each_ats:
            self.cursor.execute("select wpt1_dlon,wpt1_dlat,wpt2_dlon,wpt2_dlat from dafif_ats where wpt1_ident = ? AND ats_icao = ? AND direction = ? ORDER BY ats_ident,seq_num ASC",(x[0],'LGGG',base_heading))
            plot_var = self.cursor.fetchall()
            self.route_sender.emit(plot_var)
            time.sleep(0.1)

Any material or example to read will be super.
Thx in advance.

A: For future readers , A* algorithm with hieristics is the solution for these kind of problems.


text:
Q: Synchronizing stream outputs I am working on uploading different image sizes to the amazon s3 storage. Whenever I upload an image, I create three separate readable streams of the image and pipe it to my resizer functions and the s3 upload function.
Each of the streams uploads different size of an image to the s3 cloud. I would like the synchronize the outputs of the streams so that I can send the URLs of the uploaded photos when the uploading has completed in all of the three streams.
I am not able to know when all my streams have ended. Or how can I wait until all my streams have ended and then return the URLs of all the uploaded images?
Here is my code
resize.js
import fs from 'fs';
import sharp from 'sharp';

export const resizeThumbnail = function (path, format) {
  const readStream = fs.createReadStream(path);
  let transform = sharp();
  if (format) {
    transform = transform.toFormat(format);
  }
  transform = transform.resize(100);
  return readStream.pipe(transform);
};

export const resizeLowRes = function (path, format) {
  const readStream = fs.createReadStream(path);
  let transform = sharp();
  if (format) {
    transform = transform.toFormat(format);
  }
  transform = transform.resize(500);
  return readStream.pipe(transform);
};

export const resizeHighRes = function (path, format) {
  const readStream = fs.createReadStream(path);
  let transform = sharp();
  if (format) {
    transform = transform.toFormat(format);
  }
  transform = transform.resize(1080);
  return readStream.pipe(transform);
};

resizer.js
import { resizeThumbnail, resizeLowRes, resizeHighRes } from './resize';
import awsConfig from '../config/awsConfig';
import { uploadFromStream } from './amazonS3';

// receives a list of images
export const resizer = (images, id, callback) => {
  const imageList = images.split(',');
  const store = [];
  imageList.forEach((imagePath, i) => {
    sizeCreator(imagePath, id, i, (err, localstore) => {
      if (!err) {
        store.push(localstore);
        console.log(store);
      }
      callback(err);
    });
  });
};

const sizeCreator = (imagePath, id, i, callback) => {
  const localstore = {};
  resizeThumbnail(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'thumbnail', (err, data) => {
    localstore.thumbnail = {
      url: data.Location,
      filename: data.key,
    };
  }));
  resizeLowRes(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'lowres', (err, data) => {
    localstore.lowres = {
      url: data.Location,
      filename: data.key,
    };
  }));
  resizeHighRes(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'highres', (err, data) => {
    localstore.highres = {
      url: data.Location,
      filename: data.key,
    };
    callback(err, localstore);
  }));
};

amazonS3.js
import stream from 'stream';

export const uploadFromStream = (s3, id, index, res, callback) => {
  const pass = new stream.PassThrough();
  const params = {
    Bucket: 'Bucket',
    Key: `${id}_${res}_${index}`,
    Body: pass,
    ContentType: 'image/jpeg',
  };
  s3.upload(params, (err, data) => {
    callback(err, data);
  });
  return pass;
};

A: You can counting started stream and updating counter on finish stream event. When last stream is finished counter should have value 0. Then you can trigger different event which send the url.


text:
Q: JSONDecodeError: Expecting ',' delimiter: Python I am having trouble reading the json file I am supposed to get from the following code:

page=requests.get("https://ffcv.es/ncompeticiones/server.php?action=getEquipo&tmp=2019/2020&id=0202644811&cmp=1294", headers=headers)

data=page.json()

The part from the json object where I am getting the error is the following:
"googleMaps":"https://www.google.es/maps/place/Campo+Municipal+"Olimpic"+De+Onda/@39.9657111,-0.2621533,14z/data=!4m8!1m2!2m1!1scampo+de+futbol+calle+cirat+Onda!3m4!1s0x0:0xa61fd64366a15e5f!8m2!3d39.9"

The "Olimpic" seems to be the problem, I didn't create the json file, I just want to get passed this error and parse its content.

A: It's broken Json. A quick-and-dirty fix could be find problematic unescaped quotes and replace them:
import re
import json
import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}
page=requests.get("https://ffcv.es/ncompeticiones/server.php?action=getEquipo&tmp=2019/2020&id=0202644811&cmp=1294", headers=headers)

t = re.sub(r'(?<!\\)"\+', r'\\"+', re.sub(r'\+"', r'+\"', page.text))
data = json.loads(t)

# print json back to screen:
print(json.dumps(data, indent=4))

Prints:
{
    "id": "0202644811",
    "nombreEquipo": "C.D. Villa de Onda",
    "idClub": "0202644",
    "nombreClub": "Club Deportivo Villa de Onda",
    "urlFoto": "./img/logosClubes/0202644.jpg",
    "idCompeticion": "1294",
    "competicion": "1\u00aa. Regional G\u00ba. 1",
    "telefono": "627385404",
    "usaCalendarioOficial": "No",
    "diaDeseado": "Sábado",
    "horaDeseada": "17:00",
    "camiseta": "Blanco",
    "camiseta2": "",
    "tipocamiseta": "Lisa",
    "pantalon": "Negro",
    "camiseta1Hex": "#FFFFFF",
    "camiseta2Hex": "",
    "pantalonHex": "#000000",
    "mediasTexto": "Blanco",
    "mediasHex": "#FFFFFF",
    "estadioPrincipal": {
        "id": "020264401",
        "nombre": "Campo Mpal. \"Olimpic\"  F-11",
        "direccion": "s/n, Cirat, Onda, Castell\u00f3n, 12200",
        "urlFoto": "",
        "tipoLuz": "Artificial poca",
        "tipoSuperficie": "Artificial",
        "googleMaps": "https://www.google.es/maps/place/Campo+Municipal+\"Olimpic\"+De+Onda/@39.9657111,-0.2621533,14z/data=!4m8!1m2!2m1!1scampo+de+futbol+calle+cirat+Onda!3m4!1s0x0:0xa61fd64366a15e5f!8m2!3d39.9"
    },

...


text:
Q: Konva real time update a rect position I got two draggable rectangles in Konva, taken from this tutorial.
My goal is to have the red (NON draggable) rectangle in a position average of the blue draggable rectangle at all times.
I tried changing this from the tutorial code:
box1.on('mouseover', function() {
    document.body.style.cursor = 'pointer';
    center.x = (box1.x() + box2.x() ) / 2; // added
    center.y = (box1.y() + box2.y()) / 2; // added
});

Where center is the red rectangle that I would like to keep in the middle.
I think that the problem is that center.x = (box1.x() + box2.x() ) / 2; creates a new variable instead of changing the position of the rect as I would like.
I also added:
stage.on('contentMousemove', function () {
  layer.batchDraw();
});

But still, it does not work.
How can I update the x and y coordinates of the center rect in real time and see it move while I drag one of the others?
Minimal example where the problem can be seen:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Interactive center of mass simulation</title>

Drag the blue rectangles around, they have mass proportional to their area.

The red rectangle, that reresents the center of mass will move in real time

A: If you want to move the center object you need to use center.move
Here is a fully functional example

<!DOCTYPE html>


text:
Q: "Can't find variable: createStackNavigator"- React Native Well, apparently there's an error in the eighth line and I cannot figure it out: "const Stack = createStackNavigator();".
I wanna know how could I fix it or if it actually is wrong. I honestly couldn't find the error.
It's about
import 'react-native-gesture-handler';
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigation} from '@react-navigation/stack';

const Stack = createStackNavigator();

const MyStack = () => {
    return(
        <NavigationContainer>
            <Stack.Navigator>
            <Stack.Screen
                    name="Principal"
                    component={TelaPrincipal}
                    options={{title:'Bem Vindo à tela principal'}}
              ></Stack.Screen>
              <Stack.Screen
                name="Tela02"
                component={Tela02}
                options={{title:'Bem Vindo à tela 02'}}
              ></Stack.Screen>
            </Stack.Navigator>
        </NavigationContainer>
    );
};
    const TelaPrincipal = ({navigation}) => {
        return(
            <View>
                <Button
                    title = 'Ir para Tela 02'
                    onPress= {() => navigation.navigate('Tela02', {name:'Tela02'})}
                ></Button>
            </View>
        );
    };
    const Tela02 = ({navigation}) => {
        return(
            <View>
                <Button
                    title = 'Ir para Tela Principal'
                    onPress= {() => navigation.navigate('TelaPrincipal', {name:'Principal'})}
                ></Button>
            </View>
        );
    };
export default MyStack;```

  [1]: https://i.stack.imgur.com/ubReP.jpg

A: Well, I figured it out :)
I didn't import the right thingies.
It should be: "import {createStackNavigation, createStackNavigator} from '@react-navigation/stack';".
It was missing an item.


text:
Q: Realizing a neighborhood in $\mathbf{Gr}(k,n)$ as a neighborhood in $\mathbf{Gr}(1,n)$ Fix two positive integers $k,n$ with $1 < k < n$ and equip the Grassmannian $\mathbf{Gr}(k,n)$ with your favorite metric $\rho$. Now fix $\delta > 0$ and consider an open ball $B_{\delta}(x)$ about some $x\in \mathbf{Gr}(k,n)$, defined in terms of this metric.
I'd like to know when $B_{\delta}(x)$ can be interpreted/realized as an open neighborhood in the space of lines $\mathbf{Gr}(1,n)$. Concretely, if I let $\rho_1$ denote some metric defined for $\mathbf{Gr}(1,n)$, I'd like to know when I can write something like $$B_{\delta}(x) "=" B_{\delta_1}(P),$$ where the right-hand side of this "equality" is to be interpreted as the Hausdorff distance to some suitable set $P \subset \mathbf{Gr}(1,n)$ and $\delta_1>0$ specifies the ball/distance in the $\rho_1$ metric.  Generally speaking I would guess that there is a linear relationship between $\delta$ and $\delta_1$, with the constant of proportionality depending only on the choice of metrics $\rho,\,\rho_1$.
PS for my particular interests I think it would be good enough to have a characterization for the cases $\mathbf{Gr}(1,n)$ and $\mathbf{Gr}(2,n)$.


text:
Q: Proof for: the norm of the product between two vectors is equal to the product of their norms I need to prove the following
$\lVert \pmb{a}\pmb{b}^T\rVert_2 = \lVert \pmb{a}\rVert_2\cdot\lVert \pmb{b}\rVert_2$ where
$\pmb{a}$ and $\pmb{b}$ are vectors and $\pmb{a}\pmb{b}^T$ is a matrix. This is one of the properties for vector norms.
All help is really appreciated. I have a suspicion that the following equations might be helpful in the derivations, considering they were given alongside the question:
$\lVert A\rVert_2 = \sqrt{\rho(A^TA)}$ where $\rho(A)$ is the spectral radius of $A$.

A: Every where I use the $2$-norm
Observe that we can write
$$
\pmb{a}\pmb{b}^T = \lVert \pmb{a} \rVert \cdot \lVert \pmb{b} \rVert \cdot\pmb{n}_{\pmb{a}}\pmb{n}_{\pmb{b}}^T
$$
Where $\pmb{n}_{\pmb{u}} = \frac{1}{\lVert \pmb{u} \rVert} \pmb{u}$ is the normalization of $\pmb{u}$. Now we have
\begin{align*}
(\pmb{n}_{\pmb{a}}\pmb{n}_{\pmb{b}}^T)^T (\pmb{n}_{\pmb{a}}\pmb{n}_{\pmb{b}}^T)&= \pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{a}}^T \pmb{n}_{\pmb{a}}\pmb{n}_{\pmb{b}}^T\\
&=\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T
\end{align*}
So that
\begin{align*}
\lVert \pmb{a}\pmb{b}^T\rVert &= \lVert \pmb{a} \rVert \cdot \lVert \pmb{b} \rVert \cdot \sqrt{\rho(\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T)}
\end{align*}
so we need to find the largest eigenvalue of $\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T$ but observe that it is a projection matrix :
$$(\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T)^2=\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T \pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T = \pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T$$
if we write $\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T = D\Sigma D^T$ the eigen decomposition, then we have $D\Sigma D^T = D\Sigma D^T D \Sigma D^T = D\Sigma^2 D^T$ which means by uniqueness of the eigen decomposition that $\Sigma^2=\Sigma$. Since it is a diagonal matrix we have that every eigen values satisfies $\sigma^2=\sigma$ so that they take value in $\lbrace 0 , 1 \rbrace$.
Now it only remains to show that there is a eigen value that is $1$. But $\pmb{n}_{\pmb{b}}$ is an eigenvector associated to eigenvalue $1$, indeed
$$(\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T)\pmb{n}_{\pmb{b}} = \pmb{n}_{\pmb{b}}$$
and so $\rho(\pmb{n}_{\pmb{b}}\pmb{n}_{\pmb{b}}^T) = 1$ which in turn means that
$$\lVert \pmb{a}\pmb{b}^T\rVert = \lVert \pmb{a} \rVert \cdot \lVert \pmb{b} \rVert $$


text:
Q: Finding roots of an equation using Bisection Am trying to find the roots of the equation (x^3)-(x^2)+2 using bisection method. For this, I took two values from the user to act as the initial guesses( called limits here) and then converge onto the value where the function goes to 0. But whenever I change the limits, the value also differ by large amounts and none of them are close to the actual value. Any suggestions where I might be wrong?
Here's the code:
#include<stdio.h>
#include<cstdlib>
# define Epsilon 0.0001
float f(float x)
{
    return x*x*x-x*x+2;
}
float bisection(float a, float b)
{
    if(f(a)*f(b)>0)
    {
        printf("No root within this interval.");
    }
    float c=a;
    while(abs(b-a)>Epsilon)
    {
        c=(a+b)/2;
        if(f(a)*f(c)<0)
        {
            b=c;
        }
        else if(f(b)*f(c)<0)
        {
            a=c;
        }
        else if(f(c)==0)
        {
            printf("The root of x^3-x^2+2 is %f",c);
            break;
        }
    }
    printf("The root of x^3-x^2+2 is %f",c);
}
int main(void)
{
    float u,l;
    printf("Enter upper limit:\n");
    scanf("%f",&u);
    printf("Enter lower limit:\n");
    scanf(" %f",&l);
    bisection(l,u);
}

Thanks for the help in advance!

A: *

*You need #include <cmath>

*You need to replace abs (integer absolute value) with fabs (floating point absolute value)

*You need to check against Epsilon :  if (f(c) <= Epsilon) instead of if (f(c) == 0) which is unlikely to happen.

But anyway you still need to check if there is a solution. If there is no solution in the guess interval, the loop in the function never stops. This left as an exercise.

A: You have an infinite loop in your bisection function.
if (f(a)*f(b)>0) you determine that there is no root to be found within your interval; then you proceed to try to find it.  You fail to find a subinterval where a root exists, so you don't change anything and try again.


text:
Q: WooCommerce product shortcode not working in functions.php I am working on wordpress shortcode. In the functions.php, I have added following code
add_shortcode('post-footer-note', 'getPostFooterNote');
function getPostFooterNote() {
    return "
Hope you find this tutorial useful! Share this link on Social Media.
";
}

and in the post page, I added [post-footer-note] The code works fine. Instead of "Hope you find this tutorial useful" text I want to display WooCommerce products. To show the products on the page, I made few changes in the code
add_shortcode('post-footer-note', 'getPostFooterNote');
function getPostFooterNote() {
    return "
[products limit="8" columns="4" category="hoodies, tshirts" cat_operator="NOT IN"]
";
}

After making changes, following error is showing.
Your PHP code changes were rolled back due to an error on line 461 of file C:\xampp\htdocs\wordpress\wp-content\themes\twentynineteen\functions.php. Please fix and try saving again.

syntax error, unexpected integer "8", expecting ";"

A: You have a syntax error in:
function getPostFooterNote() {
    return "
[products limit="8" columns="4" category="hoodies, tshirts"
cat_operator="NOT IN"]
";
}

You need to use different quotations like this:
function getPostFooterNote() {
    return do_shortcode("
[products limit='8' columns='4' category='hoodies,  tshirts' cat_operator='NOT IN']
");
}

You could also flip the quotes (it doesn't matter which is the outer quotation marks (double or single).
As per the error, the second double quote is just before the 8, and therefore the return is concluded, and a semicolon is expected. Instead 8 is next, and the compiler doesn't know how to parse your code.
Edit: added @Moshe Gross' edit to final solution.


text:
Q: SharpDX + ColorMatrix Ковыряюсь в SharpDX. Хочу добавить эффект ColorMatrix. Пишу нижеприведенный код, но на строчке colorEffect.Matrix = Matrix5x4.Identity; программа падает с эксепшеном "The parameter is incorrect". С чем это связано? Матрицы не работают никакие, даже единичная, как в моем примере.
private SharpDX.Direct2D1.Effect CreateEffectGraph(SharpDX.WIC.FormatConverter formatConverter, Vector2 scale, float blurDeviation)
        {
            var d2dDevice = _deviceManager.DeviceDirect2D;
            var d2dContext = _deviceManager.ContextDirect2D;

            SharpDX.Direct2D1.Effects.BitmapSourceEffect bitmapSourceEffect = new SharpDX.Direct2D1.Effects.BitmapSourceEffect(d2dContext);

            bitmapSourceEffect.ScaleSource = scale;
            bitmapSourceEffect.Orientation = Orients[this.Rotation];
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            SharpDX.Direct2D1.Effects.ColorMatrix colorEffect = new SharpDX.Direct2D1.Effects.ColorMatrix(d2dContext);
            colorEffect.SetInput(0, bitmapSourceEffect.Output, true);

            colorEffect.Matrix = Matrix5x4.Identity;

            return colorEffect;

        }


text:
Q: Navigate between headings with swipe while using talkback Android 9 has introduced accessibilityHeading tag, which can be used by talkback to announce the Headings.
https://developer.android.com/about/versions/pie/android-9.0#a11y
Look for Heading-based navigation
In my app I have multiple Textviews in my activity with some Headings
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:accessibilityHeading="true"
            android:text="Accessibility Heading 1"
            android:textColor="#000000"
            android:textSize="18sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="Message"
            android:textColor="#000000" />

But when I run the app, headings are treated as normal textviews only and no special treatment is given by Talkback.
I can swipe left to navigate through all elements.
There is option to swipe up to change mode for talkback announcements. e.g Default, Links, Controls, Headings etc.
When chosen Headings, I expect talkback to announce only headings and to jump from one heading to another but it stays at the same place even after Swipe Left or Swipe Right gesture.

A: Set both accessibilityHeading and focusableInTouchMode to true. Then, after setting the navigation mode to Headers (you can do this via the up down gesture), swiping up or down navigates you though the headers. Swiping right and left will still allow you to navigate through single items.

A: I just tried, it work here as expected.
Talkback properly announces textviews as headings and in heading mode I can navigate to them as well.
Please ensure that you are using the latest version of Talkback.
This is quite an old question so may be you may have got the solution since then

A: I was having the same issue.
In my particular situation it was fixed when I set focusable and focusableInTouchMode to false in the parent view, and true in the TextView.


text:
Q: Removing write protection on a usb drive I have an usb flash-drive that is write protected since a system crash. In the dmesg, the device write protection is first off, then it is turned on.
Here is the dmesg:
sd 2:0:0:0: [sdb] 60566016 512-byte logical blocks: (31.0 GB/28.9 GiB)
sd 2:0:0:0: [sdb] Write Protect is off
sd 2:0:0:0: [sdb] Mode Sense: 2b 00 00 08
sd 2:0:0:0: [sdb] Write cache: disabled, read cache: enabled, doesn't support DPO or FUA
 sdb: sdb1 sdb2 sdb3 sdb4
sd 2:0:0:0: [sdb] Write Protect is on
sd 2:0:0:0: [sdb] Mode Sense: 2b 00 80 08
sd 2:0:0:0: [sdb] Attached SCSI removable disk
EXT4-fs (sdb3): INFO: recovery required on readonly filesystem
EXT4-fs (sdb3): write access unavailable, cannot proceed (try mounting with noload)
/dev/sdb4: Can't open blockdev

Here is the result of the command hdparm /dev/sdb:
/dev/sdb:
 multcount     =  0 (off)
 readonly      =  0 (off)
 readahead     = 256 (on)
 geometry      = 29573/64/32, sectors = 60566016, start = 0

I also ran badblocks on /deb/sdb, and it found no bad blocks.
I tryed the command hdparm -r0 /dev/sdb with no success. No more success with hdparm security commands like:
hdparm --security-mode m --user-master m --security-unlock p /dev/sdb

This command says:
SG_IO: bad/missing sense data, sb[]:  70 00 05 00 00 00 00 0a 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

hdparm -I /dev/sdb gives the following result:
/dev/sdb:

ATA device, with non-removable media
Standards:
    Likely used: 1
Configuration:
    Logical     max current
    cylinders   0   0
    heads       0   0
    sectors/track   0   0
    --
    Logical/Physical Sector size:           512 bytes
    device size with M = 1024*1024:           0 MBytes
    device size with M = 1000*1000:           0 MBytes
    cache/buffer size  = unknown
Capabilities:
    IORDY not likely
    Cannot perform double-word IO
    R/W multiple sector transfer: not supported
    DMA: not supported
    PIO: pio0

Is there a way to turn off write protection, or my usb flash-drive is definitely lost ?

A: Most likely USB has a hardware failure, it happens quite often especially with cheap USB drives.
There is an extensive answer for your question:
https://askubuntu.com/a/1028453/1177212


text:
Q: Check if File exists before running a query I am a newbie so forgive my ignorance;
I have an upload PDF form that I check if the form already exists, if it doesnt, I upload it and would therefore like to run a mysql insert query. I tried this:
if (file_exists($pdfSubDirectory.$filename))
    if (isset($_POST['submit']))
    {
      $quer->execute();
    }

but I get the error;
> Fatal error: Call to a member function execute() on a non-object
any ideas?
my main code is;
    <?php
require "config.php";

$cat        = $_GET['cat1'];
$catid      = $_GET['cat'];
$subcat     = $_GET['subcat'];
$subcatid   = $_GET['subcatid'];
$subcat2    = $_GET['subcat2'];

//form vars
$form_class = $_POST['Class']; // create modify delete flag
$form_cerfa = $_POST['Cerfa']; // cerfa Yes or No flag
$form_id = $_POST['ID'];
$form_name = $_POST['Name'];

$predir = "./docs";
$dir = $predir."/" .$cat. "/" .$subcat."/" .$subcat2 . "/";
$dir= strtolower($dir);
$dir= str_replace(' ', '_', $dir);

$MyHtml1 = <<<EOD

<!doctype html>

    <title>$subcat / $subcat2</title>

                                    You are in the category:
                                    $cat

                                    You are in the subcategory:
                                    $subcat

                                    You are in section:
                                    $subcat2

Time:

Date:

...

EOD;

echo $MyHtml1;
$pdfDirectory = $dir;
$pdfSubDirectory = $pdfDirectory.$_POST['Class']."/";
$thumbDirectory = $pdfDirectory . "pdfimage/";
$filename = basename( $_FILES['pdf']['name'], ".pdf");
$filename = preg_replace("/[^A-Za-z0-9_-]/", "", $filename).".pdf";
$thumb = basename($filename, ".pdf");

if (file_exists($pdfSubDirectory.$filename)) {
    echo "This file already exists.";
} else {
    if(move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfSubDirectory.$filename)) {

    //the path to the PDF file
    $pdfWithPath = $pdfDirectory.$filename;
    $pdfWithSubPath = $pdfSubDirectory.$filename;
    $pdfWithPathImage = $pdfDirectory."pdfimage/";
    $pdfWithPathImageThumb = $pdfWithPathImage.$thumb.".jpg";
    //add the desired extension to the thumbnail
    $thumb = $thumb.".jpg";

    //execute imageMagick's 'convert', setting the color space to RGB and size to 200px wide
    //exec("convert \"{$pdfWithSubPath}[0]\" -colorspace RGB -geometry 100 $thumbDirectory$thumb");
    exec("convert  -density 200 -page 792x612 \"{$pdfWithSubPath}[0]\" -append -resize 240 -background white -flatten +repage $thumbDirectory$thumb");
    //show the image
    echo "

";
    echo $pdfWithPathImageThumb;
        }
}
if (isset(file_exists($pdfSubDirectory.$filename)))
    {
      $quer->execute();
    }

///////// start of query for form addition//////////
$quer = $dbo -> prepare("INSERT into form_detail(form_id,form_name,form_category,form_subcategory,form_subcategory2,form_class,form_cerfa) VALUES(:form_id,:form_name,:form_category,:form_subcategory,:form_subcategory2,:form_class,:form_cerfa)");
$quer ->bindParam(':form_id', $form_id);
$quer ->bindParam(':form_name', $form_name);
$quer ->bindParam(':form_category', $catid);
$quer ->bindParam(':form_subcategory', $subcatid);
$quer ->bindParam(':form_subcategory2', $subcat2);
$quer ->bindParam(':form_class', $form_class);
$quer ->bindParam(':form_cerfa', $form_cerfa);

///////////// End of query for form addition////////////

$MyHtml2 = <<<EOD

<form action="" method="post" enctype="multipart/form-data" name="MyForm">
        <input type="file" name="pdf" />

            Cerfa :
            <input type="radio" name="Cerfa" value="1" checked="checked"/>Yes<input type="radio" name="Cerfa" value="0"/>No

            Form Class:
            <select name="Class">
            <option value="create">Create</option>
            <option value="modify">Modify</option>
            <option value="delete">Delete</option>
        </select>

             Form Name:
            <input type="text" name="Name" value="Name"/>

            Form Reference No :
            <input type="text" name="ID" value="Reference Number"/>

            Check details and upload
            <input type="submit" name="submit" value="Upload"/>

</form>

Forms Available

            Ref
            Cerfa
            Name

EOD;

echo $MyHtml2;

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir."create/"));

while($it->valid()) {

    if (!$it->isDot()) {

        echo 'File Name: ' . $it->getSubPathName() . "\n
";
    }

    $it->next();
}
?>

A: You need to prepare $quer before executing it. Put this code...
///////// start of query for form addition//////////
$quer = $dbo -> prepare("INSERT into form_detail(form_id,form_name,form_category,form_subcategory,form_subcategory2,form_class,form_cerfa) VALUES(:form_id,:form_name,:form_category,:form_subcategory,:form_subcategory2,:form_class,:form_cerfa)");
$quer ->bindParam(':form_id', $form_id);
$quer ->bindParam(':form_name', $form_name);
$quer ->bindParam(':form_category', $catid);
$quer ->bindParam(':form_subcategory', $subcatid);
$quer ->bindParam(':form_subcategory2', $subcat2);
$quer ->bindParam(':form_class', $form_class);
$quer ->bindParam(':form_cerfa', $form_cerfa);
///////////// End of query for form addition////////////

Above this:
if (file_exists($pdfSubDirectory.$filename))
    if (isset($_POST['submit']))
    {
      $quer->execute();
    }

When the script is ran, it gets to the if (file_exists($pdfSubDirectory.$filename)), finds it true, and tries to execute a query that doesn't exist.


text:
Q: Pictures not visible in Windows 8 Picture App I changed the default system folder C:\Users\myuser\Pictures to another folder on an externat SD-card D:\Eigene Bilder`. After doing that there where no pictures in my Windows-8 Picture-App anymore.
even after changing back the default folder, there are still no pics in my Library in the App.
How can I tell the App that the pictures are back?

A: The problem was not solved even after a system restart. But after just waiting some minutes and maybe because I connected the device to the internet, all of a sudden the pictures were found in the library again.
Maybe it just took some minutes until the system scanned the library again.