text:
Q: Netbeans 10.0 doesn't start in Windows 10 OS I've just downloaded Netbeans 10.0 and on a Windows 10 64 bit it doesn't start when i execute netbeans64.exe (not even with netbeans.exe)
I removed all the java installations and installed jdk-11.0.2+9 and jdk-11.0.2+9-jre.
Also change the path in the netbeans configuration file to the right java path.
Configured the environment variables PATH and JAVA_HOME.
When run the app nothing happens.
Somebody else with same issue?

A: I suspect that at the time you installed NetBeans you either had no valid Java installation, or you have changed your Java installation(s) since you installed NetBeans 10.0. In that scenario NetBeans may be unable to start.
To eliminate this as a possibility, explicitly specify the version of Java to be used when  starting NetBeans:

*

*Locate the file netbeans.conf. It resides in the etc directory within your NetBeans installation directory.

*It is a simple properties file containing name value pairs, with commented lines starting with a # character. Open the file in any text editor.

*Locate the line containing the text netbeans_jdkhome=. If that line starts with a # character then delete that character to uncomment the line.

*Set the value of that property to the path of the JDK that you want NetBeans to use. For example, on my Windows 10 machine the line looks like this:
netbeans_jdkhome="C:\Java\openJDK\jdk-11.0.2"

*Try restarting NetBeans once you have saved your change to netbeans.conf.

*If that doesn't work then locate the NetBeans log file, and update your question with the changes logged to it when you attempt to start NetBeans. That log is named messages.log, and is a simple text file. It will reside in a directory named var under your user directory. In my case, on Windows 10, its path is C:\Users\johndoe\AppData\Roaming\NetBeans\10.0\var\log, though obviously it will be different for you.

A: Solved...
after trying many (MANY) possible solutions the one that worked was renaming the netbeans folder to "Netbeans10" without any "strange" chars.

A: https://www.youtube.com/watch?v=vt7_6HwCFOU saw this guy and helped me out solved my problem! and it works :)). He put the file on the C drive not inside the (89x)/ programs files. like literally inside the C drive this is how it looks in my folder:
C:\netbeans
Hope it helps.


text:
Q: Can a master table have a relation to another master table? I want to ask about my project that I am working on.
I have two tables, ms_corporates and ms_subsidiaries, and the term is one corporate can have many subsidiaries but one subsidiary can have only one corporate.
This is my table right now:
ms_corporates
-------------
corporate_id PK
corporate_name
corporate_address
corporate_phone

ms_subsidiaries
---------------
subsidiary_id PK
corporate_name FK
subsidiary_name
subsidiary_address
subsidiary_phone

Can I go make a relation between them  or do I have to make a table between them?

A: Smells like a 1:many relationship.  Such is implemented by having corporate_id (not name) in the subsidiary table.  And index that column.
Then you can JOIN the tables to find information about the corporation that owns a subsidiary or find all the subsidiaries of a given corporation.
There is something else to consider.  A "corporation" and a "subsidiary" are really the same type of entity, aren't they?  Even your schema indicates that; see how the columns are virtually the same?  So...  You probably should have only one table, and put both in it.  It will have an id (a la corporate_id and subsidiary_id) and a parent_id.
parent_id is a link to the id of another row in the same table.  It is the link from the subsidiary to the corporation.  If it is 0, then you are looking at a corporation.  Non-0 means a subsidiary.
Search this forum for parent_id; you will probably find lots of other examples doing the same thing.

A: This is a candidate for a recursive relationship. You don't need two tables in this case as both tables essentially have the same columns. You simply need to create a "parent_corporate_id" with a foreign key defined as ms_corporates.corporate_id => ms_corporates.parent_corporate_id. This is self-referential to the same table. By definition, if there is a value in "parent_corporate_id", it is a subsidiary.This only holds true if a subsidiary can NEVER have more than one parent. All you need to do to make it work is remove the "corporate_" to something more generic. And your current FK won't work because "corporate_name" is not the primary key in ms_corporates. You can't create a FK on any column, it must be the primary from the "contributing" table, in this case ms_corporates.corporate_id.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are GameSalad and other visual programming "languages" on topic here? Are tools like Scratch, Alice, and GameSalad considered on topic? I see in a lot of questions users saying in the comments that the question is too simple for the site, since it is for "experts", and these tools seem to be for beginners to programming.

A: Yes, visual programming languages are on-topic on Stack Overflow.  Individual questions may be too simple if their answers can be found in any introductory tutorial, but we don't classify whole programming languages as off-topic just because they're aimed at beginner programmers.  If you have a question that you can't find the answer to in a tutorial or book for your language, go ahead and ask it.


text:
Q: Как выранить отображение таблицы rtf файла в RichTextBox? Есть RTF файл, который содержит таблицу. Содержимое файла необходимо отобразить в RichTextBox.
Сложность в следующем: если таблица содержит чейки по одной строке, то всё корректно отображается. НО если табличка будет содержать по несколько строк, то RichTextBox будет думать, что это просто одна длинная строка и не будет правильно отображать содержимое, коверкая весь документ.
я слышал, что RTF содержит в себе теги. так вот если праавильно их отобазить, то можно по идее исправить ситуацию.
Что из себя представляют эти теги? И как исправить корректность отображения таблицы?


text:
Q: How to check if the element in on screen on webpage and I also want a trigger when someone scrolls to that I want to check if the element is on the screen. It MUST NOT involve any kind of scrolling. I just want to check if the element is on the screen. I have tried different codes out there. They work perfectly fine on Desktops but not on mobile phones.
This is my current code:
var wScroll = $(this).scrollTop();

if(wScroll > $('.services').offset().top - ($(window).height() / 1.2)) {

    $('.jstransitiononservices').each(function(i){

      setTimeout(function(){
      $('.jstransitiononservices').eq(i).addClass('is-showing');
      }, 150 * (i+1));

    });

}

A: You can use Element.getBoundingClientRect() method on window scroll and you can look for top property of the returned object:

$(document).ready(function() {
  var target = $('.services')[0].getBoundingClientRect();
  console.log(target, $(window).scrollTop());
  if (target.top <= $(window).scrollTop()) {
    $('pre').html('Element is in view.');
  }
});
body {
  margin: 0;
  padding: 0;

}

services div

This one with scroll:

$(window).scroll(function() {
  var target = $('.services')[0].getBoundingClientRect();
  console.log(target, window.innerHeight);
  if (target.top <= $(window).scrollTop() && target.bottom <= window.innerHeight) {
    $('pre').html('Element is in view.');
  }
}).scroll(); // <----this triggers scroll on page load.
body {
  margin: 0;
  padding: 0;
  height:800px;
}
.services{margin:500px 0 0 0; border:solid 1px red;}
pre{position:fixed; left:0; top:0; width:100%;}

services div


text:
Q: How do I host a Windows Terminal (to run Windows applications and be accessed by users via a standard MS Remote Desktop client) on a Linux server? How do I host a Windows Terminal (to run Windows applications and be accessed by users via a standard MS Remote Desktop client) on a Linux server? I've heard there are some alternatives to Microsoft server software for this purpose.

A: LTSP is the Linux Terminal Server Project
RDP can only be used with windows servers hosting the terminal session, so you could bring up a windows VM on top of Linux, if RDP is really essential for you.
Otherwise, there are options, like VNC, X-forwarding, SPICE, NX etc.

A: The only alternative to Windows Terminal Services, assuming you actually want to run Windows applications, is Citrix. Remote screen software, such as VNC, etc., are no substitute for Terminal Services, which provides a separate environment for each user session.


text:
Q: structuring of models in ruby on rails app In my rails app I have the following models: users, games and players. A user has many games and a game has many players. So far it is really quite simple but the problem is that in one game the maximum amount of players is 8 and there is a possibility of joining a game after the maximum number of players has been reached but then you are a reserve.
So the question is: Should I have an extra reserve model? And how should all the models be associated with each other?
At the moment I have solved it by adding a reserve attribute to the player model and when the maximum amount is reached the reserve attribute is turned to 1 instead of 0. This solution feels a little clumsy and needs a lot of code. I was wondering if anyone has done something similar and had a better solution.

A: You can add a method to Game model.
has_many :players

def is_reserved
 self.players.count >= 8 ? true : false
end

Then place a condition where you are adding the players to game. I am assuming that you have the @game object.
unless @game.is_reserved
  // add players
else
 // show the warning messaage or do nothing
end

Hope it will work for you.


text:
Q: PHP update database mysqli form I am currently trying to write a system where I can add editable fields from the database onto a webpage then submit the information and change the data that's in the database.
I have got the data to be shown in the text fields but I cannot seem to get the update function to work...
<?php $mysqli = new mysqli('localhost', 'adwawdaw', 'awdawdaw', 'awdawdaw');
     $result = $mysqli->query('SELECT * FROM information WHERE id = 1');
        if (is_object($result)) {
            if ($result->num_rows) {
                while ($row = $result->fetch_assoc()) {
                    $banner = $row['banner'];
                    $embed = $row['embed'];
                    $title = $row['title'];
                    $date = $row['date'];
                    $time = $row['time'];
                    $description = $row['description'];
                    $region = $row['region'];
                    $sponsors = $row['sponsors'];
                }
            }
        }
    ?>

<form method="post" action="edit1.php">

Banner:
<input type="text" name="banner" value="<?php echo htmlspecialchars($banner) ?>">

Embed:
<input type="text" name="embed" value="<?php echo htmlspecialchars($embed) ?>">

Event Title:
<input type="text" name="title" value="<?php echo htmlspecialchars($title) ?>">

Date:
<input type="text" name="date" value="<?php echo htmlspecialchars($date) ?>">

Time:
<input type="text" name="time" value="<?php echo htmlspecialchars($time) ?>">

Description:
<input type="text" name="description" value="<?php echo htmlspecialchars($description) ?>">

Region:
<input type="text" name="region" value="<?php echo htmlspecialchars($region) ?>">

Sponsors:
<input type="text" name="sponsors" value="<?php echo htmlspecialchars($sponsors) ?>">

<input class="button" type="submit" value="Update!">
</form>
<?php
$banner = $_POST['banner'];
$embed = $row['embed'];
$title = $_POST['title'];
$date = $row['date'];
$time = $row['time'];
$description = $row['description'];
$region = $row['region'];
$sponsors = $row['sponsors'];

$mysqli->query('UPDATE livestreamadmin SET title = $title WHERE id=1');
    ?>


text:
Q: Directly input accents in TexStudio? Is it possible to input directly accents in TeXstudio, instead of the hard-to-read form \'a for á? What do I have to do to get this working?
In TexWorks, I can input the accented character directly in the editor and it will render correctly in the compiled pdf.

A: Yes, you can insert accents directly by keyboard in TeXstudio.
Note that, since TeXstudio is an editor which support a lot of font encoding you can type normally. No problem will appear until you compile your tex file.
During the compilation process those accented characters should be interpreted by the compiler. This could be done in general loading some specific packages.
If your tex file is UTF, load the package
\usepackage[utf8]{inputenc}

