text:
Q: DLL "missing" but present in path I am in the process of updating our build machine (from Windows Server 2008 to Windows 10), and we need to support both Python 2 and Python 3. We are using SWIG to generate Python bindings for our C++ code. As part of this we generate both a C++ only DLL (mylib_shared.dll, built directly using Clang) and a python-version-specific dll (_mylib.dll, built from swig).
The build is currently fine in Python 2.7, but for Python 3 when I try to import a function from _mylib.dll using the SWIG bindings, I get an error saying the shared dll is missing. This file is identical no matter which version of Python is running, and is definitely present, in the expected place and that directory is in the PATH variable (I've checked, very carefully). I have used Dependencies and dumpbin to check what it's looking for, the only difference I can see is that Python38.dll (which is obviously imported by the Python 3 version but not the Python 2 version) has a dependency on ws2_32.dll (present in C:\Windows\SysWOW64) that isn't a dependency for the equivalent Python 2 dll. That says it's missing api-ms-win-core-string-obsolete-l1-1-0.dll, but I think this is a red herring - that seems to be an implementation-dependent thing (see https://answers.microsoft.com/en-us/windows/forum/windows_10-files/missing-api-ms-win-core-dlls/d99d1368-0f92-43db-bbdb-7d080f1f96e9). I have checked that everything is being built for the correct architecture (32-bit) by loading the dlls with dumpbin.
So I'm stumped. I had a problem previously with mixed architectures causing a similar problem, but I resolved that and as I say, I'm now checking directly on the dlls being built, so I can't see it's that (also you'd expect it to be a problem for both versions of Python). The file is definitely there. I don't know what else would be causing Windows to claim it can't find the dll. Any help gratefully received!


text:
Q: Find interpretations of formulas Consider the structure $A=<\mathbb{N},<;\cdot,1>$. Find the following interpretations of formulas (for an arbitrary valuation
v):
(c) $[\![ \forall x_1\exists x_1 P(x_1,x_2) ]\!]$
(d) $[\![ \exists x_3\forall x_4 P(x_1,x_2) ]\!]$

Solution:
(c) $$[\![ \forall x_1\exists x_1 P(x_1,x_2) ]\!]$$
$$=\begin{cases}
1 \text{ if for all } a\in |A|\text{ there is some } b\in |A|\text{ } [\![ P(x_1,x_2) ]\!]^{[x_1\to a][x_1\to b]}\\
0 \text{ otherwise}\\
\end{cases}$$
$$[\![ P(x_1,x_2) ]\!]^{[x_1\to a][x_1\to b]}$$
$$=P^A([\![ x_1 ]\!]^{[x_1\to a][x_1\to b]},[\![ x_2 ]\!]^{[x_1\to a][x_1\to b]})$$
$$=P^A(b,v(x_2))$$
$$=b<v(x_2).$$
When I have arrived at this step I don't really know if I should say it's true or false. in (a) and (b) it was obvious since I had $\forall x_1\exists x_2(...)$ but i haven't said anything about the existence of $x_2$ in this particular case, what is $v(x_2)$ in this case (which feels kinda weird to me)? Is it just an arbitrary valuation of the natural numbers, that is, that I can just say this is true? Same goes for (d) then I get $v(x_1)<v(x_2)$ is this also true?  It was easier in (a) since I had "for all $a\in |A|$ there is some $b\in |A|$ such that $a<b$. If I haven't said that there exists an $x_2$ with this property nor have I said for all $x_2$ how can I then draw a conclusion?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using subtraction from integers to make a linear line gradient I've been hacking away at this code trying to get this Parametric Line to make a gradient from Magenta to Cyan based upon the length of the line (so it doesn't get cut off by a short line, or happen too soon on a longer line) I'm trying to figure out the formula to find what I'd be subtracting, but I can't seem to figure it out, any ideas?
void ParametricLine(unsigned int _X1, unsigned int _Y1,
                unsigned int _X2, unsigned int _Y2)
{

    unsigned int lengthX;
    unsigned int lengthY;

    lengthX = abs((int)_X2 - (int)_X1);
    lengthY = abs((int)_Y2 - (int)_Y1);

    int longest;
    if (lengthX > lengthY)
    {
        longest = lengthX;
    }
    else
    {
        longest = lengthY;
    }

    unsigned int color = 16711935; //magenta is green 0, others 255
    unsigned int magenta = 16711935; //magenta is green 0, others 255

    unsigned int cyan = 65535;  //cyan is red = 0, G & B are 255
    //all 255 = 16777215

    unsigned int colorsubtract = (magenta - cyan)/longest;

    //MAGENTA: R: 255, G: 0,   B: 255
    //CYAN:    R:0,    G: 255, B: 255

    for (int i = 0; i < longest; i++)
    {
        float Ratio = (float)i / longest;

        unsigned int CurrY = LERP(_Y1, _Y2, Ratio);
        unsigned int CurrX = LERP(_X1, _X2, Ratio);
        /*color = LERP(16711935, 65535, longest/65535);*/
        if (color > cyan)
            color = color - colorsubtract;
        else if (color < cyan)
            color = cyan;

        //interpolate from magenta to cyan
        raster[Position(CurrX, floor(CurrY + 0.5))] = color;
    }
    raster[Position(_X1, _Y1)] = 16777215;
    raster[Position(_X2, _Y2)] = 16777215;
}

edit: here's the Lerp function for those asking-
unsigned int LERP(unsigned int _startval, unsigned int _endval, float _ratio){
return (((int)_endval - (int)_startval) * _ratio + (int)_startval);}

A: You're doing terrible things in your code. If you want to rasterize the line, the easiest way would be to use DDA algorithm (sometimes called Bresenham algorithm), which does not require floating point arithmetic and does not draw the same points several times.
Here's another explanation of the same concept.
And here's yet another one with the C code included.
And once you read all the mentioned pages, treat the colour as one of the coordinates and apply the exactly same DDA algorithm for the colour as well.


text:
Q: Definable sets, substructures and unions Ok so my question is as follows;
Let A be a substructure of B and S $\subset$ B be a definable set define by a universal formula $\phi(x)$, I need to show that in A $\phi$ defines $A \cap S$ My thought process was as follows, firsly we can define S as $S=\{ b \in B: B \models \phi(b) \}$ if i can show this is a substructure of B and show that $A \cap S$ is a substructure of B (which i think would be easy once i know S is a substructure of B, i can easily deduce what i am trying to prove using the fact (an exercise i just proved) that if a universal formula models B it models all substructures of B.
Any help or hints?


text:
Q: How can I convert List to unique id
Possible Duplicate:
Good GetHashCode() override for List of Foo objects

I have List of Objects, Object has ID, FileName, Status(Enumerator), DateStamp, UserId.
Using Linq I filter List using UserId and send it to Web App.
I need to get some kind of Unique Id for filtered result and compare it next time to detect changes for current user. If new Object added for current user or property of existing object is changed Unique Id should be different.
I have tried to use code below to get Hash Code but hash code is different for every myList object even objects and object properties are the same. Any ideas please?
myList= _queueList.GetItems(p => p.User.Id == userId)
                  .OrderByDescending(p => p.DateStamp)
                  .ToList();

myList.GetHashCode()

A: var uniqueId = string.Join(",", myList.Select(x=>x.Id.ToString()).ToArray());

If the string is very long, you could generate an md5 or sha1 and return that instead.

A: You could leverage builtin cryptography like this:
string hash = Convert.ToBase64String(
    new SHA1CryptoServiceProvider().ComputeHash(
        Encoding.UTF8.GetBytes(
            string.Join(":", myList.Select(obj => obj.Id.ToString()).ToArray()
        )));

I put Convert.ToBase64String() to make it web-friendly (beware: the resulting string might become quite long if you have many records!)


text:
Q: Did I do PDO right? First timer at prepared statements Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
try{
$connection = new PDO('mysql:host=supertopsecret;dbname=supertopsecret;charset=utf8mb4',
'supertopsecret', 'supertopsecret');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

//Query 1 - Insert Provider's Name
//if(isset($_POST['submit'])){ delete this? do I still use this? halp
$stmt1 = $connection->prepare("INSERT INTO
`providers`(provider_first_name,provider_last_name,date_added)
VALUES (:providerfirstname, :providerlastname, NOW())");

//bind parameters:
  $stmt1->bindParam(':providerfirstname', $providerfirstname);
  $stmt1->bindParam(':providerlastname', $providerlastname);

//insert row
  $providerfirstname = $_POST['providerfirstname'];
  $providerlastname = $_POST['providerlastname'];

  $stmt1->execute();

//Query 2 - Insert Practices
$prov_id = $connection->lastInsertId();
  /*Get all values of practice_name[]:*/
  $practicename = $_POST['practice_name'];
  for ($i = 0; $i < count($practicename); $i++) {
      if ($practicename[$i]) {
          $practice_name_data = $practicename[$i];

      $stmt2 = $connection->prepare("INSERT INTO
practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)");

      $stmt2->bindParam(':prov_id', $prov_id);
      $stmt2->bindParam(':practice_name', $practice_name_data);

      $stmt2->execute();
     }
  }

echo '

Thank you! Your provider has
successfully been submitted to the database!

';

} catch(PDOException $e){
echo "Sorry, there was an problem submitting your provider to the
database. Please try again or copy and paste the error code below to
the \"Report a Problem\" page and we will try to correct the problem.

 Error: " . $e->getMessage();
die();
}
$connection = null;

A: You should use prepared statements instead of escaping yourself, see How can I prevent SQL injection in PHP?.  But it's probably '$practicename[$i]'.  It would be '{$practicename[$i]}', but easier:
foreach($practicename as $value){
   if($value!=""){
       $value =  mysqli_real_escape_string($connection, $value);
       $query2 = mysqli_query($connection,
       "INSERT INTO `practices`(prov_id,practice_name)
        VALUES ('$prov_id','$value')");
   }
}

But again, abandon this and use Prepared Statements!

A: Check this it may help you. Use PDO for insert.
$connection = new PDO("mysql:host=xxxx;dbname=xxxx;", "xxxx", "xxxx"); //database connection

for ($i = 0; $i < count($practicename); $i++) {
    if ($practicename[$i]) {
        $practice_name_data = $practicename[$i];

        $statement = $connection->prepare('INSERT INTO practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)');

        $statement->bindParam(':prov_id', $prov_id);
        $statement->bindParam(':practice_name', $practice_name_data);
        // etc.

        $statement->execute();
    }
}


text:
Q: MySQL partition is full I've just installed MySQL (with Apache) on my new Raspberry Pi. When I tried starting it I immediately got this error:
df: `/var/lib/mysql/.': No such file or directory
df: no file systems processed
[....] /etc/init.d/mysql: ERROR: The partition with /var/lib/mysql is too full! [FA failed!

The RPI is having a 8GB SD Card.

Output of du -sch /:

UPDATE 19:30 13/18
I've also found these errors in my PHP error log
PHP Warning:  Unknown: write failed: No space left on device (28) in Unknown on line 0
PHP Warning:  Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php5) in Unknown on line 0

My SD card isn't full so I don't get the problem?

A: Your / (where /var/ is appended) is full: 100%. On my rasp I'm running nginx with sqlite because apache and mysql use way more resources in general.
It doesn't look like 8GB in total, according to your df output.
Anyways, I guess your log files consume the diskspace.
You can use the following to find the folder which uses much:
du -sch /*

and:
du -sch /var/*


text:
Q: How does unplugging battery and RAM (then reconnecting) fix Acer "black screen of death"? How does unplugging battery and RAM fix Acer "black screen of death"?
Recently experienced issue where, when restarting my laptop (Acer Helios 300, 2018), I saw nothing but a black screen while the keyboard still lit up. Unplugging the power cable and doing a power reset (#1) helped temporarily, but on the next restart test, just showed the black screen again.
What ultimately helped was using the sources here:

*

*https://community.acer.com/en/discussion/comment/832619/#Comment_832619

*https://recoverit.wondershare.com/computer-problems/acer-laptop-black-screen.html (#8)

*https://forums.tomsguide.com/faq/how-to-fix-black-screen-in-acer-laptops.188316/

*https://www.youtube.com/watch?v=2LBduIAF12M
which lead me to...

*

*Turn off and unplug the laptop

*Open up the underside

*Unplug the battery

*Remove the RAM sticks

*Wait 15min

*Reconnect everything back in (RAM + battery)

*Plug laptop back in

*Turn laptop back on successfully

What does this do exactly?
Why does this happen in the first place?
Is this something that happens to all Acers or just the Helios 300?
* Note that I rarely turn my computer off (and that this black screen issue has happened on the laptop 3 times since buying it)


text:
Q: PHP Request To Fetch Data From WSO2 Data Services Server I have successfully set up the WSO2 Data Services Server and have created to some procedures which fetch the data as XML. I can see them in the DSS admin panel. In order to do that I have completed DSS wizard which allows me to add new data sources and created some procedures as well. That's fine.
What I want to know is how can I connect PHP with the DDS ? In other words How can I make a PHP request so that data are fetch to my PHP script from the DSS ? Is it possible to data to be fetched as JSON ? If so how ?

A: This simple script might give you an idea how to connect to your server:
<?php
$client = new SoapClient("http://*yourDSserver*:*yourPort*/services/yourDSservice?wsdl",array('trace' => 1));

try {
  $info = $client->__soapCall("op_name",array(*--your request data goes here--*));

} catch (SoapFault $fault) {
  print($fault);
}

print_r($info);

change yourDSserver, yourDSport,yourDSservice, as well as op_name to values suitable for your installation.
A few more lines that might be usefull for debugging:
echo "\nRequest:\n" . $client->__getLastRequest() . "\n";
echo "\nResponse:\n" . $client->__getLastResponse() . "\n";

A: To access the data service from PHP, there are many approaches. The first one would be to use a SOAP client of PHP to access the data services. The data service endpoint URLs are mentioned in the service dashboard of the service, for you to use as the SOAP endpoint. Also, if you want to access it RESTfully, you can create data service "resources", where you can use access the created HTTP paths, as configured. JSON is also supported, and you can use this as a reference on how to do that. Also, basically if that approach is not suitable, you can use WSO2 ESB to mediate the JSON requests to remove the XML namespaces and so on and get the JSON payload in the way you want. A sample on how to do that is shown here.
Cheers,
Anjana.


text:
Q: Cannot understand error from ansible parted module I am trying to create a partition on a device, check what was created and use that information for further steps, like setting a filesystem on the partition. But I am getting the error below and I don't understand what I am missing.
Here are the relevant tasks
  - name: Fetch partitions info "{{ item.0.device }}"
    parted: device={{ item.0.device }} unit=MiB
    register: nvme2n1_info
    loop:  "{{ local_volume_mount_disks|subelements('partitions') }}"
  - debug:
      var: nvme2n1_info.partitions

  - name: Create partitions "{{ item.0.device }}"
    parted:
      device: "{{ item.0.device }}"
      number: "{{ item.1.number }}"
      state: present
      label: gpt
      part_start: "{{ item.1.start }}"
      part_end: "{{ item.1.end }}"
    loop:  "{{ local_volume_mount_disks|subelements('partitions') }}"
  - parted: device= "{{ item.0.device }}" unit=GiB
    register: nvme2n1_info
    loop:  "{{ local_volume_mount_disks|subelements('partitions') }}"
  - debug:
      var: nvme2n1_info.partitions

The above tasks are using the following variables
# Create partition and mount filesystems for service storage
local_volume_mount_enabled: true
local_volume_mount_root_directory: /local-volumes

local_volume_mount_disks:
  - device: /dev/nvme2n1
    partitions:
      - number: 1
        start: 1GiB
        end: 800GiB
        storage_class: ssd-wkr-node-services

Output:
   TASK [local_volume_mount : Fetch partitions info "{{ item.0.device }}"] ********
   Friday 19 March 2021  18:45:41 +0000 (0:00:00.025)       0:00:22.876 **********
   ok: [node1] => (item=[{'device': '/dev/nvme2n1', 'partitions': [{'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}]}, {'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}])

   TASK [local_volume_mount : debug] **********************************************
   Friday 19 March 2021  18:45:41 +0000 (0:00:00.268)       0:00:23.144 **********
   ok: [node1] => {
       "nvme2n1_info.partitions": "VARIABLE IS NOT DEFINED!"
   }

   TASK [local_volume_mount : Create partitions "{{ item.0.device }}"] ************
   Friday 19 March 2021  18:45:41 +0000 (0:00:00.027)       0:00:23.171 **********
   ok: [node1] => (item=[{'device': '/dev/nvme2n1', 'partitions': [{'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}]}, {'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}])

   TASK [local_volume_mount : parted] *********************************************
   Friday 19 March 2021  18:45:41 +0000 (0:00:00.242)       0:00:23.414 **********
  failed: [node1] (item=[{'device': '/dev/nvme2n1', 'partitions': [{'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}]}, {'number': 1, 'start': '1GiB', 'end': '800GiB', 'storage_class': 'ssd-wkr-node-services'}]) => {"ansible_loop_var": "item", "changed": false, "err": "Error: Could not stat device unit - No such file or directory.\n", "item": [{"device": "/dev/nvme2n1", "partitions": [{"end": "800GiB", "number": 1, "start": "1GiB", "storage_class": "ssd-wkr-node-services"}]}, {"end": "800GiB", "number": 1, "start": "1GiB", "storage_class": "ssd-wkr-node-services"}], "msg": "Error while getting device information with parted script: '/sbin/parted -s -m  -- unit 'GiB' print'", "out": "", "rc": 1}

A: You are looping, thus it is not nvme2n1_info['partitions'] but nvme2n1_info.results list.
---

- name: test
  hosts: localhost
  become: true
  tasks:
    - parted:
        device: /dev/{{ item }}
        unit: MiB
      register: out
      loop:
        - sda
    - debug:
        msg: "{{ out.results | type_debug }}"


text:
Q: Why aren't my global variables seeming to change? I am a trying to create a very simplistic RPG and have defined several global variables at the top of my program. Within the function, mage, I have created an equation to calculate the damage of an ability using existing global variables whose values should have been updated according to the function. However, within the function, monsterFight, I call ability1 and every time it takes away nothing. I.e., it seems to take away a value of 0. I am not sure what I am doing wrong.
#include <iostream>
#include <string>
using namespace std;

int XP;
int HP;
int LVL;
int DMG;

string ability1Name;
float ability1;

void mage() {
    HP = 10;
    DMG = 5;
    ability1Name = "Magic Bolt";
    ability1 = (DMG * 1.1) * (LVL * 1.25);
}

void warrior() {
    HP = 12;
    DMG = 4;
}

void paladin() {
    HP = 15;
    DMG = 3;
}

void monsterStart(string monsterName, int level, int health) {
    cout << "*************" << endl;
    cout << "Name: " << monsterName << endl;
    cout << "Level: " << level << endl;
    cout << "HP: " << health << endl;
    cout << "*************" << endl;
}

void monsterFight(int health) {
    while (true) {
        cout << "Select an ability: " << endl << "A. " << ability1Name << endl;
        char abilitySelect;
        cin >> abilitySelect;
        if (abilitySelect == 'A') {
            health - ability1;
            cout << "Monster's HP: " << health << endl;
        }
    }
}

int main() {

    int LVL = 1;

    cout << "Welcome to the RPG!" << endl;
    cout << "Please select a class: " << endl << "A. Mage\nB. Warrior\nC. Paladin" << endl;

    char SL1;

    cin >> SL1;

    if (SL1 == 'A') {
        mage();
        cout << "You chose Mage!" << endl;
    }
    else if (SL1 == 'B') {
        warrior();
        cout << "You chose Warrior!" << endl;
    }
    else if (SL1 == 'C') {
        paladin();
        cout << "You chose Paladin!" << endl;
    }

    cout << "Let us have a tutorial by you defeating a practice monster!" << endl;
    monsterStart("Dummy", 1, 10);
    monsterFight(10);

    return 0;
}

A: It's not necessarily your usage of global variables, although as @NathanOliver pointed out, this is a bad practice.
You need to remove  int from int LVL = 1; in main(). Your global value remains 0 in the original code, while you create a new locally scoped LVL that is 1. However, your functions will only see the global LVL, not the local one.

A: At the beginning of main you are accidentally re-declaring LVL not assigning to your global. The global LVL is likely being initialized to 0 by the debugger making your damage calculation have a multiply by zero.
int LVL;
int main() {
    LVL = 1; //assigning to global
    int LVL = 1;//declaring a 'shadow' variable
}

A: You are re-declaring LVL in your main function, thus in your mage function the global LVL variable is 0.  Remove the int from the line
int LVL = 1;

so it becomes
LVL = 1;

so to not re-declare a local version of the variable.


text:
Q: LunaCryptokiException: function 'CrystokiConnect failed' returns 0x0 as non root user I have used Luna SA with SDK for generating keypairs.
When am trying to list the keystore (as non root user) its throwing below exception. If I try as root user, it does list and works fine.
I have given read write permission to non root user.
keytool error: java.security.KeyStoreException: LUNA not found
java.security.KeyStoreException: LUNA not found

Caused by: com.safenetinc.luna.LunaCryptokiException: function 'CrystokiConnect failed' returns 0x0
        at com.safenetinc.luna.LunaCryptokiException.ThrowNew(LunaCryptokiException.java:)
        at com.safenetinc.luna.LunaAPI.Initialize(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

Any help, how can I list key stores as a non root user?

A: I had the same issue and it got resolved once we provided proper permission to /usr/safenet/lunaclient/
chmod -R 777  /usr/safenet/lunaclient/

A: From their official guide:

To allow non-root users or applications access your attached HSMs and partitions, assign the users to the hsmusers group. The users you assign to the hsmusers group must exist on the client workstation. Users you add to the hsmusers group are able to access your attached HSMs and partitions. Users who are not part of the hsmusers group are not able to access your attached HSMs and partitions.

sudo gpasswd --add <username> hsmusers

A: parent folder, where certificates resides to connect hsm for handshake and luna bin fodler should have read and execure permission for non root user.
Which I missed!

A: I was having the same issue and I also had to fix the permissions of the file /etc/Chrystoki.conf.

A: I had the same issue even after providing proper permission to /usr/safenet/lunaclient/. Got it resolved after giving 755 permission to /usr/safenet/ folder
chmod -R 755  /usr/safenet/


text:
Q: Add pdf table in PDF Document I am generating a simple pdf file with a table in it.When I add some phrase in the document it works fine but also I am Adding a table inside this document but the table is not getting added in the document.Can anyone tell me what mistake I am doing here ? Thanks in Advance.
Here is my Code for generating pdf.Everything is fine except pdf table
public Document GetPDFparams(Document disclaimer)
    {
        StringBuilder Content = new StringBuilder();
        Content.Append("Testing");
        Paragraph NullContent = new Paragraph(Content.ToString(), FontFactory.GetFont(FontFactory.TIMES_ROMAN, font_size, Font.NORMAL));
        disclaimer.Add(NullContent);
        PdfPTable tableh = new PdfPTable(6);
        tableh.WidthPercentage = 100;
        tableh.SetTotalWidth(new float[] { 300f, 300f, 300f, 300f,300f,300f });
        tableh.HorizontalAlignment = Element.ALIGN_CENTER;

        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/ORIXLOGO.png"));
        //img.ScaleToFit(100, 40);
        PdfPCell LogoCell = new PdfPCell(img);
        LogoCell.HorizontalAlignment = Element.ALIGN_RIGHT;
        LogoCell.VerticalAlignment = Element.ALIGN_BOTTOM;
        LogoCell.Colspan = 2;
        LogoCell.Padding = 20;
        LogoCell.Border = 0;
        LogoCell.Indent = 0;

        tableh.AddCell(LogoCell);

        Phrase LogoText = new Phrase("abc", FontFactory.GetFont(FontFactory.TIMES_BOLD, font_size));
        PdfPCell LogoTextCell = new PdfPCell(LogoText);
        LogoTextCell.HorizontalAlignment = Element.ALIGN_LEFT;
        LogoTextCell.VerticalAlignment = Element.ALIGN_LEFT;
        LogoTextCell.Border = Rectangle.NO_BORDER;
        LogoTextCell.PaddingTop = 15;
        LogoTextCell.PaddingBottom = 5;
        LogoTextCell.PaddingLeft = 5;
        LogoTextCell.PaddingRight = 5;
        tableh.AddCell(LogoTextCell);

        disclaimer.Add(tableh);
        return disclaimer;
    }

A: Finally I got the solution.The problem was tha table has 6 columns per row and I was testing after adding only 3 columns, so After adding all 6 columns for a row table get added :).
Here is my Code :
 public Document GetPDFparams(Document disclaimer)
    {
        StringBuilder Content = new StringBuilder();
        Content.Append("Testing");
        Paragraph NullContent = new Paragraph(Content.ToString(), FontFactory.GetFont(FontFactory.TIMES_ROMAN, font_size, Font.NORMAL));
        disclaimer.Add(NullContent);
        PdfPTable tableh = new PdfPTable(6);
        tableh.WidthPercentage = 100;
        tableh.SetTotalWidth(new float[] { 30f, 30f, 30f, 30f,30f,30f });
        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/ORIXLOGO.png"));
        //img.ScaleToFit(100, 40);
        PdfPCell LogoCell = new PdfPCell(img);
        LogoCell.HorizontalAlignment = Element.ALIGN_RIGHT;
        LogoCell.VerticalAlignment = Element.ALIGN_BOTTOM;
        LogoCell.Colspan = 2;
        LogoCell.Padding = 20;
        LogoCell.Border = 0;
        //LogoCell.Indent = 0;

        tableh.AddCell(LogoCell);

        Phrase LogoText = new Phrase("abc", FontFactory.GetFont(FontFactory.TIMES_BOLD, font_size));
        PdfPCell LogoTextCell = new PdfPCell(LogoText);
        LogoTextCell.HorizontalAlignment = Element.ALIGN_LEFT;
        LogoTextCell.VerticalAlignment = Element.ALIGN_LEFT;
        LogoTextCell.Border = Rectangle.NO_BORDER;
        tableh.AddCell(LogoTextCell);
        tableh.AddCell(LogoTextCell);
        tableh.AddCell(LogoTextCell);
        tableh.AddCell(LogoTextCell);

        disclaimer.Add(tableh);
        return disclaimer;
    }


text:
Q: Unable to deserialize an encrypted array in c# The following code in my program serializes, encrypts and writes the byte array to disk.  From the looks of it, the encryption works fine.  The issue arises when the program decrypts and then deserializes the file.
Visual Studio displays the following error:
'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll
Additional information: There was an error deserializing the object of type Test.Store. The data at the root level is invalid.
I've been stuck on this one for two days, so any help would be greatly appreciated!
The following code has been trimmed down from its original form:
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;

namespace Test
{
    public class K
    {
        #region Non-Public Data Members

        private string _n = string.Empty;
        private string _u = string.Empty;
        private string _p = string.Empty;
        private string _u2 = null;
        private string _n2 = string.Empty;

        public K()
        {

        }
        public string T
        {
            get { return _n; }
            set { _n = value; }
        }

        public string U
        {
            get { return _u; }
            set { _u = value; }
        }

        public string P
        {
            get { return _p; }
            set { _p = value; }
        }

        public string U2
        {
            get { return _u2; }
            set { _u2 = value; }
        }

        public string N2
        {
            get { return _n2; }
            set { _n2 = value; }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            //stuff
            return sb.ToString();
        }
        #endregion
    }
    public class Group
    {
        private string _text = string.Empty;
        private int _imageIndex = 0;

        private List<K> _credentials = new List<K>();

        public Group()
        {
        }

        public Group(string text, int imageIndex)
        {
            _text = text;
            _imageIndex = imageIndex;
        }

        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        public int ImageIndex
        {
            get { return _imageIndex; }
            set { _imageIndex = value; }
        }

        public List<K> Ks
        {
            get { return _credentials; }
            set { _credentials = value; }
        }

        public override string ToString()
        {
            return Text;
        }

    }
    public class Store
    {
        private List<Group> _groups = new List<Group>();
        private string _docname = string.Empty;
        private bool _dirtyBit = false;

        public bool DirtyBit
        {
            get { return _dirtyBit; }
            set { _dirtyBit = value; }
        }

        public List<Group> Groups
        {
            get { return _groups; }
            set { _groups = value; }
        }

        public string DocName
        {
            get { return _docname; }
            set { _docname = value; }
        }

    }

    public class Crypto
    {
        public static string secretKey = "abcdefgh";
        [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
        public static extern bool ZeroMemory(ref string Destination, int Length);
        static string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        public static byte[] PerformCrypto(ICryptoTransform cryptoTransform, byte[] data)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(data, 0, data.Length);
                    cryptoStream.FlushFinalBlock();
                    return memoryStream.ToArray();
                }
            }
        }
        public static byte[] Decrypt(byte[] cipherTextBytes)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
            using (var decryptor = DES.CreateDecryptor(DES.Key, DES.IV))
            {
                return PerformCrypto(decryptor, cipherTextBytes);
            }
        }

        public static byte[] Encrypt(byte[] plainTextBytes)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
            using (var encryptor = DES.CreateEncryptor(DES.Key, DES.IV))
            {
                return PerformCrypto(encryptor, plainTextBytes);
            }
        }
    }

    public static class StoreMgr
    {
        private static Store _doc = new Store();

        public static void FileSaveAs(string fn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(Store));
                serializer.WriteObject(ms, _doc);
                byte[] byteArrayInput = ms.GetBuffer();
                byte[] encryptedBuffer = Crypto.Encrypt(byteArrayInput);
                File.WriteAllBytes(fn, encryptedBuffer);
            }
        }

        public static void OpenFile(string fn)
        {
                StoreMgr._doc = new Store();
                using (MemoryStream ms = new MemoryStream(Crypto.Decrypt(File.ReadAllBytes(fn))))
            {
                    DataContractSerializer deserializer = new DataContractSerializer(typeof(Store));
                    StoreMgr._doc = (Store)new DataContractSerializer(typeof(Store)).ReadObject(ms);
                }
            }
        }
    }

I've been stuck on this for quite some time. Any help is greatly appreciated!

A: If you configure System.Diagnostics.XmlWriterTraceListener in your web.config, you may find more helpful information in *.svclog

A: The issue was in the FileSaveAs method.  byte[] byteArrayInput = ms.GetBuffer() was returning unused bytes.  After switching it to byte[] byteArrayInput = ms.ToArray() program ran fine.  Thanks for everyone's help.


text:
Q: Datagrid in android studio? are there any datagrids in android studio for handling database tables or do you have to create your own?
A bit like the one you have in visual studio

A: Yes,there is. It is called GridView: https://developer.android.com/guide/topics/ui/layout/gridview.html


text:
Q: Package "acro": Displaying umlaut in PDF bookmark for acronyms list MWE:
% !TeX program = xelatex

\documentclass[ngerman,]{scrreprt}

\usepackage{babel}
\usepackage{acro}
\usepackage{hyperref}

\begin{document}

    \printacronyms

\end{document}

The PDF bookmark for the list of acronyms reads "Abkurzungen" instead of "Abkürzungen". Is there any way to change this? Umlaute in other sections are displayed correctly.

A: With pdflatex it is not really possible. acro must be changed here. With xelatex/lualatex you can reset the name:
\documentclass[ngerman]{scrreprt}
\usepackage{babel}
\usepackage{acro}
\usepackage{hyperref}

\def\blub{Abkürzung}

\DeclareAcroTranslation {list-name}
  {
    German     = Abkürzung
  }

\begin{document}

 \printacronyms

\end{document}


text:
Q: align text and images inside divs side by side So I've made this ul with a list of li in. In each li, are there some div with text and images in. I have a problem where my text and images aren't in a line anymore, and I can't seem to fix it.
Just to show my problem I've set style="width: 100px;", because I'm trying to get something like this, even though this is on:

/* Weather icon on dashboard */

.element_weather {
    min-height: 30px !important;
    min-width: 30px !important;
}

.container_weather {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

.elements_weather {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.white {
    fill: #edf8ff
}

.gray {
    fill: #cecece
}

.yellow {
    fill: #fabb33
}

.blue {
    fill: #83bfff
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

               test - 12345

                     <svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44.9 44.9" style="enable-background:new 0 0 44.9 44.9;" xml:space="preserve" height="25px" width="25px">
                        <g id="Sun">
                           <circle id="XMLID_61_" class="yellow" cx="22.4" cy="22.6" r="11"/>
                           <g>
                              <path id="XMLID_60_" class="yellow" d="M22.6,8.1h-0.3c-0.3,0-0.6-0.3-0.6-0.6v-7c0-0.3,0.3-0.6,0.6-0.6l0.3,0c0.3,0,0.6,0.3,0.6,0.6 v7C23.2,7.8,22.9,8.1,22.6,8.1z"/>
                              <path id="XMLID_59_" class="yellow" d="M22.6,36.8h-0.3c-0.3,0-0.6,0.3-0.6,0.6v7c0,0.3,0.3,0.6,0.6,0.6h0.3c0.3,0,0.6-0.3,0.6-0.6v-7 C23.2,37,22.9,36.8,22.6,36.8z"/>
                              <path id="XMLID_58_" class="yellow" d="M8.1,22.3v0.3c0,0.3-0.3,0.6-0.6,0.6h-7c-0.3,0-0.6-0.3-0.6-0.6l0-0.3c0-0.3,0.3-0.6,0.6-0.6h7 C7.8,21.7,8.1,21.9,8.1,22.3z"/>
                              <path id="XMLID_57_" class="yellow" d="M36.8,22.3v0.3c0,0.3,0.3,0.6,0.6,0.6h7c0.3,0,0.6-0.3,0.6-0.6v-0.3c0-0.3-0.3-0.6-0.6-0.6h-7 C37,21.7,36.8,21.9,36.8,22.3z"/>
                              <path id="XMLID_56_" class="yellow" d="M11.4,31.6l0.2,0.3c0.2,0.2,0.2,0.6-0.1,0.8l-5.3,4.5c-0.2,0.2-0.6,0.2-0.8-0.1l-0.2-0.3 c-0.2-0.2-0.2-0.6,0.1-0.8l5.3-4.5C10.9,31.4,11.2,31.4,11.4,31.6z"/>
                              <path id="XMLID_55_" class="yellow" d="M33.2,13l0.2,0.3c0.2,0.2,0.6,0.3,0.8,0.1l5.3-4.5c0.2-0.2,0.3-0.6,0.1-0.8l-0.2-0.3 c-0.2-0.2-0.6-0.3-0.8-0.1l-5.3,4.5C33,12.4,33,12.7,33.2,13z"/>
                              <path id="XMLID_54_" class="yellow" d="M11.4,13.2l0.2-0.3c0.2-0.2,0.2-0.6-0.1-0.8L6.3,7.6C6.1,7.4,5.7,7.5,5.5,7.7L5.3,7.9 C5.1,8.2,5.1,8.5,5.4,8.7l5.3,4.5C10.9,13.5,11.2,13.5,11.4,13.2z"/>
                              <path id="XMLID_53_" class="yellow" d="M33.2,31.9l0.2-0.3c0.2-0.2,0.6-0.3,0.8-0.1l5.3,4.5c0.2,0.2,0.3,0.6,0.1,0.8l-0.2,0.3 c-0.2,0.2-0.6,0.3-0.8,0.1l-5.3-4.5C33,32.5,33,32.1,33.2,31.9z"/>
                              <animate attributeType="CSS"
                                 attributeName="opacity"
                                 attributeType="XML"
                                 dur="0.5s"
                                 keyTimes="0;0.5;1"
                                 repeatCount="indefinite"
                                 values="1;0.6;1"
                                 calcMode="linear"/>
                           </g>
                        </g>
                     </svg>

Edit
When my li column is getting two small in width, then the icons row jumps under, and it shouldn't.

A: Currently, your .row gets applied a flex-wrap:wrap that comes from bootstrap.css.
You can overwrite it with flex-wrap: nowrap :

/* Weather icon on dashboard */

.element_weather {
    min-height: 30px !important;
    min-width: 30px !important;
}

.container_weather {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

.elements_weather {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.white {
    fill: #edf8ff
}

.gray {
    fill: #cecece
}

.yellow {
    fill: #fabb33
}

.blue {
    fill: #83bfff
}

.row {
    border : blue dashed 1px;
    flex-wrap : nowrap!important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

               test - 12345

                     <svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44.9 44.9" style="enable-background:new 0 0 44.9 44.9;" xml:space="preserve" height="25px" width="25px">
                        <g id="Sun">
                           <circle id="XMLID_61_" class="yellow" cx="22.4" cy="22.6" r="11"/>
                           <g>
                              <path id="XMLID_60_" class="yellow" d="M22.6,8.1h-0.3c-0.3,0-0.6-0.3-0.6-0.6v-7c0-0.3,0.3-0.6,0.6-0.6l0.3,0c0.3,0,0.6,0.3,0.6,0.6 v7C23.2,7.8,22.9,8.1,22.6,8.1z"/>
                              <path id="XMLID_59_" class="yellow" d="M22.6,36.8h-0.3c-0.3,0-0.6,0.3-0.6,0.6v7c0,0.3,0.3,0.6,0.6,0.6h0.3c0.3,0,0.6-0.3,0.6-0.6v-7 C23.2,37,22.9,36.8,22.6,36.8z"/>
                              <path id="XMLID_58_" class="yellow" d="M8.1,22.3v0.3c0,0.3-0.3,0.6-0.6,0.6h-7c-0.3,0-0.6-0.3-0.6-0.6l0-0.3c0-0.3,0.3-0.6,0.6-0.6h7 C7.8,21.7,8.1,21.9,8.1,22.3z"/>
                              <path id="XMLID_57_" class="yellow" d="M36.8,22.3v0.3c0,0.3,0.3,0.6,0.6,0.6h7c0.3,0,0.6-0.3,0.6-0.6v-0.3c0-0.3-0.3-0.6-0.6-0.6h-7 C37,21.7,36.8,21.9,36.8,22.3z"/>
                              <path id="XMLID_56_" class="yellow" d="M11.4,31.6l0.2,0.3c0.2,0.2,0.2,0.6-0.1,0.8l-5.3,4.5c-0.2,0.2-0.6,0.2-0.8-0.1l-0.2-0.3 c-0.2-0.2-0.2-0.6,0.1-0.8l5.3-4.5C10.9,31.4,11.2,31.4,11.4,31.6z"/>
                              <path id="XMLID_55_" class="yellow" d="M33.2,13l0.2,0.3c0.2,0.2,0.6,0.3,0.8,0.1l5.3-4.5c0.2-0.2,0.3-0.6,0.1-0.8l-0.2-0.3 c-0.2-0.2-0.6-0.3-0.8-0.1l-5.3,4.5C33,12.4,33,12.7,33.2,13z"/>
                              <path id="XMLID_54_" class="yellow" d="M11.4,13.2l0.2-0.3c0.2-0.2,0.2-0.6-0.1-0.8L6.3,7.6C6.1,7.4,5.7,7.5,5.5,7.7L5.3,7.9 C5.1,8.2,5.1,8.5,5.4,8.7l5.3,4.5C10.9,13.5,11.2,13.5,11.4,13.2z"/>
                              <path id="XMLID_53_" class="yellow" d="M33.2,31.9l0.2-0.3c0.2-0.2,0.6-0.3,0.8-0.1l5.3,4.5c0.2,0.2,0.3,0.6,0.1,0.8l-0.2,0.3 c-0.2,0.2-0.6,0.3-0.8,0.1l-5.3-4.5C33,32.5,33,32.1,33.2,31.9z"/>
                              <animate attributeType="CSS"
                                 attributeName="opacity"
                                 attributeType="XML"
                                 dur="0.5s"
                                 keyTimes="0;0.5;1"
                                 repeatCount="indefinite"
                                 values="1;0.6;1"
                                 calcMode="linear"/>
                           </g>
                        </g>
                     </svg>

A: row changed to col, and d-flex added

/* Weather icon on dashboard */

.element_weather {
    min-height: 30px !important;
    min-width: 30px !important;
}

.container_weather {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

.elements_weather {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.white {
    fill: #edf8ff
}

.gray {
    fill: #cecece
}

.yellow {
    fill: #fabb33
}

.blue {
    fill: #83bfff
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

               test - 12345

                     <svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44.9 44.9" style="enable-background:new 0 0 44.9 44.9;" xml:space="preserve" height="25px" width="25px">
                        <g id="Sun">
                           <circle id="XMLID_61_" class="yellow" cx="22.4" cy="22.6" r="11"/>
                           <g>
                              <path id="XMLID_60_" class="yellow" d="M22.6,8.1h-0.3c-0.3,0-0.6-0.3-0.6-0.6v-7c0-0.3,0.3-0.6,0.6-0.6l0.3,0c0.3,0,0.6,0.3,0.6,0.6 v7C23.2,7.8,22.9,8.1,22.6,8.1z"/>
                              <path id="XMLID_59_" class="yellow" d="M22.6,36.8h-0.3c-0.3,0-0.6,0.3-0.6,0.6v7c0,0.3,0.3,0.6,0.6,0.6h0.3c0.3,0,0.6-0.3,0.6-0.6v-7 C23.2,37,22.9,36.8,22.6,36.8z"/>
                              <path id="XMLID_58_" class="yellow" d="M8.1,22.3v0.3c0,0.3-0.3,0.6-0.6,0.6h-7c-0.3,0-0.6-0.3-0.6-0.6l0-0.3c0-0.3,0.3-0.6,0.6-0.6h7 C7.8,21.7,8.1,21.9,8.1,22.3z"/>
                              <path id="XMLID_57_" class="yellow" d="M36.8,22.3v0.3c0,0.3,0.3,0.6,0.6,0.6h7c0.3,0,0.6-0.3,0.6-0.6v-0.3c0-0.3-0.3-0.6-0.6-0.6h-7 C37,21.7,36.8,21.9,36.8,22.3z"/>
                              <path id="XMLID_56_" class="yellow" d="M11.4,31.6l0.2,0.3c0.2,0.2,0.2,0.6-0.1,0.8l-5.3,4.5c-0.2,0.2-0.6,0.2-0.8-0.1l-0.2-0.3 c-0.2-0.2-0.2-0.6,0.1-0.8l5.3-4.5C10.9,31.4,11.2,31.4,11.4,31.6z"/>
                              <path id="XMLID_55_" class="yellow" d="M33.2,13l0.2,0.3c0.2,0.2,0.6,0.3,0.8,0.1l5.3-4.5c0.2-0.2,0.3-0.6,0.1-0.8l-0.2-0.3 c-0.2-0.2-0.6-0.3-0.8-0.1l-5.3,4.5C33,12.4,33,12.7,33.2,13z"/>
                              <path id="XMLID_54_" class="yellow" d="M11.4,13.2l0.2-0.3c0.2-0.2,0.2-0.6-0.1-0.8L6.3,7.6C6.1,7.4,5.7,7.5,5.5,7.7L5.3,7.9 C5.1,8.2,5.1,8.5,5.4,8.7l5.3,4.5C10.9,13.5,11.2,13.5,11.4,13.2z"/>
                              <path id="XMLID_53_" class="yellow" d="M33.2,31.9l0.2-0.3c0.2-0.2,0.6-0.3,0.8-0.1l5.3,4.5c0.2,0.2,0.3,0.6,0.1,0.8l-0.2,0.3 c-0.2,0.2-0.6,0.3-0.8,0.1l-5.3-4.5C33,32.5,33,32.1,33.2,31.9z"/>
                              <animate attributeType="CSS"
                                 attributeName="opacity"
                                 attributeType="XML"
                                 dur="0.5s"
                                 keyTimes="0;0.5;1"
                                 repeatCount="indefinite"
                                 values="1;0.6;1"
                                 calcMode="linear"/>
                           </g>
                        </g>
                     </svg>


text:
Q: How to get a random subreddit using praw and python3? I've tried googling and all I could find was how to get a random submission from a specific subreddit, but not a random subreddit. I remember reading about it weeks ago on some website but for the life of me I cannot find out where it was.

A:
random_subreddit(nsfw=False)

Return a random lazy instance of Subreddit.
Parameters: nsfw – Return a random NSFW (not safe for work) subreddit
    (default: False).

Checkout the docs here. Look at the random_subreddit() method.


text:
Q: How to prevent entire user models from leaking up into the jade template I am currently working on the log in portion of my project but I am working with express, passport-local and mongoose. I have a set of routes:
module.exports = function (app) {
    app.get('/', function (req, res) {
        res.render('index', { user : req.user, title : "Home" });
    });

    app.get('/register', function(req, res) {
        res.render('register', { });
    });

    app.post('/register', function(req, res) {
            Athlete.register(new Athlete({
            username: req.param('username'),
            firstName: req.param('firstName'),
            lastName: req.param('lastName'),
            dob: req.param('dob')
        }), req.param('password'), function(err, athlete) {
            if (err) {
                console.log(err);
                return res.render('register');
            }
            res.redirect('/');
        });
    });

    app.get('/login', function(req, res) {
        res.render('login', { user : req.user.username });
    });

    app.post('/login', passport.authenticate('local'), function(req, res) {
        res.redirect('/');
    });

    app.get('/logout', function(req, res) {
        req.session.destroy(function (err) {
            res.redirect('/');
        });
    });};

I am currently able to sign in and sign out no problem and it displays my name as per the jade template using the p= user.firstName jade syntax. This though is burping up a object that contains a salt, hash, as well as the model values. This is clearly a huge security issue and I want to wrap my hear around what is going on between the route and the template. How can I prevent the entire user database object from coming up and which part of my code is causing the miscommunication.

A: First of all your user object won't leak as jade will be rendered on server side until you expose the secret information in your template. So passing extra information won't result in leaking.
Still if you want to restrict the entire user passing into jade, you can add a method in your user schema and call that method while using res.render.
userSchema.methods.getSafeUser = function() {
   var user = this;
   //filter user as per your requirements here.

   return user;

}
Then in your controller, use
res.render('index', { user : req.user.getSafeUser() });


text:
Q: If no current is able to flow through a capacitor what will be the node voltage on the other end of the capacitor opposite the voltage source? I'm working on a simple circuit problem including a capacitor and I am calculating the node voltage Va.
By using KVL, I find that Va is 5V. But how does the 5 volts appear on at Va if it is not connected to the voltage source? Since no current can flow through the capacitor, it is basically an open circuit, but whenever I do KVL, Va is always equal to 5V. Also, say if the voltage source increases from 0V to 5V, how does the node voltage at Va also increase from 0V to 5V? I don't understand how the voltage at Va is always equal to the voltage across the voltage source. Any help/explanation is much appreciated.

A: You may start tracking the voltage from where is grounded, the point set 0 voltage. I copy your figure as follows, and marked some positions for explanation.

The point $A$ is grounded, i.e. $V_A = 0$, and there is no voltage difference between point $B$ and point $A$, therefore $V_B = 0$. The voltage will be increased by $5 V$ for point B and point C, across the voltage source.
Then, since there are no charges in the capacitor, the voltage drop across the capacitor is zero $V_c = \Delta Q / C = 0$. This renders point $D$ has the same voltage as point $C$, i.e. $V_D = V_C = 5 V$.


text:
Q: UnboundLocalError: local variable 'strdate' referenced before assignment When I tried this codes with 3-4 files as a test, it worked fine. But when I ran with 3,000+ files, the error message popped up saying File "C:\Users\dul\Dropbox\Article\ap_final.py", line 51, in extract_data
    combid = matchcomp2 + "," + strdate + "," + matchw + "," + matchcount
UnboundLocalError: local variable 'strdate' referenced before assignment
I searched and it looks like something with global is an issue. I simply do not understand what that means..Please help.
import os,csv,datefinder,re
import numpy as np

os.chdir('C:\Users\dul\Dropbox\Article\parsedarticles')

def matchwho(text_to_match):
    if 'This story was generated by' in text_to_match:
        return('1')
    elif 'This story includes elements generated' in text_to_match:
        return('2')
    elif 'Elements of this story were generated' in text_to_match:
        return('2')
    elif 'Portions of this story were generated' in text_to_match:
        return('2')
    elif 'Parts of this story were generated' in text_to_match:
        return('2')
    elif 'A portion of this story was generated' in text_to_match:
        return('2')
    elif 'This sory was partially generated by' in text_to_match:
        return('2')
    elif 'This story contains elements generated by' in text_to_match:
        return('2')
    elif 'This story includes information generated by' in text_to_match:
        return('2')
    elif 'This story was originally generated by' in text_to_match:
        return('1')
    else:
        return('3')

def extract_data(filename):
    with open(filename, 'r') as file1:
        text1=file1.read()
#locate the date of the article
    matches = list(datefinder.find_dates(text1))
    if len(matches) > 0:
        date=matches[1]
        strdate = str(date)
    else:
        print 'No dates found'

#locate the name of the company2
    matchcomp2 = text1.split(' ', 1)[0]
#count the number of words in the article
    matchcount = re.search(r'(.*) words', text1).group(1).strip()
#determine the article
    matchw =str(matchwho(text1))
#list the returns in a line
    combid = matchcomp2 + "," + strdate + "," + matchw + "," + matchcount
#save in txt format
    with open('outfile.txt', "a+") as outfile:
        outfile.write("\n"+combid)

files = os.listdir("C:\Users\dul\Dropbox\Article\parsedarticles")
for file in files:
    if ".txt" in file:
        extract_data(file)

A: strdate only defined for case len(matches) > 0, but used in any case during assigny to combid.

A: This fails when len(matches) < 0
def extract_data(filename):
...
    if len(matches) > 0:
        date=matches[1]
        strdate = str(date)
    else:
        print 'No dates found'

So if your conditional statement fails, strdate never gets set. However,
combid = matchcomp2 + "," + strdate + "," + matchw + "," + matchcount

is dependent on that being set and assumes it will always be set.
Based on what you want to achieve there is several things you can do. One such example is this.
def extract_data(filename):
...
    if len(matches) > 0:
        date=matches[1]
        strdate = str(date)
    else:
        print 'No dates found in {}'.format(filename)
        strdate = ''

A: Looks like you are assigning strdate only when the len(matches) > 0 predicate is true, try to add a default strdate value either at the beginning or inside else clause to debug if that is the case.
It seems you are trying to call strdate but because the if condition is not true the code doesn't know what strdate is (since it hasnt been assigned yet due to the if statement being false).
That's my guess.


text:
Q: ASP.NET Core MVC 2.2 loses value in model I am developing an MVC application on ASP.NET Core 2.2 platform. I have the following classes :
public class BaseModel
{
    public string ErrorMessage { get; set; }
}
public class LoginModel : BaseModel
{
    public string Username { get; set; }
    public strinh Password { get; set; }
}
public class AccountController
{
    [HttpGet]
    public IActionResult Login()
    {
        LoginModel model = new LoginModel();
        return View(model);
    }
    [HttpPost]
    public IActionResult Login(LoginModel model)
    {
        try
        {
            throw new Exception("Test exception");
        }
        catch(Exception ex)
        {
            model.ErrorMessage = ex.Message;
            return View (model);
        }
    }
}

and my cshtml file is like :
@model MyProject.Models.LoginModel
<script>
 $(document).ready(function () {
    var _err = $('#ErrorMessage').val();
    if (_err != null && _err != '') {
        alert(_err);
    }
});
</script>
<input type="hidden" asp-for="ErrorMessage" />

What I expect is to see the error after posting back to controller. When I debug I see that ErrorMessage property is set in controller, but value in hidden field is empty.

A: It seems that the error was the hidden field was placed inside a form. Placing it out of the form did the trick.

A: You don't need to put ErrorMessage in a hidden field which makes the round trip from client to server. Instead, you can simply use @Model.ErrorMessage anywhere in the view.


text:
Q: Count php ones does not work Hi there can someone help me
I have this code:
@foreach($questions as $question)
      <?php  $correct= $question->correct; ?>
      {{($correct == 1)}}
@endforeach

and it appears this 1 1 1 1 1 I want to count how many ones are there
I tried count($correct ==1) but does not work

A: Use collect to make collection with where and count
$count = collect($questions)->where("correct",1)->count();

A: Try the following:
<?php $count = 0; ?>
@foreach($questions as $question)
    <?php
    $correct = $question->correct;
    if($correct == 1)
    {
        $count++;
    }
    ?>
@endforeach

This creates a new variable $count and increments it, every time $correct is equal to 1

A: You need to check that value equal to 1 and then increment your count:
<?php $count = 0;?>
@foreach($questions as $question)
      @if($question->correct==1)
         <?php $count++;?>
      @endif
@endforeach

A: Try This
 @php $totalCorrect = 0; @endphp
 @foreach($questions as $question)
  @if($question->correct == 1)
   @php $totalCorrect++; @endphp
  @endif
 @endforeach
 {{ $totalCorrect }}

Explaination
create a $totalCorrect variable and assign initial value to 0 then in foreach loop we check that if answer is correct then $totalCorrect variable value will increment with 1 and after foreach loop print counter variable, it will give you total correct answer's count.

A: Try this
@php
    $i==0;
@endphp
@foreach($questions as $question)
    <?php  $correct= $question->correct; ?>
    @php
        $correct == 1;
        $i++;
    @endphp
@endforeach

{{$i}}


text:
Q: Uncaught ReferenceError: acf is not defined on my wordpress site, since I installed the ACF plugin, I am now getting an error:

Uncaught ReferenceError: acf is not defined.

My jQuery has stopped working. Please help


text:
Q: Different precision for masses of moon and earth online The Google search page for "mass of moon" shows a value with nine significant digits of precision.
The corresponding page for "mass of earth" shows a value with only four significant digits.  (The Wikipedia page shows 5 digits.)
Why the vast difference in precision?  Does this have something to do with the earth mass being a "standard unit of mass in astronomy" (as mentioned on the Wikipedia page)?
For the record, I'm not questioning the accuracy of either value, but one would assume that 9 digits of precision implies a great deal of certainty and confidence regarding the accuracy.

A: We don't know the mass of the Moon with that level of accuracy. NASA gives only 4 significant digits. The best estimate of the mass of the Earth I could find is:
$$M_\oplus = (5.9722 \pm 0.0006)\times 10^{24}\;~{\rm kg}$$

Does this have something to do with the earth mass being a "standard unit of mass in astronomy"?

Yes, most likely. Google must have converted the mass of the Moon in $M_\oplus$ to $\rm kg$ without truncating the digits.
An interesting fact is that we actually know the ratio between the mass of the Moon and the mass of the Earth with an incredible precision:
$$M_☽ = (1.23000371 \pm 0.00000004) × 10^{−2}\;M_\oplus$$
But when you convert this to $\rm kg$, you lose that level of accuracy and end up with:
$$M_☽ = (7.3458 \pm 0.0007) \times 10^{22}\;{\rm kg}$$

A: One general remark: google does not give a reference for that value. A measured quantity without a source and an error is meaningless. I did not find the mass of the moon in a reputable source with that precision.
For astrophysical constants I can recommend this reference USNO, 2014, Selected Astronomical Constants there the mass of the earth is given by: $$M_E=5.9722(6)\times10^{24}\mathrm{kg}.$$
This value comes from experiments which measure $G M_E$ and then divide by the gravitational constant $G$ to get the mass. The gravitational constant is the limiting factor because it is only known up to $$G=6.67428(15)\times10^{-11}\mathrm{m}^{3}\mathrm{kg}^{-1}\mathrm{s}^{-2}.$$
The mass ratio between earth and moon however can be determined quite well using highly precise position measurements (Lunar Laser Ranging,...) and this methods do not involve $G$:
$$M_M/M_E=1.23000371(4)\times10^{-2}.$$
To my knowledge there are no precise values for the mass of the moon, which would not involve $G$ and using the mass ratio with the mass of the earth will give:
$$M_M=7.3458(7)\times10^{22}\mathrm{kg}.$$
I think the value googles gives has the significant digits of the mass ratio but since the mass of the earth is not know to that precision the digits after the first 4 are meaningless and again a measurement value without a source is worth nothing.
@Wood was faster with his correct answer; but I was nearly finished with this one and it has some additional details.


text:
Q: Python tkinter- getting user input and checking it I'm fairly new to Python but I'm trying to learn as I go along. I'm using a raspberry Pi and I'm using Python version 3.2.3. My question is I have a text widget in my frame which lets users add text. I've got a button below called "run code" and when this is clicked it calls a function which should check the input from the text box. If the character is alphabetical it then prints to a label a welcome message and my score should increase by 5 points, if the input is not alphabetical it shows an error message. I've tried to use an if statement but only the else section is performing. Any suggestions? My code is below:
    import tkinter as tk
    from tkinter import ttk

     score = 0

       class Game(tk.Tk):

        def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "Game")

        container = tk.Frame(self)
         container.pack(side="top", fill="both", expand = True)
         container.grid_rowconfigure(0, weight=1)
         container.grid_columnconfigure(0, weight=1)

         menubar = tk.Menu(container)
          filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", command=quit)

        menubar.add_cascade(label="File", menu=filemenu)

        tk.Tk.config(self, menu=menubar)

         self.frames = {}

        for F in (StartPage, Py2Page1):

             frame = F(container, self)
             self.frames[F] = frame

             frame.grid(row=0, column = 0, sticky = "nsew")

          self.show_frame(StartPage)
     def show_frame(self, cont):
         frame = self.frames[cont]
         frame.tkraise()

     class StartPage(tk.Frame):

      def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        self.columnconfigure(0,weight=1)
         self.columnconfigure(1,weight=1)

         label = tk.Label(self, text="Title")
         label.grid(row=0,column=0, columnspan=2)

            label1 = tk.Label(self, text ="Add text here")
         label1.grid(row=1,column=0, columnspan=2, pady=10)

          button1 = ttk.Button(self, text="Start", command=lambda:         controller.show_frame(Py2Page1))
            button1.grid(row=2,column=0, columnspan=2,pady=10)

    class Py2Page1(tk.Frame):
     def __init__(self, parent,controller):
        tk.Frame.__init__(self, parent)

        result = tk.StringVar()

         self.columnconfigure(0,weight=1,minsize=640)
             self.columnconfigure(1,weight=1,minsize=640)

         label = tk.Label(self, text="Title!")
         label.grid(row=0,column=0,columnspan=2)

         self.status = tk.Label(self)
         self.status.grid(row=0,column=1,sticky="e",padx=30)

         label2 = tk.Label(self, text ="""SubTitle""")
          label2.grid(row=1,column=0)

         label3 = tk.Label(self, text ="""
         Add text here....
         """, justify="left")
        label3.grid(row=2,column=0,sticky="n")

         self.user_input = tk.Text(self,wrap="word")
          self.user_input.grid(column=1,row=2)

          button4 = ttk.Button(self,text="Run Code", command = self.checking)
           button4.grid(column=1,row=3)

          button5 = ttk.Button(self,text="Clean", command = self.clear)
           button5.grid(column=1,row=4)

           self.output = tk.Label(self)
           self.output.grid(column=1,row=5,sticky='w', pady=10,padx=10)

        def checking(self):
           answer = self.user_input.get('1.0',tk.END)

          if  answer.isalpha():
             result = "Hello " + answer
             scorechanged= score =+ 5
          else:
              result = "Please enter your name again"

          self.output.config(text=result)
          self.status.config(text=scorechanged)

      def clear(self):
          self.user_input.delete('1.0',tk.END)

    app = Game()
     app.geometry("1280x720")
     app.mainloop()

Thanks

A: Addressing the initial question:
userInput = stringVar()
userEntry = Entry(master, variable=userInput) #creates an entry box
userInput.get() # returns what is in the entry box

I could imagine with this code you can accomplish what you intend to. You can use if statements to see what is in the entry box and determine weather it is a number.
try:
    int(userInput.get()) # try and convert to integer
except ValueError: # if the conversion fails due to it containing letters
    print('userInput is not a number')


text:
Q: How to display Custom Page Inside Web Part Page In one part of my portal I have a Web-Part page, and I want to use one of the zones to display a Custom Page (just a wiki page from a Team Site in the Site Page library) inside that zone.
If I use a Content-Editor, it displays code gibberish.
If I use a Page-Viewer, it shows the Custom Page with the portal header and everything.
How can I show just the custom page portion inside my Web-Part zone?
[I know I could upload custom html to a document libary and then display that in a content-editor, but then you lose the WYSIWYG RichText editor functionality]

A: If you were trying to display a web part page, you could accomplish this using a page viewer web part, as detailed in my original answer below. However, wiki pages will throw an error if they cannot find the ribbon.
Embed a web part page (not a wiki page) using a Page Viewer Web Part
When specifying the URL of the page that the page viewer web part should display, add "?isDlg=1" to the end of the URL. This causes SharePoint to treat the page as if it were in a dialog box, so it will strip out the quick launch and top navigation bars.
So for example, if the URL of your page is http://mysite/mysubsite/mylibrary/mypage.aspx you'd want to enter http://mysite/mysubsite/mylibrary/mypage.aspx?isDlg=1 into the page viewer web part's URL property.
Embedding a wiki page using a Page Viewer Web Part
As mentioned earlier, wiki pages don't play nicely with isDlg=1.
To get around that, you can customize the master page on your site so that the page will hide the ribbon and navigation bars when some other (custom) query string parameter is provided.
For example, you could add the following code to your site's master page, before the closing </head> tag.
<script>
ExecuteOrDelayUntilScriptLoaded(function(){
if(GetUrlKeyValue("dialog") == "1"){
    var ribbon = document.getElementById("s4-ribbonrow");
    if(typeof(ribbon) != "undefined"){ ribbon.style.display = "none";}
    var nots = document.querySelectorAll(".s4-notdlg");
    for(var i = 0; i < nots.length; i++){nots[i].style.display="none";}
    document.getElementById("MSO_ContentTable").style.marginLeft = "0px";
}},"SP.JS");
</script>

After that you'd be able to append ?dialog=1 to a page's url to achieve an effect similar to isDlg=1, except that it should work on wiki pages.

A: Here's a potential solution that involves a Content Editor and jQuery.load(). You can "screen scrape" the section of the source page and stuff it into an HTML element of your choosing on the destination page. It would look something like this:
$("#myDiv").load("/SitePages/Blah.aspx .ms-WPBody");

In this example, "myDiv" is the ID of a div you'd place in your CEWP, and the argument passed into the load() function is the server-relative url of the source page,then a space followed by the CSS selector of the destination page content. Note that you must escape any spaces in the page url if there are any, because jQuery interprets the first space it finds as the delimiter between the url and the selector.
http://api.jquery.com/load/
(Check out the section titled "loading page fragments")

A: I ended up putting several content editors on the web-part page, and moving the wiki content from the pages in Site Pages to the wiki content of the content editor on the web-part page.  Not what I originally had in mind, but at least I don't have to do tricks to get what I want!
However, even though this is a solution, it isn't the best solution.


text:
Q: Submitting Form via JQuery Ajax Post Request I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.
If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.
On the server, I need to look for the data somewhere other than req.body when using AJAX??
Creating the FormData object:
var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct

And this is the POST request:
$.ajax({
  url: $form.attr('action'),
  type: $form.attr('method'),
  data: ajaxData,
  dataType: false,
  cache: false,
  contentType: false,
  processData: false,
  complete: function() {
    console.log('message created');
  },
  success: function(data) {

  },
  error: function(xhr, textStatus, errorThrown) {
    console.log(xhr.statusText);
    console.log(textStatus);
    console.log(errorThrown);
  }
});

EDIT
Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:
contentType: false,

I tried this line at some point, which also doesn't work
contentType: 'application/json',

But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.

A: This is the html part
<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">
</form>

this is the JavaScript part
<script type="text/javascript">

$(document).ready(function(){
$("#form").submit(function(){
    $.ajax({
        url: "test.php",
        data: $("#form").serialize(),
        type: "POST",
        dataType: 'json',
        success: function (e) {
            console.log(JSON.stringify(e));

        },
        error:function(e){
            console.log(JSON.stringify(e));

        }
    });
    return false;
});
});

</script>

And this is the php code
<?php
die(json_encode(array("status"=>true)));
?>

Hope that will helps you.

A: I checked your code it says that's

Illegal invocation

So i'll give a solution you can use
data: $form.serialize(),
dataType: 'json',

And then you can catch your returned result by
console.log(JSON.stringify(e));

Wish that helps. If you have some errors i can help you.


text:
Q: Big Commerce - Custom Price Retrieval I'm looking at using Big Commerce.
Is it possible through customizations that I can programmatically pull a price via a web service based on who the user is?
User logs into my store; when they search, for each product the price (and some other information) is being populated by a web service call. Same goes for the product page, cart, etc.

A: Yes, this would be possible, although the implementation may vary depending on the size of your catalog/number of individual users who need pricing unique to them.
One option would be to call your web service for pricing and send those prices to the storefront for a specific customer (or group of customers) using the Price Lists API:
https://developer.bigcommerce.com/api-reference/catalog/pricelists-api
Another possibility would be to listen for the ID of the logged in customer, and based on that ID, update the prices of the products in the cart using the Cart API:
https://developer.bigcommerce.com/api-reference/cart-checkout/server-server-cart-api


text:
Q: How to print LaTex in Python 3 Jupyter Notebook I'm currently in a python class, and we're learning about some of scipy's functions - my question is only vaguely related to that.  We were tasked with creating a .quad code to solve the integral:
Definite Integral
I came up with:
def int1(x):

return (x**2*math.exp(-x)*math.sin(x))

integral1 = quad(int1,0,10)

print('Int[0,10](x^2*e^(-x)*sin(x) dx) = {:}'.format(integral1[0]))

This solves the question, but I would like to present my answer in a more elegant form.  I'd love to have the integral print out in LaTex; I know in Markup mode, I can write this as:
$$ \int_{0}^{10}x^2e^{-x}\sin(x) \,dx $$

Is there any way to have the print() function output the integral in LaTex, followed by an = then the value?
I'm programming in Anaconda3 through a Jupyter Notebook on Windows.


text:
Q: Same-origin Policy Specification I have a javascript AJAX call made to a code behind function running on my server, which returns to the client script (that has initiated the call), a url (from a different Domain than mine) with a query (http://www.web_server_url.com/my_query&callback=?). After returning the call, the following JQuery code is executed ('specific_div' being an existing div in the page):
$('#specific_div').load(returned_url);

Meanwhile, I obtain the following error message:
XMLHttpRequest cannot load http://www.web_server_url.com/my_query&callback=?. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

Although I understand the same-origin policy, I do not quite understand why I am obtaining this error message in this scenario since the url is passed from my server. Shouldn't it be accepted by the browser, considering that its origin is from the same Domain (local host in this case), although it is contacting another Domain?

A: Same origin means requested resource/information must be on the same domain (schema + host + port) as page. It does not mean "url to resource provided by the origin server".
In your particular case you have page on "http://localhost" and trying to request "http://www.web_server_url.com" - scheme ("http") and port (80) match, but domain name does not ("localhost" vs. "www.web_server_url.com").
Note that error you see explains that you need to enable CORS on destination server for this particular request.
If you don't own/control destination server (and hence can't use CORS or JSONP to securely communicate with other server client side) than you most generic option is proxy that request on your server. Note that limits on what information you can use (i.e. you can't steal cookies set on the destination domain this way).


text:
Q: Preg_replace issue bbcode I have a problem with the preg_replace function, I am trying to convert some bbcode into HTML but it is not working.
The one that I am trying to get to work is [size=200:37pfziz0][TEXT][/size:37pfziz0]
(not sure why those numbers appear there but they need to be taken into consideration. So I am trying to do [size=(1):(2)](3)[/size:(4)]
I tried it with both eregi and preg and both don't seem to work:
$txt = eregi_replace("\\[size=([^\\[]+):([^\\[]+)\\]([^\\[]*)\\[/size:([^\\[]+)\\]", "\\3", $txt);
$txt = preg_replace("#\[size\=(.*?):(.*?)\](.*?)\[/size:(.*?)\]#is", "\\3", $txt);

Can anybody tell me what I am doing wrong? I spent about an hour on doing quotes, which eventually came out fine using this method:
$txt = preg_replace("#\[quote\=(.*?):(.*?)\](.*?)\[/quote:(.*?)\]#is", "
Quote by: \\1
\\3
", $txt);

A: Okay, considering your example bbcode made it a bit difficult, here's what I came up with, after a bit of testing:
preg_replace( '/\[size=([^\]\:]+)\:([^\]]+)\](.*?)\[\/size\:([^\]]+)\]/is', '$3', $text);

Small note on this: As you've given an example with [text] in between the codes I used (.*?) to match the stuff in between. You might want to change this, if you don't need to support square brackets in between your tags.
As you can probably see, I've got my own habbits when using regex. First I'm always using / as a delimiter, because I think escaping chars is a bit easier with this. Second I'm using dollar signs for matches, to keep it simple, and don't have too many slashes.


text:
Q: Two subspaces $A$, $B$ are paralel, if and only if they are both subspaces of a space with a dimension equal $d = 1 + \max (\dim A, \dim B)$? It is true, that two affine subspaces $A$, $B$ are paralel, if and only if there exists an affine space $C$, that both are subspaces of $C$, and $\dim C = 1 + \max (\dim A, \dim B)$?
If so, do You have a proof?

A: I guess, you mean affine subspaces.
Well, the statement is not true: consider for example any two lines as $A$ and $B$ intersecting in a point, then they satisfy your criterium, as they generate the plane of those intersecting lines, though the lines are not parallel.
Another example is $A:=$ plane $(z=0)$, $B:=$ $z$-axis.
However, if in addition $A\cap B=\emptyset$ is assumed, then we can conclude that $A\parallel B$, as follows:
Without loss of generality, we can assume that $\dim A\ge\dim B$ and that $0\in A$ (else we can shift both sets with $-a_0$ for any fixed $a_0\in A$). Then, let $b_0\in B$ arbitrary. By assumption, $b_0\notin A$, so for the generated (now linear) subspace $W:=\langle A,b_0\rangle=\{a+rb_0\,\mid\, r\in\Bbb R,\ a\in A\}$, we have
$$\dim W = 1+\dim A=1+\max(\dim A,\dim B)$$
So, that $W=\langle A,B\rangle$ by hypothesis. This means that for any $b\in B$, we have $b=a+rb_0$. I let it for you to check that if $r\ne 1$, then the line of $b_0$ and $b$ will intersect $A$, which case is excluded.
So, we have $r=1$ and $b-b_0\in A$, meaning that the vector from $b_0$ to $b$ is parallel to $A$. -QED-


text:
Q: How to DNSSEC Sign Bind9 Reverse Zone I'm using bind9 and dnssec-keygen/dnssec-signzone. I've had no problem signing my forward zones however I cannot seem to find any documentation on signing reverse zones. What is the process for this?

A: The reason why there is no separate documentation for reverse zones is that reverse zones are just a subset of zones which there is plenty of documentation for. The thing that sets a reverse zone apart from other zones is how it is (typically) used, not how it actually operates.
Ie, the only thing that is actually different is that your typical lookup of a name inside a reverse zone is for type PTR and for a name which is the result of having mapped an IP address into a name based on the standardized convention of reversing the IP address and appending .in-addr.arpa or .ip6.arpa for IPv4 and IPv6 respectively. The reverse zone itself operates just the same as any other zone and neither the authoritative nameserver or the resolver server needs any special handling for this at all.


text:
Q: PHP ZipArchive::addGlobe() is slow I can not delete temp directory I have a code which

*

*Generate csv files to temp directory

*Call ZipArchive::addGlob()

*Then remove temp dir

But it seems the addGlobe() is not enough fast and files are deleted before addGlob() creates the zip file.
Code looks like:
function saveCsvDaysDataZip($campaign_id)
{
    $tempDirName = CampaignsDeviceDays::CSV_REPORTS_DIR . '/' . $campaign_id . '/temp';

    $zip = new ZipArchive();
    $zip->open($tempDirName . 'reports.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

    $addGlob = $zip->addGlob("$tempDirName/*", GLOB_BRACE, ['remove_all_path' => TRUE]);
    if( $addGlob === false ) throw  new \Exception("CampaignsDeviceDays::saveCsvDaysDataZip() error: \$zip->addGlobe() failed. " . $this->zipArchive->getStatusString() );
}

public function removeCsvExportsDir($campaign_id)
{
    $dirName = self::CSV_REPORTS_DIR . '/' . $campaign_id . '/temp';
    FileSystem::delete($dirName);
}

$saveCsvDaysDataZip($campaign_id);
$removeCsvExportsDir($campaign_id);

Is it possible that removeCsvExportsDir($campaign_id) is called before addGlob() is done?

A: Your function had no call to ZipArchive::close - which I guess PHP will then take as "permission" to continue populating the ZIP archive in the background, and return before that process is actually finished.


text:
Q: GWT: Additional  tags on RichTextArea.getHTML() in Firefox I have a com.google.gwt.user.client.ui.RichTextArea with text "Hello World".
When I do:
IE / CHROME
String text = richTextArea.getText(); // I get "Hello World" - CORRECT
String value = richTextArea.getHTML();  // I get "Hello World" - CORRECT

FIREFOX
String text = richTextArea.getText(); // I get "Hello World" - CORRECT
String value = richTextArea.getHTML();  // I get "Hello World
" - INCORRECT

Any Ideas?
THANK YOU!

A: I have read that this issue has been already reported as a bug. Meanwhile, we can get around this with a code like this:
String value = richTextArea.getHTML();
if(value.lastIndexOf("
") == value.length()-4)
  value = value.substring(0, value.length()-4);

A: The GWT issue logged for this - http://code.google.com/p/google-web-toolkit/issues/detail?id=6798
Work Around -  Sanitize the html string -
Class MyRichTextArea extends RichTextArea{
       public String getHTML() {
        return super.getHTML().equals("
") ? "" : super.getHTML();
    }
}

This is not exactly a GWT specific bug.


text:
Q: Unknown Provider error creating angular.js service with require.js I'm trying to get a service working using AMD loading with require.js. I have my controllers all working and can load $rootScope to store app-wide variables/data but I would also like to add some methods to modify or refresh some of the app-wide data when needed. Thus I was trying to create a service object in require.js
So I create this sort of a thing:
MyService.js
define( ["angular"], function (angular) {
    var MyService = function($scope, $rootScope) {
        this.$scope = $scope;
        this.$rootScope = $rootScope
    }
    MyService.$inject = ["$scope"];
    MyService.prototype = {
        constructor: MyService,
        // comma separated list of methods and properties
    }
    return MyService
})

I similarly define a couple of controllers (all already working fine) then access them in my require.js config something like:
requirejs(
    [ "angular", "MyService", "MyController" ],
    function(angular, MyService, MyController) {
        let myAppHandle = angular.module('myApp',[])
            .service("myService", ['$scope','$rootScope', MyService])

        // the following throws an error:

        //     angular.js:15697 Error: [$injector:unpr]
        //         Unknown provider: $scopeProvider <- $scope <- myService

        myAppHandle.controller('MyController', ['$scope', 'myService', MyController])
    }
)

Any help is appreciated

A: Ahh, I was guessing in the dark at how to create a service properly in require.js and after some tinkering and banging my face on the keyboard, I eventually figured out the problem was not with the controller getting the service, but with the service getting $scope
The examples I found for require.js dealt mostly with controllers, components and directives and and in just about every case, $scope was the first thing passed in.
I took $scope out of the .service() in the definition and in the constructor for the class and it's now working.
define( ["angular"], function (angular) {
    var MyService = function($rootScope) {
        // using $rootScope to store app-wide variables
        //   accessible directly or via this service
        //   potentially updated/populated by methods in this service
        this.$rootScope = $rootScope
    }
    MyService.prototype = {
        constructor: MyService,
        // comma separated list of methods and properties
    }
    return MyService
})

and
requirejs(
    [ "angular", "MyService", "MyController" ],
    function(angular, MyService, MyController) {
        let myAppHandle = angular.module('myApp',[])
            .service("myService", ['$rootScope', MyService])

        myAppHandle.controller('MyController', ['$scope', 'myService', MyController])
    }
)

for reference, this is what the controller looks like:
define( ["angular"], function (angular) {
    var MyController = function($scope, myService) {
        this.$scope = $scope
        // make service handle available as class property
        this.myService = myService
    }
    MyController.$inject = ["$scope"];
    MyController.prototype = {
        constructor: MyController,
        // comma separated list of methods and properties
    }
    return MyController
})

(Hopefully this will save someone else the 2-3 hours I took figuring this out)


text:
Q: Add a geojson file and create polygons in a map with mapbox I have an example.geojson file in the same repository with my html file, formed like this:
{
"type": "FeatureCollection",
"features": [
        {
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [0.328475794345889,51.5430323219002],
                    [0.330011830097691,51.544575635037],
                    [0.332923372866699,51.5445177628264],
                    [0.334298679806651, 51.5429165836459],
                    [0.328475794345889,51.5430323219002]
                ]
            ]
        },
        "properties": {
            "O3_var": null,
            "CO2_var": null,
            "NO2_var": null,
            "O3_mean": null,
            "CO2_mean": null,
            "NO2_mean": null,
            "PM10_var": null,
            "PM25_var": null,
            "PM10_mean": null,
            "PM25_mean": null,
            "measurement_start_utc": null
        }
    }
 ]
}

And I want to import this into the html and create a polygon on map. I have tried this:
   <!DOCTYPE html>

   ....

What should I change in my html file? Because the output is only a map. Please any advice will be helpful. Thank you in advance.

A: Thank you for your responses. I am so sorry. It's all my fault. I should have used a http server to load the page. I used python3  http server.


text:
Q: Launcher Theme In Android In my application, I've created a launcher theme for MainActivity:
<activity
            android:name=".MainActivity"
            android:exported="true"
            android:theme="@style/SplashTheme">

In another activity, I return MainActivity with:
startActivity(Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP })

In the Android 10 emulator, when I returned MainActivity, the theme didn't re-render, but in the Android 11 emulator, the theme did re-render.
Target SDK in my app is 29.
Why did my app have different results on the two devices?
Is there a workaround for two devices to have the same result?


text:
Q: Laravel: How to create correct routes group for localization? Now I write sample routes without grouping for localization my Laravel project :
Route::get('/{lang?}', function($lang=null){
    App::setlocale($lang);
    return view('welcome');
});

How I can create group of routes correctly for more one language with prefix or with argument instead of prefix or with domain routing in Laravel 5.6? And can be created localization in prefix and domain routing examples:
http://website.com/en
http://en.website.com

A: Well here's my best try:
Keep all your route definitions in e.g. web.php
You can then use multi-domain routing in your RouteServiceProvider:
Route::group([
    'domain' => '{lang}.example.com'
    'middleware' => LangMiddleware::class,
    'namespace' => $this->namespace // I guess?
], function ($router) {
     require base_path('routes/web.php');
});

In addition, using the same routes you can also do prefixed route groups:
Route::group([
        'middleware' => LangMiddleware::class,
        'namespace' => $this->namespace,
        'prefix' => {lang} //Note: This works but is undocumented so may change
], function ($router) {
    require base_path('routes/stateless.php');
});

This all relies on that LangMiddleware middleware class which can be something like:
class LangMiddleware {
     public function handle($request, $next) {
          if ($request->route("lang")) {
               // also check if language is supported?
              App::setlocale($request->route("lang"));
          }
          return $next($request);
     }
}

A: You can use group in routes to manage multiple routes and then apply functionality like middleware on them. For example:
Route::group([ 'middleware' => 'name', 'namespace' => 'prefix' ], function($router){
    $router->get('/xyz','Controller@function);
});


text:
Q: Is the rx (rxjs) fromEvent operator multicast? Hot/Cold/Multicast can be confusing. I think I'm getting my head around it now, but I wanted to confirm that I understand properly.
Looking at the source for rxjs's implementation for fromEvent, the constructor calls .publish().refCount(). Does this mean that the event listener I set up using fromEvent, for instance fromEvent(document, 'click') will only be added to the document if there is a subscriber, and once I remove all subscribers, the event listener is also removed? I am concerned about performance and want a single source stream to be multicasted to all subscribers. I believe I understand this correctly but would love some clarification if I'm not getting it. It seems like this should be the default case.
Thanks!

A: That's an interesting question I never thought to test!
Speaking of tests, RxJS's tests show that it is intended that a listener is only added upon subscription, and removed when no subscriptions remain:
http://reactivex.io/rxjs/test-file/spec-js/observables/fromEvent-spec.js.html#lineNumber48
And a quick test in the browser confirms it. Have play with this snippet with the dev tools open:

const subs = []

const panel$ = Rx.Observable
  .fromEvent(document.getElementById('target'), 'click')

function add() {
  subs.push(panel$.subscribe(() => console.log('click')))
  console.log('subscribe')
}

function clearEm() {
  subs.forEach(s => s.unsubscribe())
  console.log('unsubscribe')
}

<button id="target">Target</button>

<button onclick="add()">Add</button>
<button onclick="clearEm()">Clear</button>

Here's what the debugger shows, when you right click on the target button and look at its list of attached event listeners. You might need to hit the debugger's refresh button to see the up-to-date list.


text:
Q: FINRA API in Python or R? I am very new to the coding and now learning more about Python for financial analysts matters. I am trying to figure out how I can download equity short interest from FINRA because I could not find any similar articles or cases discussing about getting the financial data from FINRA. Would be great if somebody could clarify me that It is possible or not to do it in python or R.

A: FINRA has an API developer portal that outlines for their API products. It seems Short Interest Data can be fetched using their Market Transparency API (More info here: https://developer.finra.org/products/market-transparency).
You can use either R (jsonlite and httr libraries) or Python (requests and json modules).


text:
Q: How is the path expression built when calling the search API for Form Builder? When accessing the Form Builder summary, which lists the forms I currently have access to, I see the search API is called with
<query name="application-name"
       path="xh:head[1]/xf:model[@id = 'fr-form-model'][1]/xf:instance[@id = 'fr-form-metadata']/*[1]/application-name[1]"
       inline-label="" type="xs:string" control="output"
       search-field="true" summary-field="true" match="substring" />

How/where is the path expression built?

A: *

*It is built by the Form Runner summary page, the same way for Form Builder as for other forms, looking for elements with the fr-summary class.

*So the summary page can find those element, Form Builder has hidden outputs with that class.

*Those outputs reference real binds in Form Builder's model.

*Form Runner's summary page builds the path expression by going through the ancestors of the bind mentioned in the previous points, and building and building an expression concatenating the ref on those binds.


text:
Q: input/output error on NTFS drive when path is very long I seemed to have hit a bug in the underlying sub-system handling NTFS drives. I cannot seem to work with file paths that are more than 155 or so characters long (count includes "/mount/user/"). If the total file path is 152 characters or less everything works normally, such as rsync, cp, the file manager ...etc. However, once the character count exceeds a certain threshold then everything fails with an "input/output error"; I haven't determined the exact number but I know that 157 characters will fail.
I'm in the process of copying 4TB worth of data so manually shortening the paths isn't really an option, and I've already renamed the mount label to just 1 character but there are still files buried too deep. How do I get around this?
For reference I'm using 16.04.3 LTS, and the drive is mounted through USB, if that matters.
*note: although input/output errors are usually associated with hardware failures this is not the case; the files are perfectly fine.


text:
Q: Is this energy usage for safari normal? I was checking my activity monitor for Safari, and I see this number as its average energy usage. Is it normal?

A: It is not normal according to the "Avg Energy Impact" column. It is awkward to have more than 10,000 value for the "Avg Energy Impact" column, especially from Safari. Please contact Apple Support if you see this consistently.
You should consider the "Energy Impact" column as it shows the real-time energy usage.
The "Avg Energy Impact" column shows the average energy impact for the past 8 hours or since the Mac started up, whichever is shorter.
For more info : Apple Documentation - Activity Monitor


text:
Q: Auto sent emails from react I have a website created with react and firebase. I would like to auto sent an email to the user address email which is logged on after he click a button. How can i do that?

A: There are many possible solutions... You could use the "Trigger Email" extension for that.
Just configure the extension (follow this article) and then, each time you want to send an email, create a document in the corresponding Firestore collection when the user clicks on the button. That's it, you are done!


text:
Q: Dual Boot - XP and Ubuntu on two HDD Pardon question redundancy.  I read similar, but unanswered questions involving what I'd like to do.
I have an ancient Dell desktop running XP to which I've added a second hard drive.  Both drives are only 40GB each, so there is little room to crowd two OS on one drive.  I had been using the second drive for backup/storage, but I'd like to put Ubuntu on it and have dual boot available. I have Pangolin ISO on CD. My BIOS boot sequence options show CD-ROM, but not my DVD drive (added later - not factory) and PP is the latest distro that fits on a CD.
My proposal:
Reformat and wipe the second drive.
Set blank drive to boot first in BIOS.
Ubuntu should show no OS and I can safely let it install GRUB and OS on the second drive automatically without worry of ruining XP or partitioning incorrectly.
Let Ubuntu drive remain first to boot and GRUB will give boot option.
Any glaring holes in this plot?  I am a noob and worried about screwing up partitioning.  I was hoping this would be the simplest method, but my ignorance may be showing here.  I don't care about default boot order.
Specific questions:  Will I be able to share data between the two OS with this method?  Not critical, but I'd like to be able to at least copy stored data back and forth between them.  After running the LIVE session of Ubuntu to rescue data from a Vista corruption crash on my laptop, I've seen my Win HDD mounted in Ubuntu, but will XP see my Ubuntu drive and let me access it?
I've only recently started playing with Linux distros, but I am amazed by what can be done.  I've run Damn Small Linux and then Absolute Linux on a castoff office workstation that previously ran Win98 and it is like reviving the dead.  Most impressive.
EDIT_____________________________________________
Okay.  When I go to install, I have only two options from Ubuntu.  Replace XP and install 12.04, or "Something Different".  Since I want to keep XP on sda, I must format the partitions on sdb myself.  This is where I'm like a kid on a high dive who's hesitant to jump.  I've read a lot of different things, but most involve partitioning for both OS on the same drive.  I want to leave sda alone (except for GRUB install) and partition sdb for Ubuntu.  I have 40GB HD and 750MB of RAM.  I know that I need a swap area, a root partition, and then a space for Ubuntu files. I'd like to be able to share files between OS if possible.  Do I need to make some changes to the sda partition to do that?
This is what I think I need to do to sdb.  Please let me know if you see anything that I should change.
Primary - 1000 MB - Beginning - Swap
Primary - 10,000 MB - Beginning - ext4 - /
Primary - 28,700 MB - Beginning - ext4 - /home
The last part is the remainder of free space after the first two.  Drive reads 39,700 MB actual size.  From what I read, swap should roughly equal RAM and something I read led me to believe that 10GB would be a good size for root.
Sorry for the spoon-feeding request, but any advice is greatly appreciated.

A: Using two hard drives is one of the easiest ways of dual booting. They will probably show as sda and sdb.
There is no need to wipe the second hard drive because Linux will format it as part of the installation. You just need to point Ubuntu at the partition you want it to install into.
You should let Grub2 to install on the MBR of DISK ONE, the Windows one. THe MBR is a tiny bit of the hard dist and you should have no problem.