text:
Q: how to pass parameters with spaces to autoIT run command from selenium String cmc = "D:\\fileFolder\\File Name-" + CurrentDate() + ".xlsx";

String autoitexec = "D:\\AutoITScripts\\AttachFile.exe" + cmc;

Runtime.getRuntime().exec(autoitexec);

Above code is my current code. I am passing autoIt script location and file location from string autoitexec. I am unable to run above code ..

A: String cmc = "D:\\fileFolder\\File Name-" + CurrentDate() + ".xlsx";

String autoitexec = "\"D:\\AutoITScripts\\AttachFile.exe\" \"" + cmc + "\"";

Runtime.getRuntime().exec(autoitexec);

Escape double quotes with a backslash. i.e. 2 double quotes inside a double quoted string is " \" \" ".
Spaces are required between the command and each of the arguments.


text:
Q: How to make existing columns empty in Django I want to make existing columns empty and in the future the column can not be filled.
application = models.CharField(default="noname", max_length=100, null=False)

Make existing columns empty and in the future the column can not be filled with any values.

A: application = models.CharField(default="noname", max_length=100, blank=True, null=True, editable=False)

The editable attribute will make it disappear the form and django-admin and the field cannot be updated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Freemarker "Expected a hash, but this evaluated to a string" I'm using Freemarker as an addition with OpenOffice, to process documents with variables.
Therefore, in this case, I want an adress with either a contact person (if there is one) or just the normal contact details (adress).
[#function GetAdr]
    [#return (recipient)!"unbekannt" /]
[/#function]

[#function GetAdrWithContact]
    [#return (GetAdr().contact)!"unbekannt" /]
[/#function]

[#if (GetAdrWithContact().adress)?? ]
[#if GetAdr().name??]${(GetAdr().name)?xml}<text:line-break />[/#if][@Adr GetAdrWithContact() /]
[#elseif (GetAdr().adress)?? ][@Adr GetAdr() /] [/#if]
[/#macro]

If I want to use this code, I get the

Expected a hash, but this evaluated to a string

error, only for the case if there is no contact person though. It works, as long as there is a contact person.
Edit: I tried to check GetAdrWithContact().adress) with ?has_content or ?is_string, neither worked.

A: The ! operator (and ?has_content) only handless nulls and missing values, not type errors. And indeed it's strange when you chose a default value that differs in type from what would be there when the value isn't null. Certainly you should use {} (empty hash) as the default, or something like that. Something that's similar to the real thing. Then GetAdr().name?? and such won't be an error.


text:
Q: want to manipulate date command to count into future beyond today I have this snip of code I have been using in an alarm script I hacked together and have been using with success for the last year or so. But it has always been limited in the sense that if I specify an alarm duration that would extend beyond midnight, past 23:59, then the alarm simply sounds off immediately.
It has not been a problem b/c most of the time I just set an alarm for 1, 5, 10, 30 or 45 minutes as quick reminders. But now I would like to extend the functionality to extend beyond a day if needed and I am sure it is this snip of code that needs to be modified:
sleep $(( $(date --date="$at" +%s) - $(date +%s) ));

By first running:
15:10 ~ $ $(( $(date --date="23:59" +%s) - $(date +%s) )) ; date
bash: 31706: command not found
Sat Jul 12 15:10:34 ICT 2014

I see that there is 31706 seconds to go until 11:59PM. And then:
15:10 ~ $ $(( $(date --date="00:00" +%s) - $(date +%s) )) ; date
bash: -54637: command not found
Sat Jul 12 15:10:37 ICT 2014

I can see the code does not simply add an additional 1 second to the total number of seconds until midnight (tomorrow), but actually seems to count backwards to midnight that already occurred earlier today, some 15 odd hours ago.
I am unsure about the entire snip of code to be honest. What I wonder is if someone might mind breaking things down for a clearer understanding of what exactly is occurring here so I might be in a better position to modify my script so that it continues to count forward into the future, even beyond timestamps that will go beyond the current day.

A: When only given time, that time is applied to the current date, so 00:00 refers to midnight of today's date, which has already transpired. To refer to midnight at the beginning of tomorrow's date, explicitly specify the date as tomorrow, i.e. the whole datetime as tomorrow 00:00:
$ date
Sat Jul 12 10:29:16 CEST 2014
$ date -d "00:00"
Sat Jul 12 00:00:00 CEST 2014
$ date -d "tomorrow 00:00"
Sun Jul 13 00:00:00 CEST 2014

Using that syntax, getting the number of seconds until midnight just works:
$ echo $(( $(date -d "tomorrow 00:00" +%s) - $(date +%s) ))
48527

Note: when run exactly at midnight, this code will print 86400, not 0.


text:
Q: Add different types of childs to treeview I'd like to visualize a collection of Test class (POCO from model assembly) in a TreeView. Each Test instance has got a collection of Readers and Groups:
Test class pseudo code
public class Test
{
    // properties
   public  ObservableCollection<Reader> Readers { get; set; }
   public  ObservableCollection<Group> Groups { get; set; }
}

What I want
My goal is to visualize the tests in a TreeView like that:
Test 1
   |- Reader 1
   |- Reader 2
   |- Group 1
   |- Group 2

Test 2
   |- Reader 1
   |- Group 4
   |- Group 5

What I got so far
I can show tests and readers by using a HierarchicalDataTemplate
<HierarchicalDataTemplate DataType="{x:Type model:Test}" ItemsSource="{Binding Readers}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

Basically I want to tell the TreeView, "Hey there is another child item source with another template in my test class, use it!".
I tried using a CompositeCollection of readers and groups, but got stuck because I don't want to change the Test class (it is generated code).

A: Create a Converter and use it in your HierarchicalDataTemplate.ItemsSource.
Converter :
public class ReadersGroupsCombineConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ObservableCollection<Reader> readers = (value as Test).Readers;
        ObservableCollection<Group> groups = (value as Test).Groups;

        ObservableCollection<object> readersGroups = new ObservableCollection<object>();
        foreach (Reader reader in readers)
            readersGroups.Add(reader);

        foreach (Group group in groups)
            readersGroups.Add(group);

        return readersGroups;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML :
    <HierarchicalDataTemplate x:Key="HDTReaderGroups" ItemsSource="{Binding ., Converter={StaticResource ReaderGroupsCombineCnvKey}}">
        <HierarchicalDataTemplate.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </HierarchicalDataTemplate.ItemTemplate>
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>

A: What I've done in the past, and recommend you to do, is to create a wrapper object for each type you want to represent in the treeview. You can initialize that structure in the viewmodel. When you have all your objects set up, you can do this:
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type Model:TestNode}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

And now the templates for the children:
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type Model:ReaderNode}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type Model:GroupNode}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

This way you will have a template for each type of object you are modeling.
As I've said before, I recommend you to do this, because a binding to an object that doesn't implement INotifyPropertyChanged leaks memory, and usually POCOs and DTOs don't implement it. You can see more here: https://support.microsoft.com/en-us/kb/938416


text:
Q: Verifying Linear Regression implementation using python I just started with machine learning, spent few hours learning Linear Regression. Based on my understanding I implemented it from scratch in python (code below) without regularisation. Is my logic correct or does it need any improvements?
import numpy as np
import matplotlib.pyplot as plt

# Assigning X and y from the dataset
data = np.loadtxt('ex1data1.txt', delimiter=',')
rows=(data.size)/2
X = np.array((data[:, 0])).reshape(rows, 1)
y = np.array(data[:, 1]).reshape(rows, 1)
m = np.size(X)
X = np.insert(X, 0, values=1, axis=1)
t = np.ones(shape=[2, 1])

def linReg():
   h = np.dot(X,t)
   J = 1/(2*m) * sum((h - y)**2)
   print('Cost:',J)
   print("Error:",h-y)
   for i in range(1,2000):
       h = np.dot(X,t)
       t[0] = t[0] - 0.01*(1/m)*(np.dot((X[:,0]),(h-y)))
       t[1] = t[1] - 0.01*(1/m)*(np.dot((X[:,1]),(h-y)))
       J = 1/(2*m) * sum((h - y)**2)
       print(i)
       print('Cost:', J)

   plt.scatter(X[:,1],y,color= 'blue')
   plt.plot(X[:,1],h)
   return t

def predict(newval):
  W = linReg()
  predValue = np.dot(newval,W[1]) + W[0]
  print("Predicted Value:-",predValue)
  plt.plot(newval, predValue)
  plt.scatter(newval, predValue, color='red')
  plt.xlim(0, 40)
  plt.ylim(0, 40)
  plt.show()

print("Enter the number to be predicted:-")
nv = input()
nv = float(nv)
predict(nv)

A: To check your model, a simple thing to do would be to split your data into a training set and a test set. The training set is used to fit the model, by being passed as an argument to the linReg function, and the features of the test set are used for prediction (with your so-called predict function).
You will then need a third function to score your model, by comparing the predictions with the actual values given by the data. If you get a good score, then your implementation may be correct, and if not, a little debugging will be necessary ;-)
To get started, I would suggest rearranging your code by defining the following functions:
def train_test_split(X, y):
    """
    Return a splitted version (X_train, y_train) and (X_test, y_test) of the dataset.
    """

def linReg_train(X_train, y_train):
    """
    Fit the model and return the weights.
    """

def linReg_pred(X_test)
    """
    Use the fitted model to predict values for all the points in X_test.
    """

def linReg_score(y_predicted, y_test)
    """
    Compare predicted and true outputs to assess model quality.
    """

Some resources you might find useful:

*

*A friendly introduction to linear regression with Python: a series of videos that goes into detail about how to implement linear regression.

*Linear regression in scikit-learn: scikit-learn is one of the most useful libraries for machine learning in Python, with a very well-written documentation. If you plan to write your own implementations of ML algorithms, you may want to check them  by running your data through the scikit-learn implementations and compare the outputs with those of your own work.

Good luck !


text:
Q: in Ipython notebook / Jupyter, Pandas is not displaying the graph I try to plot I am trying to plot some data using pandas in Ipython Notebook, and while it gives me the object, it doesn't actually plot the graph itself. So it looks like this:
In [7]:

pledge.Amount.plot()

Out[7]:

<matplotlib.axes.AxesSubplot at 0x9397c6c>

The graph should follow after that, but it simply doesn't appear. I have imported matplotlib, so that's not the problem. Is there any other module I need to import?

A: Edit:Pylab has been deprecated please see the current accepted answer
Ok, It seems the answer is to start ipython notebook with --pylab=inline.
so ipython notebook --pylab=inline
This has it do what I saw earlier and what I wanted it to do.
Sorry about the vague original question.

A: simple after importing the matplotlib you have execute one magic if you have started the ipython as like this
ipython notebook

%matplotlib inline

run this command everything will be shown perfectly

A: With your import matplotlib.pyplot as plt just add
plt.show()

and it will show all stored plots.

A: Note that --pylab is deprecated and has been removed from newer builds of IPython,  The recommended way to enable inline plotting in the IPython Notebook is now to run:
%matplotlib inline
import matplotlib.pyplot as plt

See this post from the ipython-dev mailing list for more details.

A: start ipython with ipython notebook --pylab inline ,then graph will show inline.

A: All you need to do is to import matplotlib.
import matplotlib.pyplot as plt

A: import matplotlib as plt
%matplotlib as inline


text:
Q: Facebook app fetching ads reports from business account I can't figure this out, I hope someone here can point me in the right direction. I've searched for an answer but was unable to find it.
I want to create a Facebook app which would manage ads (download ads reports and statistics). I've got user account, registered as developer, created and whitelisted the app. I've got only Development Access and that means means I can query only ad accounts owned by the admins of the app, set up in the account list associated with your application.
Problem is that the account with ads is a business account so I can't add this account as part of developers team and get the statistics. I get permissions errors when trying to access the business account (I have access token and everything, it just won't let me see the ads data due to insufficient permissions).
Is there a way to do this without applying for Basic access (not sure if I'll get it since the app is not done)? Can't I really somehow connect my developer's account with that business account?
About access limits: https://developers.facebook.com/docs/reference/ads-api/access/v2.2#limits

A: Seems like this is working correctly - you can build and test the app against accounts administered by your app's admins/developers at first
Once it's working you can submit it for approval to the Basic access level, where you can manage more accounts, including those belonging to users who aren't admins/developers of the app
There's more information about the access levels and how to move between them in the Access levels dovumentation


text:
Q: XSL Template is making loading speed very slow Hello the below code is making my page loading speed very slow. Can you help please!
 <xsl:template match="Category" mode="CategorySelectorScript">
            <xsl:variable name="ThisCategoryID" select="CategoryID"/>
            <xsl:variable name="HasChildren"><xsl:choose>
                <xsl:when test="../Category[ParentCategoryID=$ThisCategoryID]">
                    true
                </xsl:when>
                <xsl:otherwise>
                    false
                </xsl:otherwise></xsl:choose>
            </xsl:variable>
            arrCategory=new Array(<xsl:value-of select="CategoryID"/>, <xsl:value-of select="ParentCategoryID"/>, '<xsl:value-of select="Name"/>', <xsl:value-of select="$HasChildren"/>);
            arrCategories.push(arrCategory);
        </xsl:template>

The problem is with this line <xsl:when test="../Category[ParentCategoryID=$ThisCategoryID]"> When i remove ../ from the XPath it loads fast but then i didn't get the working feature. So is there any alternative of ../ which works ?
Full Code
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="xsl">

<xsl:output method="xml"
            omit-xml-declaration="yes"
            indent="yes"
            encoding="utf-8"/>

    <xsl:template match="Location">
        <xsl:call-template name="CategorySelectorScript"/>

        <form id="frmLocationCategoryAdd" action="locationcategoriesadd.php" method="post">

                <input type="hidden" id="inpAction" name="inpAction" value="SAVE"/>
                <input type="hidden" id="inpLocationID" name="inpLocationID" value="{LocationID}"/>
                <input type="hidden" name="inpCategoryIDs" id="inpCategoryIDs" value=""/>

<xsl:text> </xsl:text>

Add this category

This category has already been selected

Categories to add

No categories

                    Add Categories

                    Cancel

        </form>
    </xsl:template>

    <xsl:template name="CategorySelectorScript">

    </xsl:template>

    <xsl:template match="Category" mode="CategorySelectorScript">
        <xsl:variable name="ThisCategoryID" select="CategoryID"/>
        <xsl:variable name="HasChildren"><xsl:choose>
            <xsl:when test="../Category[ParentCategoryID=$ThisCategoryID]">
                true
            </xsl:when>
            <xsl:otherwise>
                false
            </xsl:otherwise></xsl:choose>
        </xsl:variable>
        arrCategory=new Array(<xsl:value-of select="CategoryID"/>, <xsl:value-of select="ParentCategoryID"/>, '<xsl:value-of select="Name"/>', <xsl:value-of select="$HasChildren"/>);
        arrCategories.push(arrCategory);
    </xsl:template>

    <xsl:template name="CategoryFilter">
        <xsl:param name="FiltersOpen">0</xsl:param>

        <input type="hidden" name="inpCategoryIDs" id="inpCategoryIDs" value="0"/>

        <xsl:choose>
            <xsl:when test="0 = $FiltersOpen">
                Filter by location categories
                Remove location category filters
            </xsl:when>
            <xsl:otherwise>
                Filter by location categories
                Remove location category filters
            </xsl:otherwise>
        </xsl:choose>

            <xsl:if test="0 = $FiltersOpen">
                <xsl:attribute name="style">display:none;</xsl:attribute>
            </xsl:if>

<xsl:text> </xsl:text>

            Add this category

This category has already been selected

Categories to filter by

No categories

    </xsl:template>

</xsl:stylesheet>

PS: If anything else is need please comment i will share the requirements with you.
Thanks

A: You haven't shown the source XML.
If the number of Category elements is large and if they are all at the same level in the document, then you should get an improvement by defining a key:
<xsl:key name="CategoryByParentCategory" match="Category"
     use="ParentCategoryID"/>

and then change your test from test="../Category[ParentCategoryID=$ThisCategoryID]" to test="key('CategoryByParentCategory', $ThisCategoryID)"
(This change isn't safe if the Category elements are nested or if you aren't searching all of them: that's why we need to see the XML)
A point about your logic: you are setting the value of the variable $HasChildren to a text node containing the string "true" or "false" surrounded by a load of whitespace, which you are then inserting into some generated Javascript. You could achieve the effect more conveniently by changing the variable declaration to
<xsl:variable name="HasChildren"
 select="boolean(key('CategoryByParentCategory', $ThisCategoryID))"/>


text:
Q: Webpack - Change 'src' path of javascript files in index.html I am facing an issue after building my strapi application (using webpack).
After i executed yarn build, my index.html imports javascript files using the <script> tag.
The issue comes here, in my build folder, there are all of my files (images, js files etc...), and 0 subfolder.
But inside my index.html, it imports from an invalid path:
<script src="admin/file.js"></script>

I want to change this src with Webpack to look like that :
<script src="./file.js"></script>

Anybody got a solution ?
Thank you.

A: Finally, i found the fix.
I am using Strapi for this web app.
Strapi automatically fills webpack with publicPath "/admin/".
However, webpack doesn't understand and put every files (js, img, html) in the same directory, at the same level (no subfolders).
So inside src/admin/, remove the word "example" from the file name "webpack.config.example.js"
Open this file and insert this code
'use strict';
module.exports = (config, _webpack) => {
  config = {
    ...config,
    output: { ...config.output, publicPath: './'}
   }

  return config;
};


text:
Q: embedding a simple ActiveX control got Class not Registered error I just developed a very simple ActiveX control(using the VS.NET wizard, not even change a line), and compiled it. After running "regsvr32 ax1.ocx", I created a new C# WinFrom project and drag the ActiveX control into the form. Then I build and run it, the error says:
Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

within the line:
((System.ComponentModel.ISupportInitialize)(this.axax11)).EndInit();

The entire function is:
    private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
        this.axax11 = new Axax1Lib.Axax1();
        ((System.ComponentModel.ISupportInitialize)(this.axax11)).BeginInit();
        this.SuspendLayout();
        //
        // axax11
        //
        this.axax11.Enabled = true;
        this.axax11.Location = new System.Drawing.Point(103, 90);
        this.axax11.Name = "axax11";
        this.axax11.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axax11.OcxState")));
        this.axax11.Size = new System.Drawing.Size(100, 50);
        this.axax11.TabIndex = 0;
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 262);
        this.Controls.Add(this.axax11);
        this.Name = "Form1";
        this.Text = "Form1";
        ((System.ComponentModel.ISupportInitialize)(this.axax11)).EndInit();
        this.ResumeLayout(false);

    }

A: I'll assume you wrote your ActiveX control in unmanaged C++ code.  You'll need to either create a 64-bit version of this control or you need to force the .NET program that uses it to run in 32-bit mode.  The latter is the quicker fix, Project + Properties, Build tab, Platform Target = x86.


text:
Q: passing an array from an user defined action in controller to a view in Yii In my Yii application I need to perform joint queries in controller and display the final view   in views. this is the mysql query I need to perform.I hav three tables namely,items,manufacturers,items_manufacturers
SELECT items.id,item_desc,manufacturers.id,manufacturers.name FROM items_manufacturers,items,manufacturers WHERE items_manufacturers.item_id=item.id AND items_manufacturers.manufacturer_id=manufacturers.id.

The relation between the models is
public function relations()
    {

            'item' => array(self::BELONGS_TO, 'Items', 'item_id'),
            'manufacturer' => array(self::BELONGS_TO, 'Manufacturers', 'manufacturer_id'),
            'itemsManufacturersLocations' => array(self::HAS_MANY, 'ItemsManufacturersLocations', 'items_manufacturer_id'),
        );

This is the Query I performed in the controller
public function actionJoint()
{

        $imf=ItemsManufacturers::model()->with('item','manufacturer')->findAll();
    $this->render('joint',array(
    'imf'=>$imf
    ));

}

This is the code I implemented in the view
<?php

$this->breadcrumbs=array(
    'joint',
);
$this->menu=array(
    array('label'=>'Create ItemsManufacturers', 'url'=>array('create')),
    array('label'=>'Manage ItemsManufacturers', 'url'=>array('admin')),
);
?>

 List Items and Manufacturers

<?php
$this->widget('zii.widgets.CListView',array(
 'dataProvider'=>$imf,
'itemView'=>'_jointview',
)); ?>

My code  for the render of partial of view
    <?php
   /* @var $this ItemsManufacturersController */
/* @var $data ItemsManufacturers */
    ?>

        <?php echo CHtml::encode($data->getAttributeLabel('item_desc')); ?>:
        <?php echo CHtml::encode($data->item_desc); ?>

        <?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:
        <?php echo CHtml::encode($data->name); ?>

But I am getting this error  which I am unable to rectify.. Anybody help me with this.
Fatal error: Call to a member function getData() on a non-object in /var/www/yii_framework/framework/zii/widgets/CBaseListView.php on line 107

Any body help me how should I proceed since I am a newbie

A: I think you are doing mistake on view listing code.
<?php
$this->breadcrumbs=array(
    'joint',
);
$this->menu=array(
    array('label'=>'Create ItemsManufacturers', 'url'=>array('create')),
    array('label'=>'Manage ItemsManufacturers', 'url'=>array('admin')),
);
?>

 List Items and Manufacturers

<?php
$this->widget('zii.widgets.CListView',array(

'dataProvider'=>$dataProvider,,
'itemView'=>'_jointview',
)); ?>

Now you change your actionJoint() method in your controller.
public function actionJoint()
{

 $imf=ItemsManufacturers::model()->with('item','manufacturer')->findAll();

 $dataProvider=new CArrayDataProvider($imf, array(
 'id'=>'ItemsManufacturers',
 'sort'=>array(
    'attributes'=>array(
         'item_desc', 'name'
    ),
 ),
 'pagination'=>array(
    'pageSize'=>10,
 ),));

 $this->render('joint',array('dataProvider'=>$dataProvider));

}

Now on _joinview page.
check print_r($data); then retrieve data according to your need.
Now it is fine.
Hope it will help you.
Thanks


text:
Q: Trouble with tornado/ asyncio using websocket I'm converting my application from Python 2 to Python 3. Briefly, my app works in Python (server) and in Javascript (client), which connect through a websocket, which I get using tornado. At Python, I have multiple threads. I'm not using Python3's asyncio methods anywhere.
However, when converting my app from Python 2.7 (it works perfectly in Python2) to Python 3.7, I'm having problems with tornado/ asyncio.
First, I was getting the error: RuntimeError: There is no current event loop in thread 'Thread-26'.
After some googling, I found a recomendation to mitigate this:
import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())

This appears to solve that error. However, now I am getting the following warning + error:
2019-08-24 13:27:25,455 asyncio      DEBUG    Using selector: SelectSelector
2019-08-24 13:28:25,455 asyncio      ERROR    Task was destroyed but it is pending!
task: <Task pending coro=<WebSocketProtocol13.write_message.<locals>.wrapper() running at C:\Users\DLA\PycharmProjects\myPmese\Python3\lib\site-packages\tornado\websocket.py:1102>>

Any clues on what's happening? Unfortunately I cannot find what exact part of my Python code is causing this.
Many thanks! Any help would be appreciated :)
You can find bellow the architecture of my Python websocket using tornado:
import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
application = tornado.web.Application([(r'/myPmese/websocket', WSocketHandler)])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8295)
tornado.ioloop.IOLoop.instance().start()

class WSocketHandler(tornado.websocket.WebSocketHandler):

    def initialize(self):
        print('initialize') # here I initialise handlers

    def open(self):
        start_server_code()  # triggers the code from the server.

    def __call__(self, *args):
        clientCommand = self.getClientCommand()
        self.resetClientCommand()
        self.send(clientCommand , *args)

    def send(self, var_func, *args):
        try:
            self.write_message(json.dumps(self.getClientCommand()))
        except Exception as e:
            print(traceback.format_exc())

    def on_message(self, message):
        if message != '':
            try:
                eval(self.executeCommand(message))
            except Exception as e:
                print(traceback.format_exc())
                self.send('createErrorMessage', str(e))

    def on_close(self):
        tornado.ioloop.IOLoop.instance().stop()


text:
Q: DocuSign API - Java: List of Envelope-Sharings between Accounts (SharedAccess Envelope) Because of legal requests, I have to deliver a report for permission audits in DocuSign on a regular basis.
While I have solved to query over the REST-API the permission profiles, Custody Tranfer targets and SigningGroups a user belongs to, I fail now with the envelopes shared by a user to another one.
General:

*

*I am using the "main" account the Docusign Environment is based on.

*DSAdmin Permission Profile.

*Token/Authentication:
 byte[] privateKeyBytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE));
 java.util.List<String> scopes = new ArrayList<String>(2);
 scopes.add(OAuth.Scope_SIGNATURE);
 scopes.add(OAuth.Scope_IMPERSONATION);

 ApiClient apiClient = new ApiClient(BASE_URL);

 OAuthToken oAuthToken =
         apiClient.requestJWTUserToken(CLIENT_ID
                                     , API_USERNAME
                                             , scopes
                                             , privateKeyBytes
                                             , 3600);

 apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());