If your tex file is ISO load
\usepackage[latin1]{inputenc}

You can discover if it is UTF or ISO in the TeXstudio status bar.
Also, load
\usepackage[T1]{fontenc}

and probably you will have no problems.
\'a \'e \'i \'o \'u

á é í ó ú


text:
Q: как получить сертификат из из хранилища ОС Получил задание:
"Получить и проверить цифровую подпись файла, в качестве пары ключей использовать само подписанный сертификат X509 который будет располагаться в хранилище сертификатов операционной системы для доступа к хранилищу использовать X509Store." Нашел как брать сертификат из файла
try
{
X509Certificate theSigner = X509Certificate.CreateFromSignedFile ("c:\\r\\1.dll");
Console.Write("certificate info :"+ theSigner.GetCertHashString());
}
catch (Exception ex)
{
Console.WriteLine("No digital signature ");
}

а как это сделать из хранилища не знаю. Подскажите, как это сделать.

A: Для получения доступа к хранилищу вы можете использовать следующий код:
using System.Security.Cryptography.X509Certificates;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            //Выбираем и открываем хранилище с сертификатами
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            //Проходим по всем сертификатам и что то с ними делаем
            foreach (X509Certificate2 cert in store.Certificates)
            {
                //В данном участке кода будут все сертификаты из указанного хранилища
            }

            //Закрываем хранилище
            store.Close();
        }
    }
}

UPD
В связи с вполне логичным комментарием товарища @VladD дополняю кодом с использованием using. Это необходимо для обеспечения закрытия хранилища даже в случае ошибки в блоке обработки сертификатов (И банально это более лаконично).
static void Main(string[] args)
{
    //Выбираем и открываем хранилище с сертификатами
    using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
        store.Open(OpenFlags.ReadOnly);

        //Проходим по всем сертификатам и что то с ними делаем
        foreach (X509Certificate2 cert in store.Certificates)
        {
            //В данном участке кода будут все сертификаты из указанног охранилища
        }
    }
}

P.S. Если вам требуется реализовать подпись по ГОСТу, то вы можете воспользоваться библиотекой GostCryptography


text:
Q: why tooltip appears wrong in my chart JS? I have a chart that I have developed using Chart JS and it works good. The problem here is that when I hover on a point, the x axes of that point appears wrong! So for example in the image below, I am hovering on that orange point which have '23000' x axes point. but it appears '18428.91'! it has right values only with the first purple line on the bottom. I think the problem with the tooltip option but I do understand what's the problem

html

                                        <canvas id="lineChart_1"></canvas>

JS

After Editing:

A: Line charts default to a linear Y axis and a category X axis. Specifying data.labels explicitly sets labels for the x-axis category ticks but these are just text, and won't match the computed scale.
As x and y values are passed both axes need to be linear:

*

*Remove the data.labels array.

*Add the following to options:
scales: {
  x: {
    type: 'linear'
  }
}

Working example:

(function($) {
  /* "use strict" */

  /* function draw() {

  } */

  var dzSparkLine = function() {
    //let draw = Chart.controllers.line.__super__.draw; //draw shadow

    var screenWidth = $(window).width();

    var lineChart1 = function() {

      if (jQuery('#lineChart_1').length > 0) {

        //basic line chart
        const lineChart_1 = document.getElementById("lineChart_1").getContext('2d');

        lineChart_1.height = 100;

        new Chart(lineChart_1, {
          type: 'line',
          data: {
            defaultFontFamily: 'Poppins',
            /*labels: [10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 18428.91, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 25357.89, 26000, 27000, 28000, 28264.22, 29000, 29555.19],*/
            datasets: [{
              label: '5390',
              data: [{
                  x: 10000,
                  y: 58.81
                },

                {
                  x: 11000,
                  y: 57.34
                },

                {
                  x: 12000,
                  y: 55.99
                },

                {
                  x: 13000,
                  y: 54.21
                },

                {
                  x: 14000,
                  y: 52.09
                },

                {
                  x: 15000,
                  y: 49.32
                },

                {
                  x: 16000,
                  y: 45.53
                },

                {
                  x: 17000,
                  y: 41.87
                },

                {
                  x: 18000,
                  y: 36.87
                },

                {
                  x: 18428.91,
                  y: 34.15
                },

              ],

              borderColor: '#FF00FF',
              borderWidth: "2",
              backgroundColor: 'transparent',
              pointBackgroundColor: '#FF00FF'
            }, {
              label: '6160',
              data: [{
                  x: 12000,
                  y: 76.66
                },

                {
                  x: 13000,
                  y: 75.7
                },

                {
                  x: 14000,
                  y: 74.15
                },

                {
                  x: 15000,
                  y: 72.38
                },

                {
                  x: 16000,
                  y: 70.14
                },

                {
                  x: 17000,
                  y: 68.08
                },

                {
                  x: 18000,
                  y: 64.76
                },

                {
                  x: 19000,
                  y: 60.64
                },

                {
                  x: 20000,
                  y: 55.75
                },

                {
                  x: 21000,
                  y: 49.57
                },

                {
                  x: 22000,
                  y: 42.18
                },

              ],

              borderColor: '#4472C4',
              borderWidth: "2",
              backgroundColor: 'transparent',
              pointBackgroundColor: '#4472C4'
            }, {
              label: '6930',
              data: [{
                  x: 14000,
                  y: 97.17
                },

                {
                  x: 15000,
                  y: 96.06
                },

                {
                  x: 16000,
                  y: 94.58
                },

                {
                  x: 17000,
                  y: 93.3
                },

                {
                  x: 18000,
                  y: 91.41
                },

                {
                  x: 19000,
                  y: 89.35
                },

                {
                  x: 20000,
                  y: 86.44
                },

                {
                  x: 21000,
                  y: 82.95
                },

                {
                  x: 22000,
                  y: 79.01
                },

                {
                  x: 23000,
                  y: 73.08
                },

                {
                  x: 24000,
                  y: 65.36
                },

                {
                  x: 25000,
                  y: 55.55
                },

                {
                  x: 25357.89,
                  y: 50.67
                },

              ],

              borderColor: '#ED7D31',
              borderWidth: "2",
              backgroundColor: 'transparent',
              pointBackgroundColor: '#ED7D31'
            }, {
              label: '7700',
              data: [{
                  x: 16000,
                  y: 119.81
                },

                {
                  x: 17000,
                  y: 119.22
                },

                {
                  x: 18000,
                  y: 117.988
                },

                {
                  x: 19000,
                  y: 116.55
                },

                {
                  x: 20000,
                  y: 115.05
                },

                {
                  x: 21000,
                  y: 113.003
                },

                {
                  x: 22000,
                  y: 110.186
                },

                {
                  x: 23000,
                  y: 108.44
                },

                {
                  x: 24000,
                  y: 104.15
                },

                {
                  x: 25000,
                  y: 99.4
                },

                {
                  x: 26000,
                  y: 93.33
                },

                {
                  x: 27000,
                  y: 84.8
                },

                {
                  x: 28000,
                  y: 68.7
                },

                {
                  x: 28264.22,
                  y: 60.7
                },

              ],

              borderColor: '#A5A5A5',
              borderWidth: "2",
              backgroundColor: 'transparent',
              pointBackgroundColor: '#A5A5A5'
            }, {
              label: '8085',
              data: [{
                  x: 19000,
                  y: 130.56
                },

                {
                  x: 20000,
                  y: 129.3
                },

                {
                  x: 21000,
                  y: 127.6
                },

                {
                  x: 22000,
                  y: 126.08
                },

                {
                  x: 23000,
                  y: 123.7
                },

                {
                  x: 24000,
                  y: 121.088
                },

                {
                  x: 25000,
                  y: 117.9
                },

                {
                  x: 26000,
                  y: 113.6
                },

                {
                  x: 27000,
                  y: 108.2
                },

                {
                  x: 28000,
                  y: 99.17
                },

                {
                  x: 29000,
                  y: 84.9
                },

                {
                  x: 29555.19,
                  y: 66.15
                },

              ],

              borderColor: '#0070C0',
              borderWidth: "2",
              backgroundColor: 'transparent',
              pointBackgroundColor: '#0070C0'
            }, {
              label: 'Efficiency',
              data: [

                {
                  x: 17000,
                  y: 100
                }
              ],
              borderColor: 'black'
            }],
          },
          options: {
            interaction: {
              //mode: 'y'
            },
            scales: {
              x: {
                type: 'linear'
              }
            }
          }
        });

      }
    }

    /* Function ============ */
    return {
      init: function() {},

      load: function() {

        lineChart1();

      },

      resize: function() {

        lineChart1();

      }
    }

  }();

  jQuery(document).ready(function() {});

  jQuery(window).on('load', function() {
    dzSparkLine.load();
  });

  jQuery(window).on('resize', function() {
    dzSparkLine.resize();

  });

})(jQuery);

  <canvas id="lineChart_1"></canvas>


text:
Q: react native link break while loop in shell script There is a file like below
react-native-webrtc
react-native-randombytes
react-native-fs
react-native-callkeep

There is a shell script with two loop like below
while read line
do
    echo ${line}
done < './links.patch'

while read line
do
    react-native link ${line}
done < './links.patch'

First loop print each line working correctly, but second loop only link first one react-native-webrtc library then end loop. Anyone have any idea?


text:
Q: UITableView issue, it scrolls halfway up after updating or inserting a new cell My TableView is doing some kind of auto-scrolling after any kind of updates are applied to it. If I were to append a new element to the array that contains the items which are presented in the UITableView, for some reason my Table View scrolls up somewhat randomly up around 50% up the middle of the contents of the TableView.
Here's the function that deals with updating, not inserting an item into the Table View:
func updateLastMessage() {

    var section = msgSections.count - 1
    var row = msgSections[section].msg.count - 1
    let indexPath = NSIndexPath(forRow: row, inSection: section)

    self.tableView.beginUpdates()
    self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    self.tableView.endUpdates()
}

This function above works perfectly, but after I call reloadRowsAtIndexPaths on self.tableView, the table view automatically scrolls up 50% of the contents of the Table View. I get exactly the same result if I were to insert an item instead:
    self.tableView.beginUpdates()
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    self.tableView.endUpdates()

Also, if I were to comment out both beginUpdates() and endUpdates(), there seems to be no effect to the scrolling.
I only know of one hack to somewhat get around this issue by using setContentOffset to return the scroll position back to where it was before a message was updated, or a new message is inserted:
func updateLastMessage() {
    let currentContentOffset = self.tableView.contentOffset

    var section = msgSections.count - 1
    var row = msgSections[section].msg.count - 1
    let indexPath = NSIndexPath(forRow: row, inSection: section)

    self.tableView.beginUpdates()
    self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    self.tableView.endUpdates()

    self.tableView.setContentOffset(currentContentOffset, animated: false)
}

This hack doesn't work in my favor, because it scrolls slowly to the top and then jolts back to where it was which looks kind of bad.
Does anyone know exactly what could be the mechanism that's causing the TableView to scroll up so much after any appended item or updated item??
It seems to work perfectly and the animation looks very nice as but only when there aren't any items in the table view.

A: Never call reloadRowsAtIndexPaths: withRowAnimation: inside beginUpdates() and endUpdates().
The tableView will automatically call the necessary reloading of rows at the end of endUpdates().
Just call beginUpdates() and endUpdates() without any code inside. It'll work.


text:
Q: SQL : Managing change log in a Table SQL : Managing change log in a Table
On every Create , Alter SP / UDF / Trigger / View scripts, I will have to add an entry in a table along with the entire script syntax. Table will have a row of record which has user who changed, date time , database the change taken, whole script.
In SQL, How to do that in an effective way ?

A: You can use a DDL Trigger for these kind of changes. See the DDL Events which include all of the events you want to capture.
If you want the easy button, SQL Server MVP Aaron Bertrand wrote something a good while back to track these kind of changes.

A: As it is mostly the table structure updation and then inserting data so best choice go for ddl trigger on creation of table then alter the table as the after action when action is triggered


text:
Q: JSF/PrimeFaces selectOneMenu change view-id I'm using JSF2 and PrimeFaces3. How can I write selectOneMenu that would invoke JSF navigation to redirect user to another page when he change option in menu?

A: Attach an ajax listener and let it navigate by NavigationHandler.
E.g.
<h:form>
    <h:selectOneMenu value="#{navigator.outcome}">
        <f:selectItem itemLabel="Select page..." />
        <f:selectItem itemValue="page1" itemLabel="Page 1" />
        <f:selectItem itemValue="page2" itemLabel="Page 2" />
        <f:selectItem itemValue="page3" itemLabel="Page 3" />
        <f:ajax listener="#{navigator.navigate}" />
    </h:selectOneMenu>
</h:form>

(the above example expects page1.xhtml, page2.xhtml and page3.xhtml in the same context; you can even make it a <f:selectItems> instead)
with
private String outcome;

public void navigate() {
    FacesContext context = FacesContext.getCurrentInstance();
    NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
    navigationHandler.handleNavigation(context, null, outcome + "?faces-redirect=true");
}

The ?faces-redirect=true is not necessary, but it effectively sends a redirect so that the URL in browser address bar will properly change which is better for user experience and bookmarkability of the pages.

A: You could have something like:
<p:selectOneMenu value="#{myBean.mySelectedPage}">
           <f:selectItem itemValue="http://www.yahoo.com" itemLabel="yahoo"  />
           <f:selectItem itemValue="http://www.google.com" itemLabel="google" />
           <f:selectItem itemValue="search.jsf" itemLabel="search" />
           <p:ajax event="change" listener="#{myBean.myNavigationMethod}" />
 </p:selectOneMenu>

and on your navigationMethod you have:
String myPage = mySelectedPage
FacesContext.getCurrentInstance().getExternalContext().redirect(myPage);

The first two selectItem are for a full url and the last one is for another page in your web application(be careful that the extension must be the one set in your web.xml - it could be .jsf, .xhtml, .htm etc)

A: Instead of using ajax navigation use the following:
<p:selectOneMenu value="#{navigator.outcome}" onchange="window.location =this.options[this.selectedIndex].value">
    <f:selectItem itemLabel="Select page..." />
    <f:selectItem itemValue="page1" itemLabel="Page 1" />
    <f:selectItem itemValue="page2" itemLabel="Page 2" />
    <f:selectItem itemValue="page3" itemLabel="Page 3" />
    <p:ajax event="change" listener="#{navigator.navigate}" />
</p:selectOneMenu>

This works even if the session times out.


text:
Q: CodeMirror: Catching Enter Key prevents line breaks I used the extraKeys-option of CodeMirror 3.12 to detect when the user starts a new line:
extraKeys: {
    "Enter": onNewLine
}

onNewLine() does nothing but a console.log(). Now CodeMirror ignores that key. You can't start a new line anymore. Is there a way to hook up additional functionality on a new-line-event without interfering CodeMirror internals? I just want to analyze the text of the recently closed line.

A: Add a line break at the end of onNewLine function.
This should work
 function onNewLine(e){
    console.log(e);
    editor.replaceSelection("\n" ,"end");
  }

A: I found that returning CodeMirror.Pass also works:
function onNewLine(e) {
    console.log("Enter key was pressed!");
    return CodeMirror.Pass;
}

From the documentation:

A key handler function may return CodeMirror.Pass to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.

This seems to work even if the handler does perform an action.  In my case I was using the editor.indentLine function to indent the current line when the user pressed the enter key.


text:
Q: Ipad app with two UIWebViews I have an iPad app with two UIWebviews, one on top of the other. Is there a way to have all the links that are clicked in one, open in only the other view?

A: Use this in the delegate for your first UIWebView:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [otherWebView loadRequest:request];

        return NO;
    }

    return YES;
}


text:
Q: shell command not executing the same from php I am executing a shell command from php using the following:
if($dig!=""){
            $command = escapeshellcmd('python3 '. dirname(__file__). '/create_pdf.py digital '.$inv);
   }else{
            $command = escapeshellcmd('python3 '. dirname(__file__). '/create_pdf.py hmml'.$inv);
}

This is what is found in create_pdf.py
#!/usr/bin/env python3

import os
import glob
from fpdf import FPDF
from PIL import Image
import time
import sys
from PyPDF2 import PdfFileMerger
from PyPDF2 import PdfFileReader

imagetype =  sys.argv[1:][0]

pdf_id = sys.argv[1:][1]

#path containing images - to change to mnt
if imagetype == 'digital':
    root = '/mnt/../Digital/'
    rootPDF = '/home/../public_html/wp-content/uploads/Scans/Digital/'
else:
    root = '/mnt/../VHMML/'
    rootPDF = '/home/../public_html/wp-content/uploads/Scans/VHMML/'

for i in os.listdir(root):
    if  pdf_id in i:
        files = i

imageList = sorted(glob.glob(root+files+'/*.jpg')+sorted(glob.glob(root+files+'/*.JPG')))

pdf = glob.glob(root+"*/"+"*.pdf")

name = root.split(" ")[0]
#path where pdfs are to be stored
namePath = rootPDF+pdf_id+".pdf"

noImages = len(imageList)
factorL = 0.25
factorP = 0.5
im_list = []
start = time.time()

with open('debug.txt', 'a') as f:
    f.write(imagetype)
    f.write(pdf_id)
    f.write(str(noImages))

Somehow the debug file is written when I run the python script from command line but not from php. Any idea why please? The php code is found in the functions.php of wordpress.
The Apache error log is showing:
(32)Broken pipe: [client] mod_fcgid: ap_pass_brigade failed in handle_request_ipc function


text:
Q: The Jquery's document ready is not working in partial view I have an MVC 4 web application(a testing site).
I have a Product Controller , Product Views(Index(a non partial view) and Product.cshtml(a partial view)). I also have a _Layout(came from MVC)
Index.cshtml(Not a partial view)
@model IdentityASP.Models.ViewModel.ProductViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

     @Scripts.Render("~/bundles/jquery")
     @Scripts.Render("~/bundles/jquery-unobstrusive-ajax")

    @using (Ajax.BeginForm("SearchProduct", "Product", null, new
    AjaxOptions() { UpdateTargetId = "searchResults" }, null))
    {
    <input type="datetime" name="From" />
    <input type="datetime" name="To" />
    <input type="submit" name="submit" value="Submit" />
    }

@Html.Partial("~/Views/Product/Product.cshtml")

This renders ALL data in the beginning @Html.Partial("~/Views/Product/Product.cshtml")
When searching specific data this is also what is being used.
Product.cshtml (Partial View)
@model IdentityASP.Models.ViewModel.ProductViewModel

                Product Id
                CategoryId
                Category
                ManufacturerId
                ManufacturerName
                Name
                Description
                Model
                Released Date
                Released Year
                Action

            @foreach (var item in Model.ProductList)
            {

                    @item.Id
                    @item.CategoryId
                    @item.CategoryDescription
                    @item.ManufacturerId
                    @item.ManufacturerName
                    @item.Name
                    @item.Description
                    @item.Model
                    @item.ReleasedDate
                    @item.ReleasedYear
                    <button type="button" data-toggle="modal" href="@Url.Action("EditProduct", "Product",new { id = item.Id })" data-target="#AddProductModal" class="btn-edit btn btn-info btn-default">Edit</button>
                    <button type="button" class="btn-delete btn btn-info btn-default">Delete</button>

            }

Script that are all located in  Index.cshtml