This is running well. Then I try to access the sharings of the different users:
            AccountsApi accountsApi = new AccountsApi(apiClient);

        ListSharedAccessOptions listSharedAccessOptions = accountsApi.new ListSharedAccessOptions();
        listSharedAccessOptions.setItemType("envelopes");
        listSharedAccessOptions.setShared("shared_to,shared_from,shared_to_and_from");

        AccountSharedAccess accountSharedAccess = accountsApi.listSharedAccess(API_ACCOUNT_ID, listSharedAccessOptions);

        List<MemberSharedItems> memberSharedItemsList = accountSharedAccess.getSharedAccess();

        MemberSharedItems memberSharedItems = memberSharedItemsList.get(0); //  The size of this list is only 1

        List<SharedItem> sharedItemsList = memberSharedItems.getEnvelopes();

        for(SharedItem sharedItem : sharedItemsList) {
                System.out.println(sharedItem.getUser().getUserStatus() + " " + sharedItem.getShared() + " " + sharedItem.getUser().getEmail());
        }

As result I get the printout for several lines with shared_from and shared_to_and_from relative to the account I authenticated with. The result is correct.
But now I'd like to get these information as well for the other users I have in this environment. If I change the accountId in the listSharedAccess()-Arguments, I get a {"errorCode":"PARTNER_AUTHENTICATION_FAILED","message":"The specified Integrator Key was not found or is disabled. Invalid account specified for user."} as error back.
I guess the answer is very simple and I am only thinking to complicated, but I have no clue at the moment, how to list the sharings of the other users.
Here the REST-call and it's answer:
INFO: 1 * Sending client request on thread main
1 > GET https://demo.docusign.net/restapi/v2.1/accounts/API_ACOUNT_ID/shared_access?item_type=envelopes&shared=shared_to%2Cshared_from%2Cshared_to_and_from
1 > Accept: application/json
1 > Authorization: Bearer myLovelyJwtToken
1 > User-Agent: Swagger-Codegen/3.11.0-RC2/java
1 > X-DocuSign-SDK: Java