The question is , the document ready is working properly upon loading the Index and Partial View to display ALL list of data(You've got the searchbox, the highlights upon clicking each row).
but document ready is not working properly upon loading the Partial View after searching a specific data(using Index.cshtml AjaxBeginForm SearchProduct),You've got NO highlights after clicking each one and  no searchbox. I noticed all functions that are not under document ready are being called.
Why? , I will appreciate your responses
Thank you a lot
-John

A: Its now working, I put the document ready script to Product.cshtml partial view and now the click and highlight are now working.
Thanks,
John


text:
Q: How to autocomplete file paths in Vim, just like in zsh? In Zsh, I can use filename completion with slashes to target a file deep in my source tree.  For instance if I type:
 vim s/w/t/u/f >TAB<

zsh replaces the pattern with:
 vim src/wp-contents/themes/us/functions.php

What I'd like is to be able to target files the same way at the Vim command line, so that typing
 :vi s/w/t/u/f >TAB<

will autocomplete to:
 :vi src/wp-contents/themes/us/functions.php

I'm trying to parse the Vim docs for wildmode, but I don't see what settings would give me this.  It's doing autocompletion for individual filenames, but not file paths.  Does Vim support this natively?  Or how can I customize the autocomplete algorithm for files?
Thanks for any advice!
-mykle-

A: Vim doesn't have such a feature by default. The closest buil-in feature is the wildmenu/wildmode combo but it's still very different.
A quick look at the script section of vim.org didn't return anything but I didn't look too far: you should dig further. Maybe it's there, somewhere.
Did you try Command-T, LustyExplorer, FuzzyFinder, CtrlP or one of the many similar plugins?
I use CtrlP and fuzzy matching can be done on filepath or filename. When done on filepath, I can use the keysequence below to open src/wp-contents/themes/us/functions.php (assuming functions.php is the only file under us that starts with a f):
,f " my custom mapping for the :CtrlP command
swtuf<CR>

edit
In thinking about a possible solution I'm afraid I was a little myopic. I was focused on your exact requirements but Vim has cool tricks when it comes to opening files!
The :e[dit] command accepts two types of wildcards: * is like the * you would use in your shell and ** means "any subdirectory".
So it's entirely possible to do:
:e s*/w*/t*/u*/f*<Tab>

or something like:
:e **/us/f<Tab>

or even:
:e **/fun<Tab>

Combined with the wildmode settings in Jim's answer, I think you have got a pretty powerful file navigation tool, here.

A: I couldn't find a plugin to do this, so I wrote one.  It's called vim-zsh-path-completion.  It does what you're looking for, although via <C-s> rather than <Tab>.  You can use it with <Tab> for even more control over what matches, though.
It's got bugs, but for basic paths without spaces/special characters, it should work.  I think it's useful enough in its current state to be helpful.  I hope to iron out the bugs and clean up the code, but I figured I'd start soliciting feedback now.
Thanks for the idea!
Original (wrong) answer, but with some useful information about Vim's wildmode.
Put the following in your .vimrc:
set wildmenu
set wildmode=list:longest

That will complete to the longest unique match on <Tab>, including appending a / and descending into directories where appropriate.  If there are multiple matches, it will show a list of matches for what you've entered so far.  Then you can type more characters and <Tab> again to complete.
I prefer the following setting, which completes to the first unique match on <Tab>, and then pops up a menu if you hit <Tab> again, which you can navigate with the arrow keys and hit enter to select from:
set wildmode=list:longest,list:full

Check out :help wildmenu and :help wildmode.  You might also want to set wildignore to a list of patterns to ignore when completing.  I have mine as:
set wildignore=.git,*.swp,*/tmp/*


text:
Q: How do you get console input and output in a Windowed C++ project? I would like to make a debug system in C++ where I can get input from a console and output.  Output is the most important, but I would also like to get input to be able to change settings during program execution.
Does anyone have any good methods on solving this dilemma?

A: look at http://msdn.microsoft.com/en-us/library/ms681944(VS.85).aspx

*

*AllocConsole

*AttachConsole

*GetStdHandle

*WriteFile

*ReadFile


text:
Q: How to check if a table exist in Oracle? In Sql I check if a table exist with this code:
IF NOT EXISTS (SELECT NAME FROM SYSOBJECTS
     WHERE NAME = 'Plane')
   CREATE TABLE Plane(Flight int)

How to do this check if a table not exist then i create it in Oracle because it throws exception if i try to create already existing table?

A: you can check the data dictionary for that table
select table_name from user_tables where table_name='MYTABLE';

A: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]


text:
Q: Is it generally accepted that Field Aligned Currents are caused by Force-Free Fields? I am currently an undergraduate working on a project about FAC (Birkeland Currents) and it seems that most of the sources on the subject are very technical and hard for me to read (particularily because I am not at all familiar with plasma physics). My understanding is that FACs are caused by a Force-Free magnetic field but it is not at all clear to me what exactly causes them.
I looked into Perrat's Physics of the Plasma Universe, Donald Scott's paper about force-free FAC model (not too sure Scott is a good source tbh), D. Southwood and M. Kivelson's paper "An approximate Description of Field-Aligned Currents in a Planetary Magnetic Field".

A:
Is it generally accepted that Field Aligned Currents are caused by Force-Free Fields?

In a plasma, a force-free field is one that satisfies $\mathbf{j} \times \mathbf{B} = 0$, where $\mathbf{j}$ is the electric current density and $\mathbf{B}$ is the magnetic field.  One way to guarantee that the system is force-free would be to only allow $\mathbf{j}$ to be parallel to $\mathbf{B}$, i.e., field-aligned.

My understanding is that FACs are caused by a Force-Free magnetic field but it is not at all clear to me what exactly causes them.

No, the field-aligned currents (FACs) are not caused by the force-free magnetic field, at least not in the sense I think you are implying.  A FAC corresponds to a force-free configuration of the magnetic field but that doesn't mean it causes itself (see the circular reasoning there if it did?).  FACs can be caused by all sorts of things from just the simple Lorentz force making it easier to flow along $\mathbf{B}$ than across it, to large-scale kinetic Alfven waves differentially accelerating particles along $\mathbf{B}$ (e.g., electrons can be accelerated better than ions in some cases resulting in a differential flow between oppositely charged particles, i.e., a current).


text:
Q: .htaccess file to block all IPs except 4 and always allow requests to /api/ for averyone I am trying to disallow all requests by
RewriteCond %{HTTP:X-FORWARDED-FOR} !=67.x.x.x
RewriteCond %{REQUEST_URI} !^api
RewriteRule ^(.*)$ - [R=403,L]

ErrorDocument 403 "<html><hea....

So the IP 67 should be allowed for all REQ - but the directory /api/ should be accessible for everyone.
How can I do that?

A: You Can apply some of these directives.
Also, am thinking that your api is a directory
order deny,allow
deny from all
allow from 222.333.444, 67.8.9.9 # ALLOWED IPS MUST BE SEPARATED BY COMMAS

<Directory /api>
# All access controls and authentication are disabled
# in this directory
Satisfy Any
Allow from all
</Directory>

A: To deny access to all but 4 specific ip addresses you can use a negative RewriteCond and regex pattern  to match against the allowed ip addresses  something like the following :
RewriteCond %{REMOTE_ADDR} !(ip1|ip2|ip3|ip4)

If you do not want your /api uri to be redirected to 403 you can exclude it in your Rewrite pattern so that the uri is available for both allowed and denied  ip addresses.
Full code :
RewriteEngine on

RewriteCond %{REMOTE_ADDR} !(ip1|ip2|ip3|ip4)
RewriteRule !api - [R=403,L]


text:
Q: Conditional Expectation - Aplications E(g(X)|Y) Y$\sim Be(1/5)$ and let E denote an arbitrary event, and define the indicator random variable X by
$X=\begin{cases} 1 & \text{if E occurs}\\0 & \text{if E does not occur}& \end{cases}$
If $P(X=1|Y=0)=1/3$, $P(X=1|Y=1)=1/4$ and $g(x)=x^2$. Caculate $P(\mathbb{E}(g(X)|Y)>1/2).$

I caculate,
$\mathbb{E}(X^2|Y=0)=0^2P(X=0|Y=0)+1^2P(X=0|Y=0)=1/3$
$\mathbb{E}(X^2|Y=1)=0^2P(X=0|Y=1)+1^2P(X=1|Y=1)=1/4$
But, I have no idea what can I do next =S. So any help or guidance is appreciated :)

A: Indeed: $\mathsf{E}(X^2\mid Y=0)\;$ $=\;0^2\mathsf P(X=0\mid Y=0)+1^2\mathsf P(X=\color{red}{1}\mid Y=0)\;\\=\;{1/3}$
And too: $\mathsf{E}(X^2\mid Y=1)\;$ $=\;0^2\mathsf P(X=0\mid Y=1)+1^2\mathsf P(X=1\mid Y=1)\\=\;1/4$
So therefore, as BGM commented: $\mathsf E(X^2\mid Y) = \tfrac 13 \;\mathbf 1_{[Y=0]}+\tfrac 14\;\mathbf 1_{[Y=1]}$

Thus its clear that: $\mathsf P(\mathsf E(X^2\mid Y)>\tfrac12)=0$


text:
Q: Error importing Shapefile to PostGIS using Importer GUI I'm trying to import a shapefile into a PostGIS database using the graphical importer. I just installed POSTGRESQL, and PostGIS. The GUI looks like this:

After testing that my database worked, I chose the shapefile that I wanted to upload, and then received a message that it had failed to import. I tried tweaking a few paramaters, but I'm not sure what I'm doing.
Are there any good tutorials or instructions about how to do this? I'm using Windows 7 64 bit.

Just adding a little more of my error message.

Shapefile import failed. Connection:
  host=localhost port=5432 user=postgres
  password='******'  Destination:
  public.Area Source File:
  D:\files\Area
  Shapefile type: Polygon Postgis type:
  MULTIPOLYGON[2] Failed SQL begins:
  "SET CLIENT_ENCODING TO UTF8; SET
  STANDARD_CONFORMING_STRINGS TO ON;
  BEGIN; CREATE TABLE "public"."Area"
  (gid serial PRIMARY KEY, "fid_1" int4,
  "area" numeric, "dtm" float8, "dsm"
  float8, "hgt" float8, "nat_area"
  numeric, "nat_peri" numeric, "nat_vol"
  num" Failed in pgui_exec(): ERROR:
  type "geography" does not exist LINE
  14: "the_geom"
  geography(MULTIPOLYGON,4326));
                      ^
Shapefile import failed.

I've tried running @MerseyViking's suggestion, and then importing again. In the Geometry Column: box I chose MULTIPOLYGON and then tried to import the projected shapefile. The following errors appeared:
Failed SQL begins: "CREATE INDEX "NeighborCheck_MULTIPOLYGON_gist" ON "public"."NeighborCheck" using gist ("MULTIPOLYGON" gist_geometry_ops);
COMMIT;
"
Failed in pgui_exec(): ERROR:  current transaction is aborted, commands ignored until end of transaction block

Shapefile import failed.

Then I tried ticking the Load into GEOGRAPHY column box in Options, and received the following error:
Failed SQL begins: "CREATE INDEX "NeighborCheck_MULTIPOLYGON_gist" ON "public"."NeighborCheck" using gist ("MULTIPOLYGON" gist_geography_ops);
COMMIT;
"
Failed in pgui_exec(): ERROR:  current transaction is aborted, commands ignored until end of transaction block

Shapefile import failed.

Both error messages are identical and I don't quite understand them.

A: The message you are getting is that 'type geography does not exist' This either means you did not install postgis correctly or you are using an older version? Geography data type was introduced in version 1.5

A: The clue is in the import log. Note that it says:
Failed in pgui_exec(): ERROR: type geography does not exist
LINE 10: "geog" geography(MULTIPOLYGON,4326));
          ^

Shapefile import failed.

So you should ensure you have a geography column named "geog", and that you are using a version of PostGIS that supports geography columns. If you do have a working geography column, make sure the importer supports them - the GUI seems to imply that it only handles geometry columns.
Also, I notice you don't have a database specified. You will need to create one and spatially enable it. There's a good chapter in PostGIS in Action that has a script that creates a database template from which you can create spatially enabled databases:
CREATE DATABASE template_postgis WITH TEMPLATE = template1 ENCODING = 'UTF8';
\c template_postgis;
CREATE LANGUAGE plpgsql; --this may not be needed if running 8.4
\i /usr/share/pgsql/contrib/postgis-1.5/postgis.sql;
\i /usr/share/pgsql/contrib/postgis-1.5/spatial_ref_sys.sql;
\i /usr/share/pgsql/contrib/postgis-1.5/postgis_comments.sql;
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template_postgis';
GRANT ALL ON geometry_columns TO PUBLIC;
GRANT ALL ON spatial_ref_sys TO PUBLIC;
\q

A: I too had the same problem and after investigation, I found that the issue was that I simply had not created the postgis spatial extension.
If this is the issue with you, then you can use the following Query:
CREATE EXTENSION postgis

A: I'm not sure about your question as I've never used that GUIS, but I have found that the SPIT tool in QGIS works quite well. You may want to try that and see if you still have a problem. If so, then it may be that particular shapefile? Have you tried multiple files?

A: If you haven't explicitly created a spatially-enabled database, that is probably the problem, as MerseyViking suggests.

A: It could be fixed after creating postgis extension in the database. The http://gis-techniques.blogspot.com/2015/09/fixed-shape-file-import-error-in.html illustrates the steps to create the extension.

A: Enabling the "Load into GEOGRAPHY column" checkbox resolved my problem.


text:
Q: Why fill work bad with nodes but okay with coordinates or anchors? It seems to me that (path) fill command in tikz doesn't work quite well with (default) nodes. See the example below to understand what I mean.
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\node [above]{Using nodes};
\draw (0,0) node(a){}--+(0:1) node(b){};
\draw (a)--++(-120:1) node(c){}--+(0:2) node(d){}--(b);
\fill (a) ..controls +(-2.5,-2) and +(-2,-3) ..(d)--(c)--(a);
\end{tikzpicture}
\begin{tikzpicture}
\node [above]{Using coordinates};
\tikzstyle every node=[coordinate]
\draw (0,0) node(a){}--+(0:1) node(b){};
\draw (a)--++(-120:1) node(c){}--+(0:2) node(d){}--(b);
\fill (a) ..controls +(-2.5,-2) and +(-2,-3) ..(d)--(c)--(a);
\end{tikzpicture}
\begin{tikzpicture}
\node [above]{Using anchors};
\draw (0,0) node(a){}--+(0:1) node(b){};
\draw (a)--++(-120:1) node(c){}--+(0:2) node(d){}--(b);
\fill (a.base) ..controls +(-2.5,-2) and +(-2,-3) ..(d.base)--(c.base)--(a.base);
\end{tikzpicture}

\end{document}

What is the reason for this weird behaviour of fill?

A: To see the problem with a non-closed path, only draw the fill like this:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node [above]{Using nodes};
\path (0,0) node(a){}--+(0:1) node(b){};
\path (a)--++(-120:1) node(c){}--+(0:2) node(d){}--(b);
\draw[red, fill=yellow] (a) ..controls +(-2.5,-2) and +(-2,-3) ..(d)--(c)--(a);
\end{tikzpicture}
\end{document}

To correct it; here is one way by using the center points of the nodes:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node [above]{Using nodes};
\path (0,0) node(a){}--+(0:1) node(b){};
\path (a)--++(-120:1) node(c){}--+(0:2) node(d){}--(b);
\draw[red, fill=yellow] (a.center) ..controls +(-2.5,-2) and +(-2,-3) ..(d.center)--(c.center)--cycle;
\end{tikzpicture}
\end{document}


text:
Q: Foco em Elementos HTML com javascript Tenho o seguinte código. Este código contem 5 divs onde ao clicar sobre cada uma ,a que foi clicada recebe um valor de background.Quero que após clicar em uma delas,no próximo clique, a que foi clicada perca o beckground sem alterar as demais.
EX.:Cliquei na div 1 ,ficou vermelha.Cliquei na div 2 ,ficou vermelha,Cliquei na div 1 perdeu a cor vermelha ,mas a 2 tem de continuar vermelha.

 $(function () {

 $('.Classe').click(function () {

 $(this).css('background','red');

 });

 });

valor 1

valor 2

valor 3

valor 4

valor 5

A: Vc pode criar um classe que chama .ativa por exemplo e usar o método toggleClass para colocar e retirar o background vermelho quando clicar.
Veja o exemplo para entender melhor. Repare que no primeiro clique eu adiciona a classe .ativa que tem o background vermelho, e no segundo clique eu faço o toggleClass para remover essa classe assim retirando o vermelho do fundo.

$(".Classe").click(function(event){
   $(this).toggleClass("ativa");
});
div.ativa {
  background-color: #f00;
}

valor 1

valor 2

valor 3

valor 4

valor 5


text:
Q: getResources usage inside adapter class in android I have adapted class like this
public class InboxAdapter extends  RecyclerView.Adapter<InboxAdapter.ViewHolder> {
    private static final String LOG_TAG = InboxAdapter.class.getSimpleName();
    private List<inbox> mInboxes;
    private Context context;
    public InboxAdapter(List<inbox> inboxes) {
        mInboxes = inboxes;
    }

    @Override
    public InboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View contactView = inflater.inflate(R.layout.recyclerview_mail_item, parent, false);

        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(InboxAdapter.ViewHolder holder, int position) {
        inbox inbox = mInboxes.get(position);

        holder.tvIcon.setText(inbox.getName().substring(0,1).toUpperCase());
        holder.tvEmailSender.setText(inbox.getFrom());
        holder.tvEmailTitle.setText(inbox.getSubject());

    }

    @Override
    public int getItemCount() {
        return mInboxes.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tvIcon;
        public TextView tvEmailSender;
        public TextView tvEmailTitle;
        public TextView tvEmailDetails;
        public TextView tvEmailTime;

        public ViewHolder(View itemView) {
            super(itemView);

            tvIcon = itemView.findViewById(R.id.tvIcon);
            tvEmailSender = itemView.findViewById(R.id.tvEmailSender);
            tvEmailTitle = itemView.findViewById(R.id.tvEmailTitle);
            tvEmailDetails = itemView.findViewById(R.id.tvEmailDetails);
            tvEmailTime = itemView.findViewById(R.id.tvEmailTime);
        }
    }

    private int getRandomMaterialColor(String typeColor) {
        int returnColor = Color.GRAY;
        int arrayId =getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());

        if (arrayId != 0) {
            TypedArray colors = getResources().obtainTypedArray(arrayId);
            int index = (int) (Math.random() * colors.length());
            returnColor = colors.getColor(index, Color.GRAY);
            colors.recycle();
        }
        return returnColor;
    }

}

Its working fine but I want set different color for my view holder text so I have added function in it called getRandomMaterialColor. But its using getResources inside it and I am not able to use getActivity. Anyone here can please help me for solve puzzle for me? Thanks!

A: You can use the view(itemView) in ViewHolder Class for get the resources, for example:
   private int getRandomMaterialColor(View view,String typeColor) {
    int returnColor = Color.GRAY;
    int arrayId =view.getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());

    if (arrayId != 0) {
        TypedArray colors = view.getResources().obtainTypedArray(arrayId);
        int index = (int) (Math.random() * colors.length());
        returnColor = colors.getColor(index, Color.GRAY);
        colors.recycle();
    }
    return returnColor;
}


text:
Q: How to simulate process killed during phone call I have found that a (generally working) game app sometimes crashes if a phone call comes in during the game. After much experimentation and looking at logs, I have worked out the sequence of events that cause program to crash:

*

*The program is running.

*A phone call comes in.

*onPause() is executed.

at this point one of two things the game process may or may not be killed. This is under the control of the OS.
If it is not killed then, at the end of the phone call, onResume() is called and my program resumes perfectly without crashing.
If it is killed, then at the end of the phone call, my program will crash.
The problem I face now is that usually the process is not killed. So it is difficult to A) debug and B) check that any attempted fixes have worked. So my question now is, is there a way to arrange that my program always gets killed when a phone call comes in - or is there any other way of recreating my crash-causing scenario.

A: well first of all, I think that the reason for the crash is a NullPointerException, and you should check what happens in your onPause and onResume.
in the emulator, there is a simple way of emulating events that might happen during the general use of a device.
try reading this question: Ringing myself using android emulator


text:
Q: How to get WordPress user role to show in new user notification email I'm trying to modify the wordpress new user notification email to admin, using a bit of code someone else shared on here.  Here's what I have added to it, but in the new user notification email it displays: "Role: Array" instead of the role value.  Any suggestions on how to get it to show the role value?
<?php
/*
Plugin Name: Custom New User Email
Description: Changes the copy in the email sent out to new users
*/
// Redefine user notification function
if ( !function_exists('wp_new_user_notification') ) {
function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {
    $user = new WP_User($user_id);

    $user_login = stripslashes($user->user_login);
    $user_email = stripslashes($user->user_email);
    $user_info = get_userdata(1);

    $message  = sprintf(__('New user registration on %s:'), get_option('blogname')) . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
    $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n\r\n";
    $message .= sprintf(__('Role: %s'), $user_info->roles) . "\n";

    @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message);

}
}

?>

A: FYI, I figured it out and decided to post as an answer in case anyone is interested in adding this to the new user notification email (to admin only):
<?php
/*
Plugin Name: Custom New User Email
Description: Changes the copy in the email sent out to new users
*/
// Redefine user notification function
if ( !function_exists('wp_new_user_notification') ) {
    function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {
    $user = new WP_User($user_id);

    $user_login = stripslashes($user->user_login);
    $user_email = stripslashes($user->user_email);
    $user_meta = get_userdata($user_id);
    $user_roles = $user_meta->roles;

    $message  = sprintf(__('New user registration on %s:'), get_option('blogname')) . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
    $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n\r\n";
    $message .= sprintf(__('Role: %s'), implode(', ',$user_meta->roles)) . "\n";

    @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message);

    if ( empty($plaintext_pass) )
        return;

    }
}

?>


text:
Q: Was this question a suitable review queue audit test? I just got tripped up in the /review queue on this question
It showed up in the Re-Open queue, and seemed terribly written, and overly broad, so I voted to keep it closed.  The audit notification alerted me that there were no major problems with the question.
Was I being overly harsh, or should this not have been used as an example of a question without major problems?

A: If an item in a review audit can generate a real discussion on meta, and gather mixed upvotes/downvotes, then it's a terrible audit question.  The goal of an audit question isn't to see if you can adequately defend your nuanced opinion; it's to make sure you're awake.  It's like putting an essay exam where a pop quiz to make sure you're paying attention should be.

A:
Was I being overly harsh, or should this not have been used as an example of a question without major problems?

It's a lousy example, albeit one that could've been edited and not closed. I kinda think 5 votes is too low a bar for "pure gold" on SO.

A: The question is specific, its goals are clear.
The question is weak, as the author posts no framework for how the question should be solved other than the tags.  Accepting the tags are correct, I disagree that it is overly broad.
In this context, closing might have been harsh, but once it had been closed, reopening seems improper, so your decision seems correct and perhaps the appropriateness of this audit should be further scrutinized.