And the answer:
INFO: 1 * Client response received on thread main
1 < 200
1 < Cache-Control: no-cache
1 < Content-Length: 4797
1 < Content-Type: application/json; charset=utf-8
1 < Date: Wed, 10 Feb 2021 17:59:16 GMT
1 < X-BurstLimit-Limit: 500
1 < X-BurstLimit-Remaining: 499
1 < X-DocuSign-Node: DADADADAD
1 < X-DocuSign-TraceToken: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
1 < X-RateLimit-Limit: 1000
1 < X-RateLimit-Remaining: 995
1 < X-RateLimit-Reset: 1612980000
{"resultSetSize":"27","totalSetSize":"27","startPosition":"0","endPosition":"26","accountId":"API_ACCOUNT_ID","sharedAccess":[{"user":{"userName":"MyUsername","userId":"API_USERNAME","email":"my@email.address","userStatus":"Active"},"envelopes":[{"user":{"userName":"user1","userId":"API_USERNAME_user1","email":"user1@email.address","userStatus":"Active"},"shared":"shared_from"},{"user":{"userName":"user2","userId":"API_USERNAME_user2","email":"user2@email.address","userStatus":"Active"},"shared":"shared_to_and_from"}]}]}

I've shortened the Answer-JSON.
My question is simply: How do I get the information about the envelope-sharings between the different users, where my user I am logged in is not involved? (But all users belong to my DocuSign-Environment I am Admin of)
Thank you very much in advance!
Best Regards
Christian
Edit:
Found the answer myself: Sleeping a night about often helps: I've added the API_ACCOUNT_ID(s) of the users, I want to have this information to the userIds of the SharedAccessOptions and it works well.
Often the answer is so near.

A: https://appdoc.app/artifact/com.docusign/docusign-esign-java/2.4.1/com/docusign/esign/api/AccountsApi.ListSharedAccessOptions.html
Has userIds property [getUserdIDs() or setUserIds() from caller] which enable you to specific a list of userIDs (GUID) for the users you want to get information on.
Note that to find the userId, you can make another call to ListUsers() for example, or you can manually find them in the Apps and Keys page (note User ID not Account Id!)