text:
Q: Android Studio suddenly corrupted cannot read xml and java file I open my previous project and I checked it corrupted as you can see at the picture that I attached. It seems that Android Studio cannot read the file. It is happened after I update my window 8 to window 10 and import open CV library. I already tried restart my computer, after that I uninstall and reinstall Android Studio and I already tried invalidate cache memory.
? IHDR @ @?? ` U ??IDATx?  C ?Q?@ ; m۶m'  6 qֱm۶m۶ g<u     {S? w ,    Wʠ        ???  4C?  1??  xHa$  x ,$  x@R>!a}$  aGb? Xt a~ A   ?G5B T?G D   ? A\ IN ???  ??I {Ĥ  sf  #?f  ?? p 1   ? j#?U &? w?   A? ? ?[ζ   ?O   5ܿrg R  gI @ o<7  F `" y ?Ͳ? aH47?k  +?M} %n  kD?      ;  n  W  8  #$Ǧ8 C4  X؇? ?  R9Z  ?D ? BQ#>"  ? A     ?E $? ? ] ???GlVH ?Q!  < e  ,Z Dlv? R# #  ,P  e<= e  @? ) ". ?  Xz @) 0   A= \ % b(b 7F?? x  ?b   ؎    ? c?  &4  ?b Ǵ???m\    EYQ  wƒ   }| ?    "??  ?; Æo @ 2$    ?w Б a Z   ?? D" H ?~" EQ?  ? >( q  ( K? %ٗn Ē    /? ++     IEND B`

A: Try deleting this folder C:\Users\user\.AndroidStudio3.*\system\caches manually.

A: If you have any backup of your project then add those backup files bcz I remember that when I got that error last month I tried everything but didn't get file back.


text:
Q: Post 2 Post: Getting connected 'person' from post author I am using the amazing P2P plugin (many thanks Scribu!) and I am having an issue that is probably right in front of my face but I just can't see.
I have a 'People' as CPT and I have connected that to 'Users'  with a 'Person_to_User' connection I created.
On single posts I want to get the connected 'person' in my 'People' CPT from that post author.
It seems like that should be fairly simple to do but my brain is hurting from trying to get this and I can't spend much more time on this.

A: On single post, try something like this:
$author_id = get_the_author_meta('ID');

$people = get_posts( array(
  'connected_type' => 'people_to_user', // replace with whatever
  'connected_items' => $author_id,
  'suppress_filters' => false,
  'nopaging' => true
) );

Now $people[0] references the first (and only) author related to the post you're on. So $people[0]->ID can be used to get the various bits of content, thumbnail, custom meta, etc.


text:
Q: custom prototype function for string to interpolate strings like c# in JavaScript Custom prototype function for string interpolation
 var str = "user";

console.log("hello {0}".format(str ));

A: I Found here the answer from another question
Here
String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));


text:
Q: How to fix this Basegame utils error? We have imported "com.google.example.games.basegameutils.BaseGameUtils" and set it as a library for our application, but it is still calling error.
The import
com.google.example.games.basegameutils.BaseGameUtils cannot be resolved


text:
Q: Python-can't detect file from path I develope a script who get a path, read the directory who contain pics and list and store in csv file from most old to most new.
But the script only work in the same folder where place the pics but not out of the folder. Traceback say:
OSERROR [2] no such directory found: 'picname.jpg'
And it's related with getntime.
It runs in Ubuntu 16.04 and Python 2.7, for aplication Anki2.0
It is the code;
https://github.com/Marcogb81/create-CSV-images-for-anki/blob/master/image_csv_anki.py

A: You must give the absolute path of the picture.
You must change:
directory.sort(key=lambda x: os.path.getmtime(x))

to
directory.sort(key=lambda x: os.path.getmtime(os.path.join(path, x)))


text:
Q: QScrollArea: auto-scroll to newly added widget it's not the first time that I want a scroll area which behaves like the following (imagine a log or chat window, but too complex to use a simple QTextBrowser):

*

*I want to add multiple widgets, which appear one below the other (like when placed in a QVBoxLayout)

*Each widget within this layout should have a fixed size or a height-for-width (like a simple label)

*The scroll area should auto-scroll to the most recently added one

*(optional) When there is space left (scroll bar not yet enabled), the contents should be aligned to bottom

Using QScrollArea:
My attempt in the past was using a QScrollArea using a QVBoxLayout inside. But this seems to be not as simple as I thought: Whenever I add a widget to the layout, the layout doesn't resize the scroll area content widget immediately, resulting in a delayed adjustment of the contents. For one short moment, the widgets contained in the layout are resized so that the total size equals the total size before the add operation, resulting in a too small size per widget. Also, scrolling to the newly added widget is thus not possible until the layout corrected its size to the new total size of widgets, so even a QTimer::singleShot(0, ...) doesn't help here. Even with a timeout of 20 or so, there are situations in which the layout needs more time to resize. It's not deterministic, and thus far away from a nice solution.
In order to get the bottom alignment behaviour, I initially place a spacer item in the layout. It won't require any space as soon as there is no space left and scrolling gets enabled.
Using QListView:
As my items are too complex, they need to be QWidgets. They can't have the focus, aren't selectable, so an item-based solution seems to be just "the wrong way". Also, this solution sounds too "heavy".
I just can't believe that there is no easy way, so I think I just haven't seen it yet!

A: QListView should be fine. You claim that your items are static, there's no interaction with them: no focus, no selection. It'd seem that a QWidget is an overkill for such items. You only need something that has a fixed size and can draw itself. That is precisely what delegates in the Qt's model-view system are for. Just implement one or more QAbstractItemDelegates for your items, and provide an implementation of a model for the data they will be rendering. The QAbstractItemView is is already a QAbstractScrollArea!
If you want to paint HTML within a delegate, it's easy to do -- again, QWidget is an overkill for a static display! There is a very food reason why it's "hard" to use QWidget for this -- the API guides you to the correct solution. Assuming your model contains html for each item, here's how you can paint it. You can go fancy with the sizeHint, of course, and should be caching the text document, ideally storing it in the model I'd think.
void MyDelegate::paint(QPainter* p, const QStyleOptionViewItem & opt, const QModelIndex & index) const
{
   QTextDocument doc;
   doc.setHtml(index.data().toString());
   doc.drawContents(p, QRect(QPoint(0,0), sizeHint(opt, index)));
}

QSize MyDelegate::sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const
{
   return QSize(100, 200);
}


text:
Q: AngularJS Display 1 Post in New Page I want to display only Test Post 1 in next html page titleDetails.html when user clicks Test Post 1 in index.html
1) titleDetails() in index.html:
{{ post.title }}

2) controller variables and titleDetails() method:
function BlogController($scope, $http, $rootScope, $location) {
    $scope.createPost = createPost;
    $scope.deletePost = deletePost;
    $scope.editPost = editPost;
    $scope.updatePost = updatePost;
    $scope.titleDetails = titleDetails;
    $scope.postDetail = null;

function titleDetails(post)
{
    $scope.postDetail = post;
    $location.path('#/titleDetails');
}

3) body in titleDetails.html:

Blog

                    {{ postDetail.title }}

                    {{postDetail.posted}}

{{postDetail.body}}

FULL CODE:
app.js
(function () {
    angular
    .module("BlogApp", [])
    .controller("BlogController", BlogController);

    function BlogController($scope, $http, $rootScope, $location) {
        $scope.createPost = createPost;
        $scope.deletePost = deletePost;
        $scope.editPost = editPost;
        $scope.updatePost = updatePost;
        $scope.titleDetails = titleDetails;
        $scope.postDetail = null;

    function init() {
        getAllPosts();
    }
    init();

    function titleDetails(post)
    {
        $scope.postDetail = post;
        $location.path('#/titleDetails');
    }

    function updatePost(post){
        console.log(post);
        $http
        .put("/api/blogpost/"+post._id, post)
        .success(getAllPosts);
    }

    function editPost(postId){
        $http
        .get("/api/blogpost/"+postId)
        .success(function(post){
            $scope.post = post;
        });
    }

        function deletePost(postId){
            $http
            .delete("/api/blogpost/"+postId)
            .success(getAllPosts);
        }

        function getAllPosts(){
            $http
            .get("/api/blogpost")
            .success(function(posts) {
                $scope.posts = posts;
            });
        }

        function createPost(post) {
            console.log(post);
            $http
            .post("/api/blogpost",post)
            .success(getAllPosts);
        }
    }
})();

index.html
<!DOCTYPE html>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <title>Title</title>

Blog

            <input ng-model="post.title" class="form-control" placeholder="title"/>
            <textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
            <button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
            <button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>

                    {{ post.title }}

                {{post.posted}}

{{post.body}}

titleDetails.html:
<!DOCTYPE html>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <title>Title</title>

Blog

                    {{ postDetail.title }}

                    {{postDetail.posted}}

{{postDetail.body}}

A: a new scope variable in BlogController
$scope.postDetail = null;

and method titleDetails() be like
$scope.titleDetails = function(post) {
$scope.postDetail = post;
}

and also make change in index.html
 {{ post.title }}

A: Hope this following steps work for you
Pass post object to titleDetail() function.
In index.html
{{ post.title }}

In function assign post to $rootScope variable
$scope.titleDetails = function(post) {
   $rootScope.postDetail = post;
}

Now your titleDetail.html page controller:
$scope.post = $rootScope.postDetail;


text:
Q: How can I convert a date field to number in Google Data Studio? In Google Data Studio I'm searching for a formula to transform a date field into a number field.
I have been trying several options like these but they don't work.
CAST(Date_field as NUMBER)

Invalid formula - Cannot cast from DATE to DOUBLE

Date_field+0

Invalid formula - Operator "+" doesn't support DATE + NUMBER. Operator "+" supports NUMBER + NUMBER.

datevalue() or value() also don't exist.
Precision: I'm looking for a solution without changing the original date field in the data source or the connection. Only with a formula.
The expected result is a continuous series of integer numbers like this (the zero reference point doesn't matter, as long as 2 consecutive days are incremented by 1.)

Date_field
Expected_output

23 Feb 2022
44,615

22 Feb 2022
44,614

21 Feb 2022
44,613

2 Jan 2022
44,563

1 Jan 2022
44,562

31 Dec 2021
44,561

30 Dec 2021
44,560

A: The Expected_output values are how the underlying dates are formatted in Microsoft Excel and Google Sheets, which use the 1900 date system, where day 1 in Excel is 01 Jan 1900 while in Google Sheets day 1 is 31 Dec 1899 (day 2 is 01 Jan 1900), the reason being that "Excel incorrectly assumes that the year 1900 is a leap year", thus 29 Feb 1900 exists in Excel but not Google Sheets (for this reason, 31 Dec 1899 will be used below).
The calculated field below recreates the values in the Expected_output field by using the DATETIME_DIFF function to find the difference between the values in the Date_field and fixed date, 31 Dec 1899 (explained above), that was created using the DATE function which "creates a date" in the Year, Month, Day format; the +1 was added to include n+1 days (to count the initial day):
DATETIME_DIFF(Date_field, DATE(1899, 12, 31), DAY) + 1

Editable Google Data Studio Report (Embedded Google Sheets Data Source) and a GIF to elaborate:


text:
Q: How to find an upper triangular with $\ U^2 = I $ which gives $\ U $ is its own inverse It's obvious that $\ I $(identity matrix) of any size $\ N $ satisfies$\ I^2 = I$  so that $\ I $ is its own inverse.
However if we consider $\ N = 2$ and attempt to find such a triangular matrix $\ U \neq I $ we have this scenario:
$$\begin{bmatrix} u_1 & u_2 \\ 0 & u_3 \\ \end{bmatrix} .\begin{bmatrix} u_1 & u_2 \\ 0 & u_3 \\ \end{bmatrix} = I$$
$$\begin{bmatrix} u_1 & u_2 \\ 0 & u_3 \\ \end{bmatrix} .\begin{bmatrix} u_1 & u_2 \\ 0 & u_3 \\ \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ \end{bmatrix}$$
$$\begin{bmatrix} u_1^2 & u_1u_2 + u_2u_3 \\ 0 & u_3^2 \\ \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ \end{bmatrix}$$
After solving this we realize that $\ u_1 = 1,u_2, u_3 = -1$ is the form of the solution where $\ U \neq I $ for $\ N = 2 $.
But for $\ N \ge 3 $, what will be the form of such matrices?

A: Observe that $U = \operatorname{diag}(\pm 1, \dots, \pm 1)$ is a diagonal (and in particular, upper triangular) matrix that satisfies $U^2 = I$. If $P$ is an invertible upper triangular matrix then $U' = P^{-1} U P$ is also upper triangular (as a product of upper triangular matrices) and satisfies
$$ U'^2 = P^{-1} U P P^{-1} U P = P^{-1} U^2 P = P^{-1} I P = I. $$
In fact, the other direction is also true. That is, if $U$ is an upper triangular matrix that satisfies $U^2 = I$ then we can an upper triangular $P$ such that $P^{-1} U P = \operatorname{diag}(\pm 1, \dots, \pm 1)$. To see this, note that the equation $U^2 = I$ implies that the minimal polynomial of $U$ divides $(x^2 - 1) = (x - 1)(x + 1)$ and so $U$ is diagonalizable with eigenvalues $\pm 1$. Since $U$ is upper triangular, each subspace $\left< e_1, \dots, e_i \right>$ is $U$-invariant (where $e_i$ are the standard basis vectors of $\mathbb{F}^n$) and $U|_{\left< e_1, \dots, e_i \right>}$ is also diagonalizable. This implies that we can choose eigenvectors $v_i$ for $U$ such that $v_i \in  \left< e_1, \dots, e_i \right>$ for all $1 \leq i \leq n$. Taking the vectors $v_i$ to be the columns of $P$, we obtain the required result.

A: Here's one possible form. Let $a$ be any number. Define an $n \times n$ matrix as given below.
\begin{equation*}
A = \begin{bmatrix}
1 & a & \dfrac{a^2}{2} & \dfrac{a^3}{4}& \cdots & \dfrac{a^{n-1}}{2^{n-2}}\\
0 & -1 & -a & -\dfrac{a^2}{2} & \cdots & -\dfrac{a^{n-2}}{2^{n-3}}\\
0 & 0 & 1 & a & \cdots & \dfrac{a^{n-3}}{2^{n-4}}\\
0 & 0 & 0 & -1 & \cdots & -\dfrac{a^{n-4}}{2^{n-5}}\\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots\\
0 & 0 & 0 & 0 & \cdots & (-1)^{n-1}
\end{bmatrix}
\end{equation*}
Then $A^2 = I$ (verify).


text:
Q: How to include iframe coding in joomla How to include iframe coding in joomla

A: Joomla has TinyMCE as default Editor. It don't allow iframe tag.
You can enable iframe tag in Editor.
Go to > Extensions > Plugins > TinyMCE
Paste iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder]
in Extended Valid Elements
Now go back to your editor, open html view and paste your iframe code. It will save it.

A: Edit HTML in the editor and add the  tag there.

A: I needed to paste an image in a frame, so after i understood that i can't use frames i paste this code, cause i needed scroller.

If you need to paste a video from youtube it is better to hide the video under a image (screensho for example) giving the link to video. not iframe nor embed doesn't work in joomla.
hope that help)


text:
Q: Importing JavaScript files in Typescript, unable to access functions in TS, able to access them in html I recently started integrating TypeScript and React with my companies legacy JavaScript code base. It's been very hit and miss, as I'm sure many of you understand.
After overcoming many of the big hurdles such as setting up a proper webpack process, understanding and setting up tsconfig files and breaking up the bundling properly, I've finally integrated it all with our current CI-pipeline.
However, now I'm having an issue with importing JavaScript libraries in my TypeScript code. I know it's bad practice, but it's sort of a middle-hand before moving to becoming fully TS-compliant.
I've got this basic component which builds fine:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Header } from "./components/header";
import * as $C from "./../../fortress.content.js";
import * as $F from "./../../fortress.js";

let url : string  = $F.writeUrl("Account", "LoginAjax");

ReactDOM.render(

 {url}

,
    document.getElementById("body")
);

$F.writeUrl allows us to essentially create a string based on a webconfig file in the root of the project, so basically a function taking a few different parameters and returning a string based on it:
However, when I run the transpiled JavaScript in a baremetal html file:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

I get these errors:
Uncaught TypeError: Cannot read property 'bind' of undefined
    at new t (filemanager.bundle.js:1)
    at ReactCompositeComponentWrapper.mountComponent (react.js:5504)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (react.js:12346)
    at Object.mountComponent (react.js:12971)
    at ReactDOMComponent.mountChildren (react.js:11685)
    at ReactDOMComponent._createContentMarkup (react.js:6817)

anothermanager.bundle.js:1 Uncaught ReferenceError: $C is not defined
    at anothermanager.bundle.js:1
    at Object.<anonymous> (anothermanager.bundle.js:1)
    at n (anothermanager.bundle.js:1)
    at Object.<anonymous> (anothermanager.bundle.js:1)
    at n (anothermanager.bundle.js:1)
    at anothermanager.bundle.js:1
    at anothermanager.bundle.js:1
    at ReactDOMComponent.mountComponent (react.js:6705)
    at Object.mountComponent (react.js:12971)
    at ReactCompositeComponentWrapper.mountComponent (react.js:5581)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (react.js:12346)

index.html:17 Uncaught ReferenceError: $F is not defined
    at index.html:17

So I tried changing this to instantiate $C and $F in my TS:
let test = $F;
let test2 = $C;

This removed the above errors and actually shows me the $F and $C objects in my console log. But the problem now is that the $F.writeUrl("Account", "LoginAjax") is blowing as Chrome won't recognise it as a "function".
Have I done anything wrong with my imports?

A: I guess you don't need to import those files in your react bundle. If those files doesn't export anything with module.exports or export, and instead they just setup window members to be used later (which was in fact the standard years ago), as far as I know you should:
1)
Load those files as scripts, so they are available everywhere. Be sure to add them before any react related script/bundle, so you're sure they are available when the react code mounts:

2)
Now, they are available in your react code. You need to use them from window instead to let your bundler handle the $F/$C modules:
let $f: any = (window as any).$F;
let url : string  = $F.writeUrl("Account", "LoginAjax");

A:
[...] importing JavaScript libraries in my TypeScript code. I know it's bad practice, but it's sort of a middle-hand before moving to becoming fully TS-compliant

Don't worry, it's not necessarily a bad practice, especially during a transitionary period.
In a small addition to Sergeon's answer that covers the implementation problem, I'll add that some JavaScript libraries do have typings that allow you to use them in TypeScript applications, like jQuery:
npm i --saveDev "@types/jquery"

Then to use the typings in a .ts module:
import "jquery";
declare const $: JQueryStatic;

Which also gives you the benefit of some IDE IntelliSense assistance:

You can look for and add your other libraries from the @types/ repository, if you desire.


text:
Q: Rxjs combine objects (the right way) I have the following object:
const myObject = {
  info: [
    { id: 'F', pronouns: 'hers' },
    { id: 'M',  pronouns: 'his'}
  ],
  items:[
    {
      name: 'John', age: 35,
      children: [
        {child: 'Eric',age: 10,sex: 'M'},
        {child: 'Andrea',age: 4,sex: 'F'}
      ]
    },
    {
      name: 'Bob', age: 23,  children: [
        { child: 'Oscar', age: 1, sex: 'M'}
      ]
    }
  ]
}

I tried to combine this so I wil have a new Observable that looks like:
const newObject = {
  info: [
    { id: 'F', pronouns: 'hers', persons:
        [{
          name: 'John', age: 35,
            children: [
              {child: 'Andrea',age: 4,sex: 'F'}
          ]
        }]
    },
    { id: 'M', pronouns: 'his', persons:
        [{
          name: 'John', age: 35,
          children: [
            {child: 'Eric',age: 10,sex: 'M'},
            {child: 'Andrea',age: 4,sex: 'F'}
          ]
        },
        {
          name: 'Bob', age: 23,  children: [
            { child: 'Oscar', age: 1, sex: 'M'}
          ]
        }]
    },
  ]};

I tried varioous functions, but I think I miss a functional concept.
The filtering can be done by
const source = of(myObject).pipe(
  map(x => x.items),
  map(x => {
    return x.filter(y => {
      return y.children.find(y => y.sex === 'M');
    })
  }),
  map(x => {
    return x.map(y => {
      return {
        ...y,
        children: y.children.filter(c => c.sex === 'M')
      }
    })
  })
);

But then I'll missing the info part of the object...

A: you needn't a observable
const newObject = {
  info: myObject.info.map(x => {
    const person = myObject.items
      .map((p:any) => ({...p,children:p.children.filter(c=>c.sex==x.id)}))
      .filter(p=>p.children.length)
    return {...x,persons:person};
  })
};

If you want an observable take account that only the first "map" is the rxjs operator map, the rest are map of array
of(myObject)
  .pipe(
    map(obj => {
      return {
        info: obj.info.map(x => {
          const person = myObject.items
            .map((p: any) => ({
              ...p,
              children: p.children.filter(c => c.sex == x.id)
            }))
            .filter(p => p.children.length);
          return { ...x, persons: person };
        })
      };
    })
  )