text:
Q: Search and extract results from an array based on an entry keyword in ruby I would like to compare an Array to an element and extract those data in the another Array
Here is an example of data i'm working with:
Array = [{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"},
         {:id=>4, :keyword=>"happy", :Date=>"01/02/2016"} ... ]

for example i want the first keyword happy to search the same array ,extract if there's any similar words and put them inside another array here is what i'm looking for an end result:
Results = [{:keyword=>happy, :match =>{
           {:id=>3, :keyword=>"happy", :Date=>"01/02/2016"}... }]

Here is the first part of the code :
 def relationship(file)
    data     = open_data(file)
    parsed   = JSON.parse(data)
    keywords = []
    i = 0
    parsed.each do |word|
    keywords << { id: i += 1 , keyword: word['keyword'].downcase, Date:     word['Date'] }
    end
end

A: def search_keyword(keyword)
    hash = [
        {:id=>1, :keyword=>"happy", :Date=>"01/02/2015"},
        {:id=>2, :keyword=>"sad", :Date=>"01/02/2016"},
        {:id=>3, :keyword=>"fine", :Date=>"01/02/2017"},
        {:id=>4, :keyword=>"happy", :Date=>"01/02/2018"}
    ]
    keywords = []
    hash.each do |key|
        if key[:keyword] == keyword
            keywords << key
        end
    end
    keywords
    #{:keyword=> keyword, :match=> keywords}
end

search_keyword('fine')
#search_keyword('sad')

You could group the match elements by key (:match) then get the result with a single hash lookup.

A: Here's another idea that could help you with your situation using enumerable and index:
array to be search:
array = [
        {:id=>3, :keyword=>"happy", :Date=>"01/02/2016"},
        {:id=>4, :keyword=>"happy", :Date=>"01/02/2016"},
        {:id=>1, :keyword=>"happy", :Date=>"01/02/2015"},
        {:id=>2, :keyword=>"sad",   :Date=>"01/02/2016"},
        {:id=>30, :keyword=>"fine", :Date=>"01/02/2017"},
        {:id=>41, :keyword=>"happy", :Date=>"01/02/2018"}
  ]

method search:
store all element matching the term in the array.
def search(term, array)
    array = []
    array << {keyword: "#{term}", match: []}
    arr.select { |element| array.first[:match] << element if element[:keyword].index(term) }
    array
end

Testing:
  p search('sa', array)
  # => [{:keyword=>"sa", :match=>[{:id=>2, :keyword=>"sad", :Date=>"01/02/2016"}, {:id=>21, :keyword=>"sad", :Date=>"01/02/2016"}]}]

hope that will get you goin!


text:
Q: Shared MySQL database between workstations with Docker I want to be able to develop the same website from different computers. I've created github repository and Docker enviroment (using this tutorial: https://www.vultr.com/docs/deploy-a-php-application-using-docker-compose ).
I've got the git repository on both workstations to share the project and Docker files. I've built images ("docker build -t vultr-php php/"; "docker build -t vultr-nginx nginx/") and run composer file ("docker-compose up -d") on both computers. I'm new to Docker so I've only followed this vultr.com tutorial.
Enviroment is working but I'd like to share the database in a way that when I'm done working on a laptop and start working on a desktop then I've got the same database. Is there a way to do this with docker/git?


text:
Q: can text messages be opened directly on third party app (android)? when a text message is sent form, lets say an application 'myApp' it'll open in default text message app of the receiver. but i want to control how it looks to receiver(like changing colour). Is there anyway to send text and read that text in native app, 'myApp'? Or identify it was sent from 'myApp' and import message to 'myApp'.

A: sure you can to receive messages make a broadcast receiver for ingoing messages an each time a message arrive start your activity that displays the message ...
public class SMSApp extends IntentReceiver {
    private static final String LOG_TAG = "SMSApp";

    /* package */ static final String ACTION =
            "android.provider.Telephony.SMS_RECEIVED";

    public void onReceiveIntent(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            StringBuilder buf = new StringBuilder();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
                for (int i = 0; i < messages.length; i++) {
                    SmsMessage message = messages[i];
                    buf.append("Received SMS from  ");
                    buf.append(message.getDisplayOriginatingAddress());
                    buf.append(" - ");
                    buf.append(message.getDisplayMessageBody());
                }
            }
           //start you messages activity

        Intent i = new Intent();
        i.setClassName("com.test", "com.test.myMessagesAcivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //prepare message text to be sent to the activity via bundle
        Bundle bundle = new Bundle();
        bundle.putString("message", but.toString());
        i.putExtras(bundle);
        context.startActivity(i);

        }
    }

}

and in your manifest file add these permissions
<uses-permission android:id="android.permission.RECEIVE_SMS" />

<uses-permission android:name="android.permission.SEND_SMS"/>

and this receiver
<receiver class="SMSApp">

            <intent-filter>

                <action android:value="android.provider.Telephony.SMS_RECEIVED" />

            </intent-filter>

        </receiver>

and to send SMS from your app
use this method
public void eb3atSMS(String phoneNumber, String message)
    {

        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, **DummyClasshere.class**), 0);
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
    }


text:
Q: Return a function parameter based on function result In my simplified example scenario, my objective is to return the sensor temperature (called "TemperatureOfRecord") that is closest to 70 degrees, given a particular timestamp and building. For example, building #1's TemperatureOfRecord for the 8:00 a.m. timestamp is 65 degrees because 65 degrees is closer to 70 degrees than 80 degrees is. The "Delta" column is a computed column that returns the absolute value of the sensor temperature minus 70 degrees. I use the differential to test each sensor temperature against the target temperature of 70 degrees.
The nested correlated subquery below returns the correct results, but I am having a lot of trouble scaling this approach out for my actual scenario. Therefore, I would like to ask if there is a simpler approach that I could use.
SELECT
    tt.TmStamp
    , tt.Building
    , tt.Sensor
    , tt.Temperature
    , tt.Delta
    , (SELECT tt2.Temperature
        FROM dbo.TempTest tt2
        WHERE tt2.Building = tt.Building
            AND tt2.TmStamp = tt.TmStamp
            AND tt2.Delta =
            (SELECT MIN(tt3.Delta)
            FROM dbo.TempTest tt3
            WHERE tt3.Building = tt.Building
                AND tt3.TmStamp = tt.TmStamp)
    ) AS TemperatureOfRecord
FROM dbo.TempTest tt

The results of the above query are below.

A: You could attempt to use a CTE instead. Here's a SQLFiddle too. I've compared the execution plans of the two queries as well - and even though the CTE cost more, it only had about a third the amount of scans/reads than the subquery method.
WITH rec AS (
    SELECT TmStamp, Building, Temperature, ROW_NUMBER() OVER (PARTITION BY TmStamp, Building ORDER BY Delta) AS RowOrder
    FROM dbo.TempTest
)
SELECT
    tt.TmStamp
    , tt.Building
    , tt.Sensor
    , tt.Temperature
    , tt.Delta
    , rec.Temperature AS TemperatureOfRecord
FROM dbo.TempTest tt
JOIN rec
    ON tt.TmStamp = rec.TmStamp AND tt.Building = rec.Building
WHERE rec.RowOrder = 1


text:
Q: Will Calling clear() on a vector of lists clear all the nodes in the list at each index? I am creating a hash table that has a private data member vector<list<pair<K, V>>> hashTable;. My understanding is that a rehash function should assign the elements of the original table to a temp table, empty the original table, resize it, the hash the elements of the temp table back into the original table.
Will an assignment such as vector<list<pair<K,V>>> tempTable = origTable; make a deep copy? Or do I need to declare tempTable to be the same size as original table and then go through each list at each index and add it to tempTable?
Finally, will calling origTable.clear(); empty out all the nodes in each list at each index and reclaim the memory correctly or do I need to step through each index and explicitly empty each list?
Thanks

A: The convention for types in C++ is to have copy semantics, and std::vector, std::list and std::pair all adhere to this.
Therefore vector<list<pair<K,V>>> tempTable = origTable; does a 'deep copy', and no reference to the old data is kept. And similarly calling .clear() on such a vector will destroy all used memory.

A: vector<list<pair<K,V>>> tempTable = origTable;

Everything will copy, from the vector, list, and pair all the way through to K and V.  However, it's worth considering that if K and/or V are themselves pointers, then the pointer will be copied but the object they point to will not, and you will have aliasing.

A: Yes. Copy assignment of vector is deep. The elements will be copied.
Calling clear will erase all elements from the standard vector. All of those objects are destroyed. The destructor of the standard iterator destroys all of its nodes.


text:
Q: Airflow - Failed to fetch log file from worker. 404 Client Error: NOT FOUND I am not able to fetch the worker pod logs on airflow UI. The error I am getting on airflow is:
`
*** Falling back to local log
*** Trying to get logs (last 100 lines) from worker pod aggregationtestcheckingcache-33ea24f45f1344d7a628e21a53b4f6d0 ***

*** Unable to fetch logs from worker pod aggregationtestcheckingcache-33ea24f45f1344d7a628e21a53b4f6d0 ***
(404)
Reason: Not Found
HTTP response headers: HTTPHeaderDict({'Audit-Id': 'b3c492f1-56e5-4fbe-a5b9-ab6c7e01f722', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Tue, 22 Nov 2022 20:15:04 GMT', 'Content-Length': '290'})
HTTP response body: b'{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"pods \\"aggregationtestcheckingcache-33ea24f45f1344d7a628e21a53b4f6d0\\" not found","reason":"NotFound","details":{"name":"aggregationtestcheckingcache-33ea24f45f1344d7a628e21a53b4f6d0","kind":"pods"},"code":404}\n'

`
As soon as a particular dag runs, the logs are visible on the airflow but when it gets success, the logs disapper and the error message is cannot fetch worker log pods. Error:404 Reason:Not found.
But, when the dag is running, I am able to see the pods and the logs on was console.

A: On the off-chance that you're still experiencing this issue: the most likely culprit here is that you haven't configured persistent logs yet.
If persistent logs aren't configured, then Airflow can only fetch logs from actively running tasks, because the log UI is effectively a frontend for kubectl logs. Once the task completes, the pod gets deleted, and hence the 404 error because the pod it wants to inspect is gone. The Airflow documentation goes into more detail and covers the requirements needed to enable persistent logs.
I believe there's also a configuration setting that tells Airflow not to auto-delete completed tasks, but enabling that setting means you'll need to clean them up manually.


text:
Q: Why would I use Min/Max scaling over Z-Score? If I'm using a prediction model which uses a distance-based metric to help calculate class separability, why would I use Min/Max over the Z-Score? I've always thought Z-Score as superior because during your training stage you can't state if you've seen the minimum and maximum values, meaning during production there may be data samples that get normalized to a range not seen by the prediction model, whereas if you use the standard deviation and mean to calculate a Z-Score you can minimize this issue.
Does anyone have any reasons for why Min/Max scaling can be better suited rather than using the Z-Score?

A: There are ML algorithm which react sensible to the change of distance ratio betw. two samples, think k-NN with euclidean distance function.
With k-NN a min-max scaling pre-processing could be a better alternative.
But as always, it depends highly on your data set, how many outliers you have, etc.
And for production, i would argue that in both cases you don't exactly know what comes your way. the only think to remember here, is that you scale the new data instance the same way you scaled the other values.
Then it should not make a difference for your ML algorithm.
IMO, a good walk-through on pros/cons is the Scikit-learn User Guide.


text:
Q: Setting font markers to left-justified in QGIS I have to design a symbology in QGIS following a very strict rulebook. I need to place certain attributes as at exact positions aroud the symbol. Since it is defined as part of the symbol, I do not us labels in this occasion but use font markers in addition to other symbols to create the symbol I need.
However, the text is of varying length. I can define offset and anchor point position but the text is always centred, which means longer text can cover the symbol etc. Is there a way to set the text of the font marker itself to left-justified?
Edit: I am trying to create symbols for certain emergency managment situations. Here is a rather complex example from the rulebook I have to follow for that. I am trying to add text similar to the text fields on the lower right corner of that example:

I suppose I can use rule based labels for this, but the style is meant to work in QGIS as well as in QField and a Geoserverapplication that we are supposed to use. In my experience labels tend to get messed quicker than symbols - but I may be mistaken hiere.

A: A workaround would be to use a constant number of characters and to apply the same offset everywhere. To achieve this, the rpad() function can be used to add spaces to the right of the current text.
It is not perfect though, as different letters have different width.


text:
Q: How to get client domain name from a request I have wcf-service host at kkk.com. When someone(other domain) request to my service I use this code to get client's domain name.
public static string GetClientDomian(HttpContext context)
{
    string clientDomain = string.Empty;
    clientDomain = context.Request.Url.Host;

    return clientDomain;
}

But it's always return kkk.com not return the client's domain name. How to solve this? Thanks.

A: OK. This code is work. Change context.Request.Url.Host to context.Request.UrlReferrer.Host
Like this
public static string GetClientDomian(HttpContext context)
{
    string clientDomain = string.Empty;
    clientDomain = context.Request.UrlReferrer.Host;

    return clientDomain;
}


text:
Q: Numerical integration over non-uniform Grids I have a function which I want to integrate. I have two numpy arrays, one with the x-values and one with the function f(x). I am looking for a function F(x) which is the antiderivative of f(x), defined on the same grid x. This grid x is non-uniform.
Is there some numpy or scipy function giving me the array F(x)?

A: You are likely looking for scipy.integrate.cumtrapz.


text:
Q: Are word timestamps always immediately consecutive and always start from 0? In google cloud speech to text, I'm getting the timestamps of the words as documented here using PHP.
Two issues:
The first word always starts at 0s, even if the audio file doesn't have any sound until after.
Each word timestamp is immediately followed by another, even when the speaker pauses between words.
Is it possible to get a more precise word timestamp with PHP?

A: Based on the documentation, it seems there isn't an option to modify any parameter in order to get a more precise word timestamp.
However, you can report this issue by providing all the information requested within the form.


text:
Q: ASP.NET MVC User role in Angular2 I'am new in Angular2 and now I would like to change my website to Angular2,and in cshtml file we can show specific HTML with razor like:
@if(User.IsInRole("Admin"))
{
    Admin can see here only!
}

And now in Angular2 there's no cshtml,my choice is use AJAX to get the role and put in a variable or LocalStorage,is there any better practice?thanks

A: Yes, there is.
In Angular 2 you could use if conditions as well but in a different manner.
For example:

 Admin can see here only!

This means that this div will be shown only when the isAdmin value is true.
And the is admin true should be set on your .ts (typescript) file where you actually will have the app logic.


text:
Q: ssh force tty return extra non-printable character I know ^M will show up when ssh -t, ref1, but I don't catch the situation when ssh -t into Centos 7.2(even Centos 6.2 is OK, but no difference between their environment vars). Anyone know about this? Or maybe related to ref2?
$ ssh -t centos72 'echo $HOME' 2>/dev/null|cat -A
^[[?25h^[[0G^[[K^[[?25h^[[0G^[[K/home/user^M$
$ ssh centos72 'echo $HOME' 2>/dev/null|cat -A
/home/user$
$ ssh -t ubuntu1404 'echo $HOME' 2>/dev/null|cat -A
/home/user^M$
$ ssh ubuntu1404 'echo $HOME' 2>/dev/null|cat -A
/home/user$

A: These are control characters for your terminal or VT100 codes. They are needed to make your terminal working with the remote psoudoterminal, to show your prompt and other stuff.
Verbose description of the tags from another SO question and from wikipedia:

*

*CSI ?25h : Shows the cursor.

*CSI n G : Moves the cursor to column n. (not ANSI.SYS)

*CSI n K : Erases part of the line. If n is zero (or missing), clear from cursor to the end of the line. If n is one, clear from cursor to beginning of the line. If n is two, clear entire line. Cursor position does not change.

*and once more the first two.

*^M : Carriage Return (on the end of the line)

These are some basic sanity checks to make sure the terminal is ready. Ubuntu sends them probably only after the query from the local terminal.


text:
Q: Login logout in smarty I have written the header.tpl and login.php file in smarty.  i want to show the logout text if user  is logged  in. otherwise it should show login if user is not logged in.below is the code of login.php
if(isset($_REQUEST['submit']))
    {
        $name=$_REQUEST['name'];
        $pass=$_REQUEST['pass'];
    $rs=mysql_query("select * from form where name='$name'");
    $fetchdata=mysql_fetch_array($rs);
        if($rs)
        {
            $name=$fetchdata['name']
            $_SESSION['name']=$name;
            $name1=$_SESSION['name'];
            //$smarty->assign('name',$_SESSION['name']);
            $smarty->assign('name1',$name1);
            $smarty->display("about.tpl");

        }
        else
        {
            $smarty->display("login.tpl");
        }
    }

below is the header.tpl code
{if $name1!= ''}: Logout{else}login{/if}

it is showing error
Parse error: syntax error, unexpected T_VARIABLE in D:\xampp\htdocs\smarty\login.php on line 29

A: I found a bunch of weird things.

*

*You should escape the name and pass before inserting into sql query. see http://www.php.net/manual/en/function.mysql-real-escape-string.php for more details.

*The php documentation recommend that you should use the MySQLi extension

*I can't see a authentication..I mean you don't use the give password. Is this correct?

*I think mysql_query isn't falsey even when the result is empty. You can solve this with if($fetchdata=mysql_fetch_array($rs)){... instead of if($rs)

*I'm not sure if this would throw an exception but i would write {if {$name1|default:""}!= ''}: Logout{else}login{/if} instead of {if $name1!= ''}: Logout{else}login{/if}

A: This is an old post, but I ran into a similar issue just a couple minutes ago.
I was getting an parse error for the variable: $_smarty_t
I tried different things to make there error go away, but there was nothing obvious.  I confirmed that caching was turned off, but the issue persisted, even after deleting the individual cached file.
Eventually I deleted the entire contents of that directory and refreshed, and the error finally resolved.
This issue occurred with Smarty v3.1.27, as loaded through Composer, smarty/smarty.


text:
Q: 2-d grid nodes are overlapping, when browser window resize i've create a grid of 24x64 nodes where rows are 24 and cols are 64. but the problem is whenever i open the console window nodes are overlapping with each other.
i want to resize all nodes automatically as window size changes can anyone help?
grid.jsx
const Grid = ({ grid }) => {
  return (

      {grid.map((row, rowIdx) => {
        return (

            {row.map((node) => (
              <Node node={node} />
            ))}

        );
      })}

  );
};

node.jsx
const Node = ({ node }) => {
  return (

  );
};

css file
.grid {
  overflow: hidden;
  position: absolute;
  left: 20px;
  align-content: flex-start;
  justify-content: center;
  margin-top: 50px;
}

.cur-row {
  height: 23px;
}

.node {
  width: 23px;
  height: 23px;
  border: 1px solid rgb(175, 216, 248);
  display: inline-block;
}

this is grid when the run the app.
this is the grid when i open the console window
as you can see some nodes are overlapping with other nodes.
i want all the nodes resize according to the window size. can anyone help?

A: You can use both Grid layout and Flexbox layout to achive the following. Below is the demo code using CSS display: grid property.

/* for demo purpose only, ignore this as you already have react code */
let cols = 64;
let rows = 24;
let gridEl = document.querySelector('.grid');

for (let i = 1; i <= 24; i++) {
  gridEl.innerHTML += `<div class="grid-row"></div>`;
}

document.querySelectorAll('.grid-row').forEach(function(item) {
  for (let j = 1; j <= 64; j++) {
    item.innerHTML += `<div class="grid-column"></div>`;
  }
});
:root {
  --grid-container: 1023px;
  --column-size: 23px;
  --column-count: 64;
  --border-color: rgb(175, 216, 248);
}

.grid {
  margin: 20px auto;
  max-width: var(--grid-container);
  overflow: auto;
  /*enable scroll if required for responsive design */
}

.grid-row {
  display: grid;
  grid-template-columns: repeat(var(--column-count), 1fr);
}

.grid-column {
  height: var(--column-size);
  width: var(--column-size);
  border: 1px solid var(--border-color);
}


text:
Q: Join 2 Mongo DB tables with Id and ObjectId My Scenario : I need to join 2 below tables in Mongo DB and condition is
testScenarioId(table 1) = _id (table 2)
Table 1:
{
    "_id" : ObjectId("58516a6838fdb54d744ba070"),
    "_class" : "com.TestResults",
    "testScenarioId" : "581cef861892ad1eb7d124dd",
    "runId" : 314,
    "status" : "passed"
}

Table 2:
{
    "_id" : ObjectId("57f41cb9319ed34079df8a2d"),
    "environment" : "STAGE",
    "component" : "platform",
    "scenarioName" : "ABC-1234",

}

i am able to do if i am joining with same local field and foreign field but not on the above case.

A: Mongodb does not support type coercion in $lookup. So field of type ObjectId can not be looked up with a string type foreign field.
What you need to do is while saving the testScenarioId, you need to store as objectId.
I tried using $type in aggregation but its not supported. So currently here is no way to do it directly in aggregation pipeline.

A: If you want to implement join in 2 collections, then you will be insert "testScenarioId" in ObjectId form.
At that time,you have insert id in string form and "lookup" Aggregation does not support this form of Id.
Reason why ObjectId: when query finds Id from first table (table 1), they will get id in ObjectId form, and after then they will compare id with second table parameter "testScenarioId" which was store in string form, and they will not match and query return null data.


text:
Q: Using UIDropInteractionDelegate and movies Im trying to implement drag and drop photos and videos into my app.
I have made photos work using below code
public func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers:
        [kUTTypeImage as String, kUTTypeMovie as String]) &&
        session.items.count == 1
}

public func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate
    session: UIDropSession) -> UIDropProposal {

    let dropOperation: UIDropOperation?

    if session.canLoadObjects(ofClass: UIImage.self) {
        //Make sure over drop space
    }
    else
    {
        dropOperation = .forbidden
    }

    return UIDropProposal(operation: dropOperation!)
}

public func dropInteraction(_ interaction: UIDropInteraction,
                            performDrop session: UIDropSession) {

    if session.canLoadObjects(ofClass: UIImage.self) {
        session.loadObjects(ofClass: UIImage.self) { (items) in
            if let images = items as? [UIImage] {
                //Do something with the image file
            }
        }
    }
}

As I said photos work perfectly but im unsure what to do about videos (kUTTypeMovie),
what class type is videos in "session.canLoadObjects(ofClass: UIImage.self)"
Thanks

A: You can get an URL to the movie file using the itemProviders loadFileRepresentation like this
for item in session.items {
    if item.itemProvider.hasItemConformingToTypeIdentifier(kUTTypeMovie as String) {
        item.itemProvider.loadFileRepresentation(forTypeIdentifier: kUTTypeMovie as String) { (url, error) in

             // Copy the file to your documents directory before using it

        }
    }
}

Remember to also add kuTTypeMovie to the canHandle function
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers: [kUTTypeMovie as String])
}

A: To add onto @torof's solution i finished the copy part to which he refers in the comment in his code. As file destination i use .cachesDirectory since i don't want to permanently store the file, but rather just for a use in this session, just outside of the callback. This way it gets cleaned up by the OS automatically when space is needed.

session.items.filter { $0.itemProvider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) }.forEach { item in
    item.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { [weak self] (videoURL, error) in
        guard let url = videoURL,
              let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return }
        let destURL = documentsURL.appendingPathComponent(url.lastPathComponent)

        try? FileManager.default.copyItem(at: url, to: destURL)

        // the file is now at destURL
        // you may us it now outside of the callback
    }
}

A: 2022 ... syntax for type identifiers has changed:
func dropInteraction(_ i: UIDropInteraction, canHandle s: UIDropSession) -> Bool {
    guard s.items.count == 1 else { return false }
    return s.hasItemsConforming(
     toTypeIdentifiers: [UTType.image.identifier, UTType.video.identifier])
}

and you need:
import UniformTypeIdentifiers


text:
Q: Discharge lithium ion battery to a specific state of charge I am trying to make a circuit to discharge a 4s battery pack to 30% state of charge to ship it safely.
I will be doing this from time to time and would like to discharge the packs rapidly (around an hour at roughly 10A.)
I figured out the no-load voltage which corresponds to that percentage. I was trying to use the pack voltage (divided,) a voltage reference, and a comparator to check for that low voltage and open the switch.
When the battery is discharging the voltage drop across the battery is significant - almost 1V. If I cut the load at that point, the battery immediately floats back up to the no-load voltage, turning the discharge circuit back on and it gets into a weird switching behavior. I've been using a MOSFET but want to switch to a relay so that I don't have to deal with the extra MOSFET heat, just the heat from my load resistors. With a relay, though, I don't want that rapid switching. Is there a good way to prevent the rapid switching behavior?

A: A Lithium Ion battery has a very flat discharge curve which makes it difficult to determine the state of charge from voltage. The voltage drop "signal" is swamped by the internal resistance of the battery dropping the voltage as you discharge it. This is probably leading to the behaviour you see. When you stop discharge the voltage comes back up retriggering the discharge circuit.
The only places on the charge discharge curves that you can determine the state of charge by voltage is on the upper and lower "knees" where the voltage changes rapidly with state of charge.
If you are discharging the battery for safe shipping you do not need much accuracy for state of charge. Fully charge the battery as determined by the steep voltage rise at the upper knee and then discharge it by timing the discharge, measure the amps, then multiply amps times hours to burn off 70% of the battery capacity.

A:
When the battery is discharging the voltage drop across the battery is
significant,almost 1V. If I cut the load at that point, the battery
immediately floats back up to the no-load voltage, turning the
discharge circuit back on

*

*Add hysteresis to the comparator circuit, so it doesn't turn back on unless the battery voltage rises more than 1 V.

*Make the hysteresis so large that the circuit doesn't turn on at all unless you push a button.
The circuit could look like this:-

simulate this circuit – Schematic created using CircuitLab
When voltage falls below the comparator threshold and its output goes low, D2 pulls the + input down to ~0.6 V, forcing the comparator output to stay low even after the battery voltage goes back up. SW1 (when pressed) pulls the - input down below this voltage to start the discharge. The FET is either fully on or fully off so its power dissipation is low.
If the circuit is powered from the battery as shown then SW1 may not be necessary, since when C1 is fully discharged it should cause the comparator to turn on when the battery is plugged in.

A: Lithium cells are rated and sold at 3.7V because that is the "storage" voltage that is fairly safe and can last for years. I quickly discharge my 2S (2 cells) battery to about 7V when lighting a car tail light bulb then the unloaded voltage is 3.7V per cell.


text:
Q: One datasource for project I'm using wizard to add tables to my project to work with them. Is having just one datasource for project better way? At the moment there is only 5 tables.

POST EDIT
It's so cumbersome and I'm feeling myself going wrong way to use wizard, that makes another one dataset for every table, so I thought about just one dataset for my little application. But as I have little experience with ADO .NET, I hope to get advice here.

A: Perhaps is better to use Entity Framework 4.1 / 4.2

A: I find it's much easier to maintain an application when features of the system are isolated from one another. So in this instance having a dataset, one for each way the system is accessed, would make it easier to maintain.
an example of how this plays out:

*

*a context to search for customers

*a context to allow a customer to place an order

*a context to add a product to a customer's shopping cart

this is probably overkill for a system of 5 tables, but if you can train yourself to think in context specific usages, it makes it much easier to expand and change the system moving forward.

A: If you want to use typed DataSet instead of EF or Linq2Sql just add new DataSet to your project, open it, right click and Add->TableAdapter, add all tables you need.


text:
Q: CPU time in quadruple vs. double precision I am doing some long-term simulations in which I'm trying to achieve the highest possible accuracy in the solution of systems of ODEs. I am trying to find out how much time quadruple (128-bit) precision calculations take versus double (64-bit) precision. I googled around a bit and saw several opinions about it: some say it will take 4 times longer, others 60-70 times... So I decided to take matters in my own hands and I wrote a simple Fortran benchmark program:
program QUAD_TEST

implicit none

integer,parameter  ::  dp = selected_int_kind(15)
integer,parameter  ::  qp = selected_int_kind(33)

integer   ::  cstart_dp,cend_dp,cstart_qp,cend_qp,crate
real      ::  time_dp,time_qp
real(dp)  ::  sum_dp,sqrt_dp,pi_dp,mone_dp,zero_dp
real(qp)  ::  sum_qp,sqrt_qp,pi_qp,mone_qp,zero_qp
integer   ::  i

! ==============================================================================

! == TEST 1. ELEMENTARY OPERATIONS ==
sum_dp = 1._dp
sum_qp = 1._qp
call SYSTEM_CLOCK(count_rate=crate)

write(*,*) 'Testing elementary operations...'

call SYSTEM_CLOCK(count=cstart_dp)
do i=1,50000000
  sum_dp = sum_dp - 1._dp
  sum_dp = sum_dp + 1._dp
  sum_dp = sum_dp*2._dp
  sum_dp = sum_dp/2._dp
end do
call SYSTEM_CLOCK(count=cend_dp)
time_dp = real(cend_dp - cstart_dp)/real(crate)
write(*,*) 'DP sum: ',sum_dp
write(*,*) 'DP time: ',time_dp,' seconds'

call SYSTEM_CLOCK(count=cstart_qp)
do i=1,50000000
  sum_qp = sum_qp - 1._qp
  sum_qp = sum_qp + 1._qp
  sum_qp = sum_qp*2._qp
  sum_qp = sum_qp/2._qp
end do
call SYSTEM_CLOCK(count=cend_qp)
time_qp = real(cend_qp - cstart_qp)/real(crate)
write(*,*) 'QP sum: ',sum_qp
write(*,*) 'QP time: ',time_qp,' seconds'
write(*,*)
write(*,*) 'DP is ',time_qp/time_dp,' times faster.'
write(*,*)

! == TEST 2. SQUARE ROOT ==
sqrt_dp = 2._dp
sqrt_qp = 2._qp

write(*,*) 'Testing square root ...'

call SYSTEM_CLOCK(count=cstart_dp)
do i = 1,10000000
   sqrt_dp = sqrt(sqrt_dp)
   sqrt_dp = 2._dp
end do
call SYSTEM_CLOCK(count=cend_dp)
time_dp = real(cend_dp - cstart_dp)/real(crate)
write(*,*) 'DP sqrt: ',sqrt_dp
write(*,*) 'DP time: ',time_dp,' seconds'

call SYSTEM_CLOCK(count=cstart_qp)
do i = 1,10000000
   sqrt_qp = sqrt(sqrt_qp)
   sqrt_qp = 2._qp
end do
call SYSTEM_CLOCK(count=cend_qp)
time_qp = real(cend_qp - cstart_qp)/real(crate)
write(*,*) 'QP sqrt: ',sqrt_qp
write(*,*) 'QP time: ',time_qp,' seconds'
write(*,*)
write(*,*) 'DP is ',time_qp/time_dp,' times faster.'
write(*,*)

! == TEST 3. TRIGONOMETRIC FUNCTIONS ==
pi_dp = acos(-1._dp); mone_dp = 1._dp; zero_dp = 0._dp
pi_qp = acos(-1._qp); mone_qp = 1._qp; zero_qp = 0._qp

write(*,*) 'Testing trigonometric functions ...'

call SYSTEM_CLOCK(count=cstart_dp)
do i = 1,10000000
    mone_dp = cos(pi_dp)
    zero_dp = sin(pi_dp)
end do
call SYSTEM_CLOCK(count=cend_dp)
time_dp = real(cend_dp - cstart_dp)/real(crate)
write(*,*) 'DP cos: ',mone_dp
write(*,*) 'DP sin: ',zero_dp
write(*,*) 'DP time: ',time_dp,' seconds'

call SYSTEM_CLOCK(count=cstart_qp)
do i = 1,10000000
    mone_qp = cos(pi_qp)
    zero_qp = sin(pi_qp)
end do
call SYSTEM_CLOCK(count=cend_qp)
time_qp = real(cend_qp - cstart_qp)/real(crate)
write(*,*) 'QP cos: ',mone_qp
write(*,*) 'QP sin: ',zero_qp
write(*,*) 'QP time: ',time_qp,' seconds'
write(*,*)
write(*,*) 'DP is ',time_qp/time_dp,' times faster.'
write(*,*)

end program QUAD_TEST

Results of a typical run, after compiling with gfortran 4.8.4, without any optimization flag:
 Testing elementary operations...
 DP sum:    1.0000000000000000
 DP time:   0.572000027      seconds
 QP sum:    1.00000000000000000000000000000000000
 QP time:    4.32299995      seconds

 DP is    7.55769205      times faster.

 Testing square root ...
 DP sqrt:    2.0000000000000000
 DP time:    5.20000011E-02  seconds
 QP sqrt:    2.00000000000000000000000000000000000
 QP time:    2.60700011      seconds

 DP is    50.1346169      times faster.

 Testing trigonometric functions ...
 DP cos:   -1.0000000000000000
 DP sin:    1.2246467991473532E-016
 DP time:    2.79600000      seconds
 QP cos:   -1.00000000000000000000000000000000000
 QP sin:    8.67181013012378102479704402604335225E-0035
 QP time:    5.90199995      seconds

 DP is    2.11087275      times faster.

Something must be going on here. My guess is that sqrt is computed with gfortran through an optimized algorithm, which probably hasn't been implemented for quadruple precision computations. This might not be the case for sin and cos, but why are elementary operations 7.6 times slower in quadruple precision while for trigonometric functions things slow down only by a factor of 2? If the algorithm used for the trigonometric functions would be the same for quad and double precision, I would expect to see a sevenfold increase in CPU time for them too.
What is the average slowdown in scientific calculations when 128-bit precision is used, compared to 64-bit?
I am running this on an Intel i7-4771 @ 3.50GHz.

A: More an extended comment than an answer, but...
Current CPUs provide a lot of hardware acceleration for double precision floating point arithmetic. Some even provide facilities for extended precision.
Beyond that, you are limited to software implementations which are (as you noticed) considerably slower.
However, the exact factor of this slow-down is almost impossible to predict in generic cases.
It depends on your CPU (e.g. which acceleration it has built-in), and on the software stack.
For double-precision you typically use different math-libraries than for quadruple precision, and these might use different algorithms for basic operations.
For a particular operation/algorithm on a given hardware using the same algorithm you can probably derive a number, but this for sure will not be universally true.

A: It's interesting to note that if you change:
sqrt_qp = sqrt(sqrt_qp)
sqrt_qp = 2._qp

to
sqrt_qp = sqrt(2._qp)

the computation will be faster !


text:
Q: Amazon AWS Kinesis Video Boto GetMedia/PutMedia Does anybody know of a complete sample as to how to send video to a kinesis video stream, using boto3 sdk?
This question was asked initially for both both GetMedia and PutMedia. Now I have got this sample code for the GetMedia part:
client = boto3.client('kinesisvideo')
response = client.get_data_endpoint(
    StreamName='my-test-stream',
    APIName='GET_MEDIA'
)
print(response)
endpoint = response.get('DataEndpoint', None)
print("endpoint %s" % endpoint)

if endpoint is not None:
    client2 = boto3.client('kinesis-video-media', endpoint_url=endpoint)
    response = client2.get_media(
        StreamName='my-test-stream',
        StartSelector={
            'StartSelectorType': 'EARLIEST',
        }
    )
    print(response)

    stream = response['Payload'] # botocore.response.StreamingBody object
    while True:
            ret, frame = stream.read()
            print(" stream type ret %s frame %s" % (type(ret), type(frame)))

How do you to the PutMedia? From a previous post "Amazon Kinesis Video GetMedia/PutMedia", it looks like you have to construct your own url request for a PutMedia. Is that the case? If it is, can someone share a complete sample?

A: The code below works.
The code is largely derived from a previous post How to Implement Amazon Kinesis PutMedia Method using PYTHON and Amazon Kinesis Video PutMedia Using Python. Some of the changes are from monitoring how the kinesis video stream c-producer 2.0.2 works.
The same pair of keys are set twice: once in the way for boto, another by the two special environment variables at the beginning of the code.
your_env_access_key_var = 'AWS_KVS_USER_ACCESS_KEY'
your_env_secret_key_var = 'AWS_KVS_USER_SECRET_KEY'
your_stream_name = 'my-video-stream-test'

def get_endpoint_boto():
    import boto3

    client = boto3.client('kinesisvideo')
    response = client.get_data_endpoint(
        StreamName=your_stream_name,
        APIName='PUT_MEDIA'
    )
    pp.pprint(response)
    endpoint = response.get('DataEndpoint', None)
    print("endpoint %s" % endpoint)
    if endpoint is None:
        raise Exception("endpoint none")
    return endpoint

def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

def get_signature_key(key, date_stamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning

def get_host_from_endpoint(endpoint):
    # u'https://s-123abc78.kinesisvideo.us-east-2.amazonaws.com'
    if not endpoint.startswith('https://'):
        return None
    retv = endpoint[len('https://'):]
    return str(retv)

def get_region_from_endpoint(endpoint):
    # u'https://s-123abc78.kinesisvideo.us-east-2.amazonaws.com'
    if not endpoint.startswith('https://'):
        return None
    retv = endpoint[len('https://'):].split('.')[2]
    return str(retv)

class gen_request_parameters:
    def __init__(self):
        self._data = ''
        if True:
            localfile = '6-step_example.webm.360p.webm' # upload ok
            #localfile = 'big-buck-bunny_trailer.webm' # error fragment duration over limit
            with open(localfile, 'rb') as image:
                request_parameters = image.read()
                self._data = request_parameters
        self._pointer = 0
        self._size = len(self._data)
    def __iter__(self):
        return self
    def next(self):
        if self._pointer >= self._size:
            raise StopIteration  # signals "the end"
        left = self._size - self._pointer
        chunksz = 16000
        if left < 16000:
            chunksz = left
        pointer_start = self._pointer
        self._pointer += chunksz
        print("Data: chunk size %d" % chunksz)
        return self._data[pointer_start:self._pointer]

# ************* REQUEST VALUES *************
endpoint = get_endpoint_boto()

method = 'POST'
service = 'kinesisvideo'
host = get_host_from_endpoint(endpoint)
region = get_region_from_endpoint(endpoint)
##endpoint = 'https://**<the endpoint you get with get_data_endpoint>**/PutMedia'

endpoint += '/putMedia'

# POST requests use a content type header. For DynamoDB,
# the content is JSON.
content_type = 'application/json'
start_tmstp = repr(time.time())

# Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = None # '*************************'
secret_key = None # '*************************'
while True: # scope
    k = os.getenv(your_env_access_key_var)
    if k is not None and type(k) is str and k.startswith('AKIA5'):
        access_key = k
    k = os.getenv(your_env_secret_key_var)
    if k is not None and type(k) is str and len(k) > 4:
        secret_key = k
    break # scope
if access_key is None or secret_key is None:
    print('No access key is available.')
    sys.exit()

# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
date_stamp = t.strftime('%Y%m%d')  # Date w/o time, used in credential scope

# ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

# Step 1 is to define the verb (GET, POST, etc.)--already done.

# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
##canonical_uri = '/'
canonical_uri = '/putMedia' #endpoint[len('https://'):]

## Step 3: Create the canonical query string. In this example, request
# parameters are passed in the body of the request and the query string
# is blank.
canonical_querystring = ''

# Step 4: Create the canonical headers. Header names must be trimmed
# and lowercase, and sorted in code point order from low to high.
# Note that there is a trailing \n.
#'host:' + host + '\n' +
canonical_headers = ''
#canonical_headers += 'Accept: */*\r\n'
canonical_headers += 'connection:keep-alive\n'
canonical_headers += 'content-type:application/json\n'
canonical_headers += 'host:' + host + '\n'
canonical_headers += 'transfer-encoding:chunked\n'
#canonical_headers += 'x-amz-content-sha256: ' + 'UNSIGNED-PAYLOAD' + '\r\n'
canonical_headers += 'user-agent:AWS-SDK-KVS/2.0.2 GCC/7.4.0 Linux/4.15.0-46-generic x86_64\n'
canonical_headers += 'x-amz-date:' + amz_date + '\n'
canonical_headers += 'x-amzn-fragment-acknowledgment-required:1\n'
canonical_headers += 'x-amzn-fragment-timecode-type:ABSOLUTE\n'
canonical_headers += 'x-amzn-producer-start-timestamp:' + start_tmstp + '\n'
canonical_headers += 'x-amzn-stream-name:' + your_stream_name + '\n'

# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers include those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
# For DynamoDB, content-type and x-amz-target are also required.
#
#in original sample  after x-amz-date :  + 'x-amz-target;'
signed_headers = 'connection;content-type;host;transfer-encoding;user-agent;'
signed_headers += 'x-amz-date;x-amzn-fragment-acknowledgment-required;'
signed_headers += 'x-amzn-fragment-timecode-type;x-amzn-producer-start-timestamp;x-amzn-stream-name'

# Step 6: Create payload hash. In this example, the payload (body of
# the request) contains the request parameters.

# Step 7: Combine elements to create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers
canonical_request += '\n'
canonical_request += hashlib.sha256(''.encode('utf-8')).hexdigest()

# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(
    canonical_request.encode('utf-8')).hexdigest()

# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = get_signature_key(secret_key, date_stamp, region, service)

# Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
                     hashlib.sha256).hexdigest()

# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# Put the signature information in a header named Authorization.
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', '
authorization_header += 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

# # Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {
    'Accept': '*/*',
    'Authorization': authorization_header,
    'connection': 'keep-alive',
    'content-type': content_type,
    #'host': host,
    'transfer-encoding': 'chunked',
    # 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD',
    'user-agent': 'AWS-SDK-KVS/2.0.2 GCC/7.4.0 Linux/4.15.0-46-generic x86_64',
    'x-amz-date': amz_date,
    'x-amzn-fragment-acknowledgment-required': '1',
    'x-amzn-fragment-timecode-type': 'ABSOLUTE',
    'x-amzn-producer-start-timestamp': start_tmstp,
    'x-amzn-stream-name': your_stream_name,
    'Expect': '100-continue'
}

# ************* SEND THE REQUEST *************
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + endpoint)

r = requests.post(endpoint, data=gen_request_parameters(), headers=headers)

print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)


text:
Q: How to dynamically set window titles in Tmux? I want to set the title of Tmux windows dynamically to the path of the first pane. How do I set a title dynamically?

A: Okay, so Tmux actually sets the window title based off the active pane title, you need to set the pane title and it will be used as the window title. These instructions are for fish, feel free to add examples for bash and zsh etc.
Create a new function:
function tmux_pane_title --on-variable PWD
    printf "\033k$PWD\033\\"
end

Then put this in your config.fish:
tmux_pane_title

source: https://github.com/fish-shell/fish-shell/issues/981
source: man tmux NAMES AND TITLES section


text:
Q: Does floating-point use a key in hashtable? I know that floating-point values cannot be compared by ==. I have made a custom comparison function like this.
auto isEqual = [](const double& a, const double& b) {
  return fabs(a-b) <= numeric_limits<double>::epsilon();
};

I would like to know how I modify the unordered map to be worked as I expected.
auto isEqual = [](const double& a, const double& b) {
  return fabs(a-b) <= numeric_limits<double>::epsilon();
};

unordered_map<double, int, hash<double>, decltype(isEqual)> m(0, hash<double>(), isEqual);
m[1/(double)3]++;
cout << m[1-2/(double)3] << endl; // expected 1, but zero

// -----------------------------

auto comp = [&](const double& a, const double& b) {
  if (isEqual(a, b)) return false;
  return a < b;
};

map<double, int, decltype(comp)> m2(comp);
m2[1/(double)3]++;
cout << m2[1-2/(double)3] << endl;  // expected and answered 1

A: It is essentially impossible to modify an unordered_map to use floating-point values that contain different rounding errors as keys.
Customizing the equality comparison alone is insufficient because it is merely used to distinguish values that are mapped to the same bucket by the hash function. Different floating-point values generally hash to different buckets, even if they differ only by the tiniest of rounding errors. Therefore, one must also customize the hash function.
However, then the requirement for the hash function would be that it map floating-point values that are different but that you would like to consider as equal to the same bucket. In general, this is impossible because, if you want to consider any two very close numbers as equal, say numbers that are so close that they are adjacent in the floating-point format, then transitivity requires the hash function to map all numbers to one bucket. That is, since zero and the smallest positive representable number must map to the same bucket, and the smallest and second smallest positive representable numbers must map to the same bucket, then zero and the second smallest positive representable number must map to the same bucket. Similarly, the third smallest number must represent to the same bucket as the second smallest and therefore to the same bucket as zero. And so on for the fourth and fifth. This creates a chain that continues for all numbers: They must all map to the same bucket.
Therefore, no hash function can serve to implement a non-degenerate map for floating-point numbers that considers close numbers as equal.
In special situations, it is possible to implement a reasonable hash for certain sets of numbers. For example, if it is known that all the floating-point values represent a number of cents, and that the floating-point numbers never contain accumulated rounding errors that reach or exceed half a cent, then each value can be rounded to the nearest cent (or the representable value nearest that) before hashing. Note that the domain of values in this case is really a discrete set, such as a set of fixed-point numbers, not a continuous set such as the set of real numbers that floating-point arithmetic is intended to approximate. In this case, the only modification that is needed is to quantize the floating-point value (round it to the nearest member of the set) before inserting it into the map. No custom hash function or equality comparison is needed.


text:
Q: PHP 7.0 STRPOS not functioning as expected So, I was trying to use strpos to test if a string existed in a variable, but in all my attempts to make the if statement work, it was not succeeding, so I went about outputting the string and trying to find the point where strpos detected it, but it was not though it was clearly there! In this case I am searching an SMTP error output for the Gmail SMTP error code.I know how to fix the error, but I want my system to be able to parse smtp errors and report them to my users...
PHP Code:
$Request = RequestPasswordReset($_POST["email"]);
echo $Request;
echo "
Position of Error Code: " . strpos($Request, "gsmtp SMTP code: 550");
die();
if($Request === "SUCCESS") {
    DisplayError("Password Reset Successful", "We have sent a email that contains a link to reset your password.", "/account/resetpassword.php");
} else if($Request === "USER_NOT_FOUND") {
    DisplayError("Password Reset Request Failed", "The specified email is not tied to any accounts in our system.", "/account/resetpassword.php");
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {
    DisplayError("Password Reset Request Failed", "The mail was blocked by our relay due to IPs being not whitelisted.", "/account/resetpassword.php");
} else {
    DisplayError("Password Reset Request Failed", "The request failed for an unknown reason.", "/account/resetpassword.php");
}

Text Output:
It does actually repeat itself, I echoed out the $Request twice and it did the following twice exactly

The following From address failed: XXXXXXX : MAIL FROM command failed,Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp ,550,5.7.1SMTP server error: MAIL FROM command failed Detail: Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp SMTP code: 550 Additional SMTP info: 5.7.1Position of Error Code:

(EDIT) Reset Password Request Function:
function RequestPasswordReset($Email) {
// Try to Get User
$User = GetUser_Email($Email);

// Does user exist?
if($User === "NOT_FOUND") {
  return "USER_NOT_FOUND";
}

// Generate Link To Send with Email
$Link = GeneratePasswordResetLink();
$SendEmail = SendPasswordReset($User["Email"], $User["FirstName"] . $User["LastName"], $Link);

if($SendEmail !== "SUCCESS") {
  return $SendEmail;
} else {
  // WHAT IF MYSQL FAILS????? ~~~~~~~~~~~~~~~ NEED  SOLOUTION
  $PDO_Connection = CreateMySQLConnection();
  $PDO_CMD = $PDO_Connection -> prepare("UPDATE accounts SET ResetPassword=? WHERE Email=?");
    $PDO_CMD -> execute(array($Link, $User["Email"]));
  return "SUCCESS";
}
}

(EDIT) Send Password Reset Function:
$User = GetUser_ResetID($resetID);

$mail = CreateSMTPConnection();
$mail->AddAddress($targetAddress, $targetName);       // Add a recipient

$mail->IsHTML(true);                                  // Set email format to HTML
$mail->Subject = 'LitenUp Password Reset';
$mail->Body    = str_replace("https://mylitenup.net/account/resetpassword.php?ID=", ("https://mylitenup.net/account/resetpassword.php?ID=" . $resetID), file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/php/mailer/documents/resetpassword.html"));
$mail->AltBody = 'Reset Your Password: https://mylitenup.net/account/resetpassword.php?ID=' . $resetID;
$mail->XMailer = 'LitenUp Mailer';
$mail->XPriority = '1';

  try{
    $mail->send();
    return "SUCCESS";
  } catch (phpmailerException $e) {
    return $e->errorMessage();
  } catch (\Exception $e) {
    return $e->getMessage();
  }

(EDIT): I tried mb_strpos, but it is not working, so if that is what will work, why is it not working for me? I did mb_strpos($Request, "gsmtp SMTP code: 550");, but after execution it echos the request, but the Position of Error Code: line does not get echoed.
(Update 1): I really apologize for the delay, in a worst case I will extend this again with a bounty. However, you guys were right! When I first had the error, I outputted it and just copied the line "gsmtp SMTP code: 550", but after doing the  tag there appears to be a new line of some sort. You can see in the  that the line should be something more like "gsmtp" +  + " SMTP code: 550", but I am not sure what the line break should be. I tried  and \n.

A: The best solution would be to take the time to isolate exactly what character(s) is in that white-space.
Until you do that, you can just use regex to gloss over whatever is in there.
Change:
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {

to:
} elseif(preg_match("/gsmtp\s+SMTP\s+code:\s+550/",$Request)) {

A: My best guess:
You're outputting to HTML, so it's possible that your CRLFs/LFs are rendering as spaces. I'd enclose your echo statements with
...
 tags to see if it's the case. strpos would fail because you're searching for a space character where it's actually a CRLF/LF.


text:
Q: react-chartjs-2 Radar Component My Radar component hasnt ticks:{stepSize} property. Max is 5 and min is 1 but radar go up to 2. And I want it to jump one by one. more space between the triangles
i

nterface LineProps {
  options: ChartOptions<"radar">;
  data: ChartData<"radar">;
}

interface PropsComponent {
  labels: string[];
  data: number[];
}

interface PropsComponent {
  labels: string[];
  data: number[];
}
const Component = ({ labels, data }: PropsComponent) => {
  const Props: LineProps = {
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top",
        },
      },
      scales: {
        ticks: {
          beginAtZero: true,
          max: 9,
          min: 1,
        },
      },
    },
    data: {
      datasets: [
        {
          label: "Datos",
          data: data,
          borderColor: "red",
          backgroundColor: "red",
        },
      ],
      labels: labels,
    },
  };

labels = [criterion1,criterion2,criterion3]
values = [1,2,5]


text:
Q: No borders in table in org-mode This is how I wrote my table in org-mode:
| col1 | col2 | col3 |
|------+------+------|
| val1 | val2 | val3 |
| val4 | val5 | val6 |

This is the output I'm getting in org-export-as-pdf :

What I want is the borders for the table. The org-mode version I'm
using is 7.9.3f.
UPDATE:
With #+ATTR_LaTeX: align=|c|c|c|, I get the follwing table:

UPDATE:
Solved that using putting horizontal lines on top and below of the table using C-u C-c - and C-c - respectively.

A: If you want vertical lines, you need to specify it, hence something like:
#+ATTR_LaTeX: align=|c|c|c|

in your old version of Org mode, or:
#+ATTR_LaTeX: :align |c|c|c|

in Org mode 8.