Updated corrected: in the observable is pipe(map(obj=... NOT pipe(map(this.newObject


text:
Q: wordpress wrong category name in url redirects to the actual category I have this url structure in my wordpress project:
www.example.com/category/subcategory/post
There is a weird issue where i'm entering a url with category & subcategory which do not exists - but with an existing post name, it redirects me to the relevant post.
so for instance:
I have a post named 'bitcoin' which is under the category 'reviews' and subcategory of 'trade'.
I go to - www.example.com/blabla/blulu/bitcoin
and I get redirected to - www.example.com/reviews/trade/bitcoin
I want to avoid this redirect from happening - any idea how or what is causing this?

A: I believe this is the sollution you are looking for:
function remove_redirect_guess_404_permalink( $redirect_url ) {
 if ( is_404() )
    return false;
 return $redirect_url;
}
add_filter( 'redirect_canonical', 'remove_redirect_guess_404_permalink' );

I found this answer here, but until I get reputation 50 I cannot post this as comment.


text:
Q: mocking session in requests library In my python code I have global requests.session instance:
import requests
session = requests.session()

How can I mock it with Mock? Is there any decorator for this kind of operations? I tried following:
session.get = mock.Mock(side_effect=self.side_effects)

but (as expected) this code doesn't return session.get to original state after each test, like @mock.patch decorator do.

A: Use mock.patch to patch session in your module. Here you go, a complete working example https://gist.github.com/k-bx/5861641

A: Since requests.session() returns an instance of the Session class, it is also possible to use patch.object()
from requests import Session
from unittest.mock import patch

@patch.object(Session, 'get')
def test_foo(mock_get):
    mock_get.return_value = 'bar'

A: With some inspiration from the previous answer and :
mock-attributes-in-python-mock
I was able to mock a session defined like this:
class MyClient(object):
    """
    """
    def __init__(self):
        self.session = requests.session()

with that: (the call to get returns a response with a status_code attribute set to 200)
def test_login_session():
    with mock.patch('path.to.requests.session') as patched_session:
        # instantiate service: Arrange
        test_client = MyClient()
        type(patched_session().get.return_value).status_code = mock.PropertyMock(return_value=200)

        # Act (+assert)
        resp = test_client.login_cookie()

        # Assert
        assert resp is None

A: I discovered the requests_mock library.  It saved me a lot of bother.  With pytest...
def test_success(self, requests_mock):
    """They give us a token.
    """
    requests_mock.get("https://example.com/api/v1/login",
        text=(
          '{"result":1001, "errMsg":null,'
          f'"token":"TEST_TOKEN",' '"expire":1799}'))

    auth_token = the_module_I_am_testing.BearerAuth('test_apikey')

    assert auth_token == 'TEST_TOKEN'

The module I am testing has my BearerAuth class which hits an endpoint for a token to start a requests.session with.


text:
Q: Mapping array parameter type to array return type? I have an enum to describe "fields", and a mapping of each field to a type:
enum Field {
  Id,
  Position,
  Name,
  Enabled,
}

interface FieldTypes extends Record<Field, any> {
  [Field.Id]: number;
  [Field.Position]: number;
  [Field.Name]: string;
  [Field.Enabled]: boolean;
}

I wrote a function to extract a given field from some data (which I've defined here as unknown type because it's not important for this question):
declare function getField<F extends Field>(
  data: unknown,
  field: F
): FieldTypes[F];

const position: number = getField({}, Field.Position);
const name: string = getField({}, Field.Name);

This compiles without error. getField indeed returns a number for position and a string for name.
Now I want to write a getFields function that extracts multiple fields from data in order, but I'm struggling to define it. Here's how I expect it to work:
const fields: [boolean, number, number] = getFields({}, [
  Field.Enabled,
  Field.Id,
  Field.Position,
]);

So how do I define this function? This is what I tried but it doesn't return the correct type:
declare function getFields<F extends Field>(
  data: unknown,
  fields: F[]
): FieldTypes[F][];

A: This should work for you:
enum Field {
  Id,
  Position,
  Name,
  Enabled,
}

interface FieldTypes extends Record<Field, any> {
  [Field.Id]: number;
  [Field.Position]: number;
  [Field.Name]: string;
  [Field.Enabled]: boolean;
}

First we create another type which takes an tuple of Field and returns an tuple with the corresponding types.
type MultipleFieldTypes<T extends readonly Field[]> = {
    [K in keyof T]: T[K] extends keyof FieldTypes ? FieldTypes[T[K]] : never
}

Then we modify the function getFields to accept a tuple of Field as the generic type F. As the return type we pass F to MultipleFieldTypes.
declare function getFields<F extends Field[]>(
  data: unknown,
  fields: [...F]
): MultipleFieldTypes<F>;

Now we have the correct return type:
const fields: [boolean, number, number] = getFields({}, [
  Field.Enabled,
  Field.Id,
  Field.Position,
]);

Playground


text:
Q: base.html for Django Registration Redux I am using django-registration-redux and everything works like a charm. However, I am a bit dissatisfied with the fact that it forces me to name the base template that it uses base.html, and that I have to put it in the templates directory.
I'd rather have it somewhere like this:
"/templates/registration/redux_base.html"
Is it possible to define this somewhere in my settings.py? I could not find that, but I think this must be possible. (Otherwise I am getting name clashes with other apps which is frustrating...)

A: Almost all templates from redux are extending template "registration/registration_base.html", except of templates for activation (for some reason they are extending directly from "base.html"). Template "registration/registration_base.html" looks literally like this:
{% extends "base.html" %}

So you can override that template (simply by creating "global" template for project on that location) and define here another {% extends %} or your whole new template.
But templates for email activation, as I mentioned above, are extending directly from "base.html" so if you are using them, you must overrite them separately.

A: Whenever it bothers you simply replace
{% extends "base.html" %}

with
{% extends "registration/redux_base.html" %}

And ofcourse create redux_base.html as you wish.


text:
Q: How can I show a user files and folders on a shared drive that are created by another user and with my app? I have the problem, that I can't show my users files created with my app on a shared drive, but created by other users. This destroys the collaboration possibilities. The scope I have registered is https://www.googleapis.com/auth/drive.file.
Is there any way to read files that are on a shared drive without the https://www.googleapis.com/auth/drive scope? I really would dislike using this scope.


text:
Q: Rails 3 activerecord query where clause with timezone I have a problem with my rails application (rails 3.2.x, MySQL 5.x). Sample case to produce:

*

*set time_zone='Hanoi' in application.rb

*model Post

*new post created at 2013-06-28 01:00:00 (date of server: Fri Jun 28 01:00:00 ICT 2013)

MySQL is config with timezone SYSTEM. created_at of new post will be store with value 2013-06-27 18:00:00
How can i find all posts in 2013-06-28 in rails app?
Post.where("DATE(created_at) = ?", Date.today)

Is this timezone configuration correct or not?


text:
Q: How to read a Delphi Array of Fixed Sized Strings within a packed record in c# I need to read a blob field from a database into a c# app.
However the blob field was written to the database by a Delphi App using the following method:
 procedure WriteABlob(Blob : TBlobField; var Buffer; size : integer);
 var
     s : String;
 begin
     setlength(s,size);
     move(buffer,s[1],Size);
     Blob.Value := S;
 end;

The Structure written to the database is not a simple structure and contains things like
MyVariable : Array[0..3] of String[80];

or worse some of them contain
MyRecord = Packed Record
case byte of
    1: (
        iValue:Integer;
       )
    2: (
        cValue:Char;
       )
end;

I've been trying reading in the bytes from the database and then using
Marshal.PtrToStructure()

in order to move it into the struct
My Struct is defined as follows:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1, Size = 10710)]
    public struct MyBlobField
    {
        ...
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.AnsiBStr,SizeConst = SpecificArraySize)]
        public String[] ArrayofFixedLengthStrings;
        ...
    }

But i get an error when calling Marshal.PtrToStructure():

Cannot marshal field
  'ArrayofFixedLengthStrings' of type
  'MyBlobField': Invalid
  managed/unmanaged type combination
  (String[] must be paired with an
  ArraySubType of LPStr, LPWStr, BStr or
  LPTStr).

I was wondering if there was a attribute I could define on a CustomMarshaler which would accept a pairing with a String[]
Any ideas how I could read the contents of the blob into c#?

A: Figured it out...
Declared a struct String20 as
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct String20
    {
        [MarshalAs(UnmanagedType.U1)]
        public byte StringSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
        public String Value;
    }

Apparently the string size identifier at the beginning of a fixed length string (i.e a delphi ShortString) is only 1 byte.
Then changed the definition of header_identifiers to:
       [MarshalAs(UnmanagedType.ByValArray, SizeConst = max_header_identifiers)]
        public String20[] header_identifiers;

Also found that Delphi Packed Boolean need to be cast as
[MarshalAs(UnmanagedType.I1)]
public bool BooleanVar;

A: My first comment is that the "String[80]" is a fixed-length string (which should be easier to handle in a structure), and in C# you are trying to put it into a "String[]" - which is actually a reference (pointer) to a string.
My next comment is that you could, at worst, try reading it into an array of bytes, and pull out the bytes you need and manipulate them into the destination structure.


text:
Q: PHP DOM and HTML entities I'm programming php cms with xml templates parsed by DOM and encountered error with html entities being replaced with symbols. Here is an example:
<CMS_STRING type="link" name="home" title="{enUS:"Home Link"}" />

After saving document ($doc->saveXML()) this gets converted to:
<CMS_STRING type="link" name="home" title="{enUS:"Home Link"}" />

And it causes errors with further template processing as I need to load and save multiple times (caching).
I also tried hex entities and $doc->substituteEntities = false but they were still converted.
EDIT: The problem actually was with DOMNode::attributes->getNamedItem()->nodeValue which I used to process attributes. It returns code with replaced html entities.


text:
Q: How to drive two complementary MOSFETs for a variable load? I am designing a variable digital load and I am controlling it with a PWM signal from an ESP32. The problem is that I don't know how to control the P-channel MOSFET. What would the circuit be?

UPDATE, it was as simple as an OpAmp


text:
Q: Insert data command not saving data into database in magento I have migrated a magento site successfully nut when i import database in phpmyadmin. it created all tables but not inserting all values in tables.
when i try to manually insert data.it does not save data and there in not error also..please help


text:
Q: Inequality with sums and products Let a,b,c,d positive real numbers such that
$a+b<c+d$ and
$(a+b)(c+d)<ab+cd$.
Prove that
$(a+b)cd>(c+d)ab$
Source: book on olympiads
I tried manipulating the given statements and i obtained
$3ab<cd$
To use this i would need to show that $cd<3(a+b)$ but i am stuck.

A: Since $ab+cd>(a+b)(c+d)$ and $ab<a(a+b)<a(c+d)$, $cd>b(c+d)$. Thus $(a+b)cd>acd>ab(c+d)$.


text:
Q: json parsing in android How to parse the following JSON in android ?
{"Servicedata":{"services_description":"Absolutely awesome compound on 50+ acres","services_image":"http:\/\/192.168.100.81\/watchdog_webservice\/service_images\/shop1.jpg","service_userid":"1"}}

A: JSONObject object = new JSONObject(yourJsonString);
JSONObject servicedata = object.getJSONObject("Servicedata");
String desc = servicedata.getString("services_description");
String image = servicedata.getString("services_image");
String id = servicedata.getString("service_userid");

A: What is the source of the JSON data? The below is for parsing JSON from a URL.
 try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }