text:
Q: callback vs generator based design I'd like to get your advice for a design. I've got an Oven controlling the temperature and I'm doing some temperature dependent measurements. I'm basically setting the temperature, measure some stuff and move on.
I came up with two designs, simplified of course, which are shown below. The first one uses a callback based approach:
class Oven(object):
    # ... some methods
    def step_temperature(start, stop, num, rate, callback):
        temperatures = np.linspace(start, stop, num)
        for t in temperatures:
            self.temperature = t, rate # sweep to temperature with given rate
            self._wait_for_stability() # wait until temperature is reached.
            callback(t)                # execute the measurement
# Use Case
oven = Oven()
oven.step_temperature(start=20, stop=200, num=10, rate=1, callback=measure_stuff)

The second design is a generator based design
class Oven(object):
    # ... some methods

    def step_temperature(start, stop, num, rate):
        temperatures = np.linspace(start, stop, num)
        for t in temperatures:
            self.temperature = t, rate
            self._wait_for_stability()
            yield t
# Use Case
oven = Oven()
for t in oven.step_temperature(start=20, stop=200, num=10, rate=1):
    measure_stuff(t)

I'm tending towards the second design, but I'm interrested in your suggestions. If there is a even better way don't hesitate to tell me.

A: @P3trus.  I recently answered a very similar Python "yield versus callback" question on StackExchange's CodeReview.  If you want to read it, here's a link but I'll summarize:
There are three common patterns used to solve the "report feedback" requirement:

*

*yield

*a callback function

*inline, hard-coded feedback

Both yield and callbacks allow you to separate the presentation details of UI/IO from the model or computation code.  This is good.  Both work well.
If you go with Python's yield, ensure you understand iterables and generators well, since several languages implement a yield keyword but have subtle implementation differences that might surprise you if, for example, you're used to C#'s yield. Here's a reference on that -- it's subtle but worth reading. Essentially, in Python when your function yields, it returns a generator which can be usefully assigned to a variable, capturing iteration to that point, but you may or may not want to do that.  Don't let that scare you; yield is good.
Callbacks do have a nice advantage in that they allow communication back to the caller (in the model or computational code) which can be used to pause or halt processing or otherwise send a message to the model.  This is a nice separation of duties and it allows communication that may be more difficult if you use yield.  Or maybe not.  There is always a way.  :)
For example, while updating the reported temperature the callback can also monitor buttons or keys and return a value to the caller which could indicate, for example, that the user wants to abort processing and this doesn't pollute the model with awareness of specific UI or IO.
So instead of just:
callback(t)

You can let callback do its temperature reporting job but also listen to what it may have collected from the user, such as:
if callback(t) == ABORT_BUTTON_PRESSED:
    self.shutdown  # or whatever

Hope this helps.

A: If you occasionally do different stuff with t per call of step_temperature, (like, you call it, and some of the results, you do one thing with, while some you do another with), you'd want the generator version. If every time you call step_temperature, you want the same thing done to every item, and no differing computation between, I'd use the callback version. That way anyone who uses your code doesn't have to know when to call their processing function for t.


text:
Q: Removing hidden data and "personal information" from '.doc' , '.docx' and '.pptx' documents Hi I am trying to remove the 'hidden data' and personal information set for '.doc, .docx, .pptx' documments through powershell :
HEre is the powershell script which I have written for the same :
$path = "C:\Users\anisjain\Documents\GRR Production\HiddenProrerties"
Add-Type -AssemblyName Microsoft.Office.Interop.Word
$xlRemoveDocType = "Microsoft.Office.Interop.xlRDIRemovePersonalInformation" -as [type]
$wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
$objword = New-Object -ComObject word.application

foreach($obj in $wordFiles)
{
$documents = $MSWord.Documents.Open($obj.fullname)
"Removing document information from $obj"
$documents.RemoveDocumentInformation($xlRemoveDocType::xlRDIRemovePersonalInformation)
$documents.Save()
$objword.documents.close()
}
$objword.Quit()

This however, doesnt work. Can someone please tell me where am i going wrong?
and if there is some other way of doing it. I have around 2000 records from which i wish to remove the 'hidden document information'. Thanks in advance.

A: here's the script that works for me, after some googling/copying/modifying
$path = "d:\rubbish\myfolder\"
Add-Type -AssemblyName Microsoft.Office.Interop.Word
$WdRemoveDocType = "Microsoft.Office.Interop.Word.WdRemoveDocInfoType" -as [type]
$wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
$objword = New-Object -ComObject word.application
$objword.visible = $false

foreach($obj in $wordFiles)
{
    $documents = $objword.Documents.Open($obj.fullname)
    "Removing document information from $obj"
    # WdRemoveDocInfoType Enumeration Reference
    # http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdremovedocinfotype(v=office.14).aspx
    # 99 = WdRDIAll
    #$documents.RemoveDocumentInformation(99)
    $documents.RemoveDocumentInformation($WdRemoveDocType::wdRDIAll)
    $documents.Save()
    $objword.documents.close()
}
$objword.Quit()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing List elements in Java Please ignore any beginner mistakes if I make. Following is my issue:
I have a class Item :
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "item")
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
//@ManyToOne
private Long id;
private String stream_item_key;
private String stream_item_date;
private String channel;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "item_workflow", joinColumns = @JoinColumn(name = "item_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "workflow_id", referencedColumnName = "id"))
private List<Workflow> workflow;

Workflow is another class and Workflow has the following class members:
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String actor;
    private String assignee;
    private String date;
    private String team;
    private String action;

I have used JPA to join item and workflow and I am able to see the complete extract of the data. However in a different method I am trying to extract only Item.stream_item_date, Workflow.Actor and Workflow.date
I am able to extract Item.stream_item_date using the getStream_item_date() accessor but I am not sure how to access the List elements. I have researched Stackoverflow and I could not find any answers, all of them led to update index and other things. I am not sure if this is the right way to do it?
Thanks in advance for your answers!

A: Thanks for the answer @JB Nizet
Item items = this.getQueryOne();
// getQueryOne() returns the Item object
for (Workflow workflow: items.getWorkflow()) {
   System.out.println(workflow.getActor());
   System.out.println(workflow.getDate());
}

A:    for(Iterator<?>ui=Item.getWorkflow().iterator()ui.hasNext();){
         Workflow temp= (Workflow) ui.next();
           System.out.print(temp.getActor()); }


text:
Q: ObjectMapper.readvalue in json In object mapper class am getting JsonParseException when i pass parameter as "abc,asd"(for Junit test purpose) . Please clarify why am getting this exception.
What value it will accept it for further processing.
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap> listM=mapper .readValue("abc,asd",ArrayList.class);
for (Iterator iterator = listM.iterator(); iterator.hasNext();) {
                LinkedHashMap linkedMap = (LinkedHashMap) iterator.next();
syso("linkedMap .get(methodname).get(0)")

A: You're getting this exception because abc,asd is not a valid JSON. JSON is a Javascript Object that basically has key and value. Example:
{"abc":"abc"}
And can get a List of these:
[{"abc":"abc"}, {"asd":"asd"}]
So, a valid code would be:
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap> listM = mapper.readValue("[{\"abc\":\"abc\"}, {\"asd\":\"asd\"}]", ArrayList.class);
    for (Iterator iterator = listM.iterator(); iterator.hasNext();) {
        LinkedHashMap linkedMap = (LinkedHashMap) iterator.next();
        System.out.println(linkedMap);
    }


text:
Q: Woocommerce hook run after an Order been created through REST API I'm building a plugin that needs to update data after order creation! I have succeeded in doing that on the website but not in the REST API
What I have done is using woocommerce_thankyou that working fine after checkout through the website but not the REST API too!!
So how to do the same function below after Creating an Order through WooCommerce REST API!!
add_action('woocommerce_thankyou', 'edit_stock_metadata', 10, 1);
function edit_stock_metadata($order_id)
{

    if (!$order_id)
        return;

    // Getting an instance of the order object
    $order = wc_get_order($order_id);

    // iterating through each order items (getting product ID and the product object)
    // (work for simple and variable products)
    foreach ($order->get_items() as $item_id => $item) {

        if ($item['variation_id'] > 0) {
            $product_id = $item['variation_id']; // variable product
            $variation = new WC_Product_Variation($product_id);
            $stock_qty = intval($variation->get_meta('_stock_multiplier'));
            $item_quantity  = $item->get_quantity(); // Get the item quantity
            $variation->update_meta_data('_stock_multiplier', ($stock_qty - $item_quantity));
            $variation->save();
        }
    }
}


text:
Q: NullReferenceException Object reference not set to an instance of an object Unity Есть класс WorldGenerator со вложеным циклом. Ошибка возникает на 22 строке
GameObject block = Instantiate(DB.blocks[0].gObj, new Vector3(x, y, 1), Quaternion.identity);
Полный текст ошибки:

NullReferenceException: Object reference not set to an instance of an object
  WorldGanerator.Generate (System.Int32 size) (at Assets/Scripts/WorldGanerator.cs:22)"

public class WorldGanerator : MonoBehaviour
{
    public GameObject PlayerInventoryPanel;
    public GameObject Player;
    DataBase DB;

    private void Start()
    {
        DB = gameObject.AddComponent<DataBase>();
    }

    public void Generate(int size)
    {
        for(int y = -size/2; y < size; y++)
        {
            for (int x = -size/2; x < size; x++)
            {
                GameObject block = Instantiate(DB.blocks[0].gObj, new Vector3(x, y, 1), Quaternion.identity);
                block.GetComponent<SpriteRenderer>().sprite = DB.blocks[0].Img;
            }
        }

        Instantiate(Player, Vector3.zero, Quaternion.identity);
    }
}

Функция Generate вызывается из класса Game в Start
public class Game : MonoBehaviour
{
    DataBase DB;
    WorldGanerator WG;

    public GameObject PlayerInventoryPanel;

    private void Start()
    {
        DB = gameObject.AddComponent<DataBase>();
        WG = gameObject.AddComponent<WorldGanerator>();

        DB.Setup();
        WG.Generate(10);

        PlayerInventoryPanel.SetActive(false);
    }
}

A: В ошибке прописано, что DB имеет значение null.  Почему у вас AddComponent()? AddComponent добавляет компонент GameObject, используйте GetComponent() чтобы получить компонент. В методе Start вы не присваиваете какое либо значение переменной, DB а наоборот. Поэтому DB это null и соответственно появляется ошибка. Поэтому заменитель AddComponent на GetComponent.


text:
Q: Polymer iron-list not updating view on dynamic add I am using Polymer 1.7.0 and Angular2 to build a app. I created a custom Polymer element to wrap the iron-list template in order to be able to use it with Angular2 but i have a problem when it comes to dynamicly adding items to the iron-list.
The add function modifies the items array but it doesnt render the new element even if i am triggering the iron-resize event after modifying the items array.
If i delete a item first, and then try to add a element, then it gets rendered.
This is the polymer element i use:

<dom-module id="role-users-list">
  <template>

    <iron-media-query query="(min-width: 600px)" on-query-matches-changed="queryValueChanged" query-matches="{{wide}}"></iron-media-query>
    <iron-list items="{{items}}" class="test" style="height:85%">
        <template>
            <paper-card class="verticalJustified">

                  <paper-icon-button class="cardIcons" icon="group-work"></paper-icon-button>

                      {{item.fullName}}
                      <template is="dom-if" if="{{item.direct}}">
                        User associated directly
                      </template>
                      <template is="dom-if" if="{{!item.direct}}">
                        Role granted through {{item.groupName}}
                      </template>

                <template is="dom-if" if="{{item.direct}}">

                      <paper-icon-button class="cardIcons" icon="delete" target-user="{{item.username}}" on-tap="onDelete" (click)="deleteUser(user)"></paper-icon-button>

                </template>

            </paper-card>
        </template>
    </iron-list>
  </template>

</dom-module>

After adding or removing a element i call the updateIronList function to trigger the rendering with the iron-resize event.
PS: The add functionality is in the parent Angular2 component where i modify the items array.
The only difference i could notice was that since the delete button is inside the polymer custom element, it causes it to focus that item when its clicked.
If i didnt make myself understood, ask and i will clarify.

A: I fixed my issue by updating the updateIronList function to:
updateIronList:function(){
        let ironListElem = this._nodes.filter(function(value){return value.localName === "iron-list"})[0];
        ironListElem.fire("iron-resize");
        ironListElem._virtualCount = (this.items.length <= 20) ? this.items.length : 20;
      },

It seems the issue was caused by the fact that when the items array length changed, iron-list didnt automaticly update the number of items displayed.


text:
Q: Formatting hashtable from a single column of a pscustomobject I am having trouble pulling key values from a hashtable JSON Object
$personnelresult = Invoke-RestMethod -Method Get www.url.com -WebSession $currentsession
               # Create Table Format
$personnelresult = @{expression={$_.id};Label="ID";Width=37},
                   @{expression={$_.name};Label="Name";Width=32},
                   @{expression={$_.Atributes};Label="Attributes";Width=128}
               # Print Results
Write-Host "----------------" -ForegroundColor Green
Write-Host "Personnel report" -ForegroundColor Green
Write-Host "----------------" -ForegroundColor Green
$personnelresult.details |
Format-Table $personnelresult
Write-Host "----------------------" -ForegroundColor Yellow
Write-Host "Count is limited to 15" -ForegroundColor Yellow
Write-Host "----------------------" -ForegroundColor Yellow
               # End Results

I am getting this:
ID        Name       Atrributes
----      ----       ----------
245       Joe        @{age=23; weight=200; height=73}
423       Brendan    @{age=25; weight=173; height=45}
213       Ashley     @{age=28; weight=350; height=20}

What I want is this or something similar
ID        Name       Attributes
----      ----       ----------
245       Joe        age=23 weight=200 height=73
423       Brendan    age=25 weight=173 height=45
213       Ashley     age=28 weight=350 height=20

What I've tried:
I placed this before my table
$personnelresult.details.Attributes = $personnelresult.details.Attributes |
ForEach-Object {
Foreach($p in psobject.properties)
{
    $p.Name
}
}

And, I'll get
ID        Name       Atrributes
----      ----       ----------
245       Joe        {System.Int32 age=23, System.Int32 weight=200, System.Int32 height=73}
423       Brendan    {System.Int32 age=25, System.Int32 weight=173, System.Int32 height=45}
213       Ashley     {System.Int32 age=28, System.Int32 weight=350, System.Int32 height=20}

If there is a better practice or suggestion on handling this data let me know. Additionally, I am dealing with much longer strings than this in the original script. The idea is to show all this information on a single ID in the console.

A: Well, if the idea is to have everything in one ID, you can do this:
$personnelresult = @{e={$_.id};l="ID";Width=37},
                   @{e={$_.name};l="Name";Width=32},
                   @{e={$_.Atributes.age};l="Age";Width=32},
                   @{e={$_.Atributes.weight};l="Weight";Width=32},
                   @{e={$_.Atributes.height};l="Height";Width=32}

That would still get everything on 1 line and leave you with a better way to manipulate the data later on in the pipeline.


text:
Q: how to create a timer- and show it in the canvas I got a canvas and bitmaps in the game that I build, and I wanted to add a timer.
However, all the tutorials that I saw used TextView. In my app, I can't see the TextView since I have a Canvas and Bitmaps above them.
How can I create a timer although this problem.
Thanks! This is the code:
while(pressed!=true){
            if (!holder.getSurface().isValid())
                continue;
            Canvas c= holder.lockCanvas();
            c.drawBitmap(galaxy, 30, 0, null);
            c.drawBitmap(player, x-(player.getWidth()/2), y-(player.getHeight()/2), null);
            c.drawText("2:34", 30, 60, timerpaint);
            holder.unlockCanvasAndPost(c);
        }


text:
Q: selenium sendkeys doesn't function Good morning,
I have a problem in java using the command sendKeys with the libraries of SELENIUM.
The text field ,in question, is visible in the window only when you scroll down to see it.
var element = driver.FindElement(By.Xpath("…"));
element.SendKeys("blah");

So, when the text field is visible in the window the message "blah" is sent to the text field element without any problem.
Instead ,when the text field element is not visible in the window ,because I don't scroll down it, the message "blah" isn't sent to the text field.
How can I solve this problem?
I would like to send the message "blah" to the text field element also when it doesn't appear in the window .
How I can I do it?

A: use executeScript to scroll the element into view.
driver.executeScript("arguments[0].scrollIntoView();",element);
element.sendKeys("blah");

A: You can use Actions moveToElement Method for doing things like these

public Actions moveToElement(WebElement toElement)
Moves the mouse
   to the middle of the element. The element is scrolled into view and
  its location is calculated using getBoundingClientRect.

new Actions(driver).moveToElement(element).build().perform();
element.SendKeys("blah");

A: If you can't set text using standart SendKeys method you can try ExecuteScript (if problem really in SendKeys and not in your selector =)). Smth like:
webdriver.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");


text:
Q: loading an iframe dynamically. Im trying to load an iframe onto a container dynamically.
there are two buttons a and b, on clicking each of them a different url should load onto the iframe.
I have tried-
1.using two different containers instead of one as shown below..during
   which browser crashes.
2. i was not able to switch the content inside the container by using dom.clear.
3. should i consider using a different xtype?. since container positions the iframe right on the spot where i wanted it to.
Ext.define('xxxxxx', {
    extend: 'yyyyy',
    width: '100%',
    height: 125,
    renderTo: Ext.getBody(),
    items: [{
        xtype: 'radiogroup',
        columns: 2,
        width: 400,
        horizontal: true,
        name:'canvas',
        items: [
                        {
                            boxLabel: 'a',
                            id: 'i1',
                            inputValue: 'i1',
                            handler: function () {
                            var iframe = new Ext.ux.IFrame({
                                src: 'https://www.sencha.com',
                                title: 'Hello',
                                width: "100%",
                                height: 1400,
                                renderTo: 'canvas'
                            });

                        }
                    },
                    {
                        boxLabel: 'b',
                        id: 'i2',
                        inputValue: 'i2',
                        handler: function () {
                        var iframe = new Ext.ux.IFrame({
    src: 'https://www.sencha.com/web-application-lifecycle-management-sencha-platform/',
                                width: "100%",
                                height: 1400,
                                renderTo: 'canvas'
                            });
                        }
                    }
            ]
},
{
    xtype: 'container',
    name: 'somename',
    id: 'canvas',
}]

});

A: I had to destroy each of the iframe objects that were created.
This could dynamically load iframe source as long as it wanted.
handler: function () {

 if (iframe != undefined)
   {
       iframe.destroy();
    }
var iframe = new Ext.ux.IFrame({

         src: 'https://www.sencha.com/web-application-lifecycle-management-sencha-platform/',
         width: "100%",
         height: 1400,
         renderTo: 'canvas'

    });
}


text:
Q: Powershell command with where clause coming from variable I have an issue while working with where clause when using variable for that purpose. My where clause is dynamic thus I worked out that way:
$server_FS_exclusions = @("print$","prnproc$","Scripts$","Logs$")
foreach ($exc in $server_FS_exclusions) {$exc_where += "(`$_.Name -ne '$exc') -and "}
$where = $exc_where.Substring(0,$exc_where.LastIndexOf(" -and "))

Get-WmiObject -Query 'SELECT * FROM Win32_Share Where Type=0' -ComputerName XYZ | where {$where}

Unfortunatelly this does not work as expected but does no throw any error. It behave like where clause does not exist or not match conditions.
However when I write the same command to console and get the output
Write-Host  "Get-WmiObject -Query 'SELECT * FROM Win32_Share Where Type=0' -ComputerName XYZ | where {$where}"

and finally use that directly in console it works perfectly.
Get-WmiObject -Query 'SELECT * FROM Win32_Share Where Type=0' -ComputerName XYZ | where {($_.Name -ne 'print$') -and ($_.Name -ne 'prnproc$') -and ($_.Name -ne 'Scripts$') -and ($_.Name -ne 'Logs$')}

I guessing the issue might be related to quoting strings but I'm not sure how I should deal with this.
Any help appreciated :)


text:
Q: Export method/function in react native export { width as responsiveHeight } from "react-native-responsive-dimensions";

I want to export responsiveHeight with name width. What is correct way to do this? As this is not working.

A: Your syntax is opposite. You want to get responsiveHeight as width.
Try this
export { responsiveHeight as width } from "react-native-responsive-dimensions";

A: You're actually doing the opposite, you are taking your width function and add it an alias called responsiveHeight, so you need to do this:
export { responsiveHeight } from "react-native-responsive-dimensions";

just as simple as that, export width in that way, it should work with no issue.

A: Try This One.
import React from "react";
import {responsive} from "react-native-responsive-ui";

@responsive
export default class Debug extends React.Component {
    render() {
        const {width, height} = this.props.window;
        console.log(`New window dimensions: ${width}x${height}`);
        return null;
    }
}


text:
Q: Accessing url of ImageField via values() method on django queryset I have a data model in Django where I save photos uploaded by users. There's an attribute called image_file in the Photo model (of the type ImageField) where - among other things - the image's url is stored. I can successfully access this url with item.image_file.url in the template (and view) for instance.
However, I can't seem to be able to do the following in the view:
Photo.objects.filter(owner=user).order_by('-id').values('id','image_file.url')[:10]
I.e. For a particular user, I'm trying to get the 10 latest photo objects' image urls along with object ids. This gives me FieldError: Cannot resolve keyword 'image_file.url' into field. Shouldn't this have worked?
I understand I can retrieve the entire object and do the filtering in the template, but I felt it's more optimal to solely retrieve the fields I actually need instead of the full object.
p.s. it's a postgresql backend and the underlying Storage class has been over-ridden

A: The url is a property, not a value in the database (FileField code) which is why you can't get to it from values(). As far as I can see, you'd have to get the url value separately...
You might want to take a look at only() though. If you go that route, you should probably watch the SQL queries with something like Django Debug Toolbar. If the url property tries to retrieve a field that wasn't included in only(), it will likely make a separate SQL call.


text:
Q: Matlab - finding nearest neighbor in three-dimensional coordinate system Welcome!
I have a set of n matlab matrix with the following structure:
xyz_1   -3,37200000000000   2,80000000000000    5,03400000000000

xyz_2   -2,21700000000000   1,74500000000000    7,45300000000000

....    ..................  ................    ................

xyz_n  -1,39300000000000    0,00700000000000000 6,35500000000000

where the first column is the name of matrix, while the next three columns are the xyz coordinates. I' am looking for an efficient way to find the nearest neighbor. I would like to give the matrix name and k of potential neighbors as the input parameter then program will find the nearest neighbors giving me the result matrix in the following form:
[nearest_neighbor_name_1;    distance_between_quoted_element_and_nearest_neigbor_1

 nearest_neighbor_name_2;    distance_between_quoted_element_and_nearest_neigbor_2

 nearest_neighbor_name_....; distance_between_quoted_element_and_nearest_neigbor_....

 nearest_neighbor_name_k;    distance_between_quoted_element_and_nearest_neigbor_k]

I tried to use the  knnsearchunfortunately without effect. Thank you for your help!

A: Is the traditional way of unsatisfactory in some way?  Evaluate the distance from each point to your test point and then sort the distances...
%define the "k" entries that you are interested in assessing
mydata_xyz = [-3.37200000000000   2.80000000000000    5.03400000000000;
              -2.21700000000000   1.74500000000000    7.45300000000000;
                        <the rest of your data here>
              -1.39300000000000    0.00700000000000000 6.35500000000000];

%define the point about which you are looking for the nearest neighbors
mypoint_xyz = [ <whatever your xyz coordinate is];

%compute the distance from the given point to all of the other test points.
%Note the use of the transpose (apostrophe) to ensure that it sums in the
% correct direction
distance = sqrt(sum( ((mydata_xyz - ones(size(mydata_xyz,1),1)*mypoint_xyz).^2)' ));

%sort to get the nearest neighbor followed by the next nearest neighbors
[sorted_distance, Isort] = sort(distance);

%print out each one of the points, from closest to farthest
for I=1:length(Isort)
    disp(['Point ' num2str(Isort) ...
          ', dist = ' num2str(distance(Isort(I))) ...
          ', xyz = ' num2str(mydata_xyz(Isort(I),:))]);
end


text:
Q: Cortana channel - Failed to create bot module I'm using Azure Bot Channels Registration for my bot, I have working endpoint and bot works well in Web Chat and My settings are:

Display Name: Engine Crave
Invocation Name: Engine Crave
Long Desc, Short Desc etc are all correct and filled and also organization at the last is also selected.

Also, My bot takes no user permissions. But when I save the Cortana Channel, I get a popup:
Unable to save.
There was an error saving the channel:
Failed to create bot module. Trace Id : 87140f58-46f8-4101-a849-17d63af6831c

Trace ID always keeps changing whenever I try.
Pls help!

A: Yayay! I found answer myself. Go-to settings and make display name same as your bot registration name when you registered on Azure! Mine was crave-engine.
Next goto Channels Registration -> Cortana -> Here you will see

Display Name: crave-engine
Invocation Name: crave-engine

Let these be like this and just click the "Register" button at the bottom. It's ok for now, You can however change these names When you register from https://knowledge.store .
I don't know these was some kind of bug or Azure Bot Team did this on purpose!


text:
Q: Table Rate Message Sorry, no quotes are available for this order at this time I am getting the error as "Sorry, no quotes are available for this order at this time."
My table Rate data is as follows :
Country Region/State    Zip/Postal Code Weight (and above)  Shipping Price
IN  *   *   500 120
IN  GUJAR   *   500 100
IN  MAHAR   *   500 80
IN  *   *   250 70
IN  GUJAR   *   250 55
IN  MAHAR   *   250 55

If i order any product of the weight it is displaying this message.
I tried on local server with default magento template but it is working fine. Please help me on this

A: Found the Answer .
I made changes to Ship to specific countries to all countries and Now it is displaying.
Don't know whether it is a bug or not. But now the rates from table rates are now displaying.


text:
Q: Taylor series and singularities I'm studying complex analysis and I cannot find a way to solve this exercise. I'll report the text:
Set $$f(z)=\frac{1}{1-\sin(z)}$$
1 -  Find the first nonzero terms in Taylor expansion of $f(z)$ around $0$
$$$$2 - Find and classify the isolated singularities in the extended complex plane
$$$$3 - Evaluate the integral $$\int_{\left | z=2 \right |} \frac{f(z))}{z}dz$$
Now, I was able to solve the first part of the exercise by computing the Taylor series by definition and I found the isolated singularities of the functions (all points such that $z = \frac{\pi}{2}+2k\pi$, with $k$ integer.
By computing the limit of the function in the neighbourhood of the singularities, I'm able to find out that those singularities are poles, but I'm not able to find the order. From this point on I'm stuck.
For part 3, I know I should use the residue theorem to compute the integral by knowing that the function has two singularities at $0$ and $\frac{\pi}{2}$.
Anyone knows how to solve it? Thanks in advance

A: Let $g(z):=1- \sin z$ and $z_k:=\frac{\pi}{2}+2k\pi$
Then we have
$$g(z_k)=0, g'(z_k)=0, g''(z_k) \ne 0.$$
Hence $g$ has azero of order $2$ at $z_k.$ Therefore $f$ has a pole of order $2$ at $z_k.$
Can you proceed ?

A: Using what Fred said I was able to complete the second part of the question. In order to compute the other part, it is needed to proceed from the definition which will lead to an infinite series sum and obtain that the result is $\frac{-8}{\pi^2}$
The help of my complex analysis professor was needed though to check the result.


text:
Q: How to mutate values of nested structs in Rust? I'm having trouble figuring out how to mutate nested structs. I have a Folder struct that can hold Files and other Folders inside it. I then want to be able to add new files and folders to those nested folders after creating them, but I keep running into errors.
Code:
type SubFolder = Vec<Box<Folder>>;
type Files = Vec<String>;

#[derive(Debug)]
struct Folder {
    files: Files,
    sub_folder: SubFolder
}

impl Folder {
    pub fn new() -> Self {
        Self {
            files: Vec::new(),
            sub_folder: Vec::new(),
        }
    }

    pub fn add_file(&mut self, file: String) {
        self.files.push(file);
    }

    pub fn add_folder(&mut self, dir: Box<Folder>) {
        self.sub_folder.push(dir);
    }
}

fn main() {
    let mut folder_1 = Folder::new();
    let mut folder_2 = Folder::new();

    folder_1.add_folder(Box::new(folder_2));
    folder_2.add_file(String::from("b.txt")); // Error

}

Error Message:
error[E0382]: borrow of moved value: `folder_2`
  --> src/main.rs:32:5
   |
29 |     let mut folder_2 = Folder::new();
   |         ------------ move occurs because `folder_2` has type `Folder`, which does not implement the `Copy` trait
30 |
31 |     folder_1.add_folder(Box::new(folder_2));
   |                                  -------- value moved here
32 |     folder_2.add_file(String::from("b.txt")); // Error
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move

Is it even possible to do this? Or do I need to use unsafe code? Any resources or suggestions would be appreciated.

A: for your methods add_folder and add_file you need mut reference to self. However after folder2 has been moved you can not reference it anymore.
There are a few ways to address it.

*

*You can use "full path".

Like so:
type SubFolder = Vec<Box<Folder>>;
type Files = Vec<String>;
#[derive(Debug)]
struct Folder {
    files: Files,
    sub_folder: SubFolder
}

impl Folder {
    pub fn new() -> Self {
        Self {
            files: Vec::new(),
            sub_folder: Vec::new(),
        }
    }

    pub fn add_file(&mut self, file: String) {
        self.files.push(file);
    }

    pub fn add_folder(&mut self, dir: Box<Folder>) {
        self.sub_folder.push(dir);
    }
}

fn main() {
    let mut folder_1 = Folder::new();
    let mut folder_2 = Folder::new();

    folder_1.add_folder(Box::new(folder_2));
    folder_1.sub_folder[0].add_file(String::from("b.txt")); // Ok
}

*Or if you really need to reference folder2 then you have to own it multiple times, so you need Rc for multiple ownership and RefCell for interior mutability as Rc is read only

E.g.:
use std::cell::RefCell;
use std::rc::Rc;

type SubFolder = Vec<Rc<RefCell<Folder>>>;
type Files = Vec<String>;
#[derive(Debug)]
struct Folder {
    files: Files,
    sub_folder: SubFolder
}

impl Folder {
    pub fn new() -> Self {
        Self {
            files: Vec::new(),
            sub_folder: Vec::new()
        }
    }

    pub fn add_file(&mut self, file: String) {
        self.files.push(file);
    }

    pub fn add_folder(&mut self, dir: Rc<RefCell<Folder>>) {
        self.sub_folder.push(dir);
    }
}

fn main() {
    let mut folder_1 = Folder::new();
    let mut folder_2 = Rc::new((RefCell::new(Folder::new())));

    folder_1.add_folder(Rc::clone(folder_2));
    folder_2.borrow_mut().add_file(String::from("b.txt")); // Ok
}

Btw, with Vec you can not address subfolder or file by name. Maybe better use Hashmap?


text:
Q: Join Two queries with different declarations I need to join two different queries to get some columns from both. The first one has a CTE.
Query1:
   WITH StatusChanges AS
(
    SELECT
       HistoryID,PartID,Status, DateAdded,
       rnAsset = ROW_NUMBER() OVER (PARTITION BY PartID ORDER BY DateAdded)
    FROM aAssetHistory
) SELECT
    A.isMarketed,A.AssetDescription,A.aPartID,A.SerialNumber,A.PartNumber,
    A.Location,A.Vintage,Ap.Fund,A.ProjectNumber,AP.ProjectName ,
    (
       SELECT Top 1 Disposition
       FROM aAssetDisposition AD
       WHERE (A.aPartid = AD.AssetID)) As Disposition, A.LocStatus ,
          CASE
             WHEN A.LocStatus='In Repair' THEN EstimatedCompletion
             WHEN A.LocStatus like '%lease%' THEN IIF(ProjectedReDeliveryDate='1/1/1900',LeaseExpiry,ProjectedReDeliveryDate)
             WHEN A.LocStatus='Stored' OR A.LocStatus='Marketed' THEN SC.DateAdded
          END 'Available',A.AssetComment,
          Cast(ISNULL((SELECT Top 1 1
                       FROM aAssetMarketingDocuments AMDocs
                       WHERE A.aPartid=AMDocs.aPartid),0) As bit
       ) Attachment
    FROM aAsset A
INNER JOIN aProject AP On A.ProjectNumber=AP.ProjectNumber
LEFT JOIN aAsset ParentA  On A.ParentACPartID=ParentA.aPartid
LEFT JOIN aEngineShop ES ON A.LocStatus='In Repair' AND ES.PartID=A.aPartid
LEFT JOIN vLeasedAsset LA ON A.LocStatus like '%lease%' AND LA.aPartID=A.aPartid
LEFT JOIN (
          SELECT SC1.PartID, SC1.DateAdded,RN= ROW_NUMBER() OVER (PARTITION BY SC1.PartID ORDER BY SC1.DateAdded DESC)
          FROM StatusChanges SC1
          LEFT JOIN StatusChanges SC2 ON SC1.PartID=SC2.PartID AND SC2.rnAsset=SC1.rnAsset-1
          WHERE (SC1.Status<>SC2.Status OR SC2.HistoryID IS NULL)) SC
ON (A.LocStatus='Stored' OR A.LocStatus='Marketed') AND A.aPartid=SC.PartID AND SC.rn = 1
WHERE ((A.isMarketed=1 AND (ParentA.isMarketed IS NULL OR ParentA.isMarketed=0)) )

Query2:
 SELECT
    A.[AssetMarketingID],B.PartID, aCompany.Company 'PotentialCustomer', A.isActive,
    ISNULL(CAST(Lease AS bit),0) 'Lease', ISNULL(CAST(Exchange AS bit),0) 'Exchange',
    ISNULL(CAST(Sale AS bit),0) 'Sale' ,DocumentStage,ContactTB.FirstName + ' ' + ContactTB.LastName 'Contact',
    A.ContactDate,A.Status,B.Amount, A.DateCreated, [Notes]
FROM aAssetMarketing A
LEFT JOIN aAssetMarketingAssets B ON A.AssetMarketingID=B.AssetMarketingID
LEFT JOIN aCompany On [PotentialCustomerID]=COid
LEFT JOIN aCompanyContact ContactTB ON [MarketingContactID]=ContactID
LEFT JOIN (
          select AssetMarketingID,max(case when DealStructure = 'Exchange' then 1 ELSE 0 end) Exchange,
          max(case when DealStructure = 'Lease' then 1 Else 0 end) Lease,
          max(case when DealStructure = 'Sale' then 1 Else 0 end) Sale
FROM [aAssetMarketingDealStructure]
GROUP BY AssetMarketingID) DS
    ON DS.AssetMarketingID=A.AssetMarketingID
ORDER BY A.ContactDate DESC

A:    WITH StatusChanges AS
(
    SELECT
       HistoryID,PartID,Status, DateAdded,
       rnAsset = ROW_NUMBER() OVER (PARTITION BY PartID ORDER BY DateAdded)
    FROM aAssetHistory
) SELECT
    A.isMarketed,A.AssetDescription,A.aPartID,A.SerialNumber,A.PartNumber,
    A.Location,A.Vintage,Ap.Fund,A.ProjectNumber,AP.ProjectName ,
    (
       SELECT Top 1 Disposition
       FROM aAssetDisposition AD
       WHERE (A.aPartid = AD.AssetID)) As Disposition, A.LocStatus ,
          CASE
             WHEN A.LocStatus='In Repair' THEN EstimatedCompletion
             WHEN A.LocStatus like '%lease%' THEN IIF(ProjectedReDeliveryDate='1/1/1900',LeaseExpiry,ProjectedReDeliveryDate)
             WHEN A.LocStatus='Stored' OR A.LocStatus='Marketed' THEN SC.DateAdded
          END 'Available',A.AssetComment,
          Cast(ISNULL((SELECT Top 1 1
                       FROM aAssetMarketingDocuments AMDocs
                       WHERE A.aPartid=AMDocs.aPartid),0) As bit
       ) Attachment
    INTO #tmp
    FROM aAsset A
INNER JOIN aProject AP On A.ProjectNumber=AP.ProjectNumber
LEFT JOIN aAsset ParentA  On A.ParentACPartID=ParentA.aPartid
LEFT JOIN aEngineShop ES ON A.LocStatus='In Repair' AND ES.PartID=A.aPartid
LEFT JOIN vLeasedAsset LA ON A.LocStatus like '%lease%' AND LA.aPartID=A.aPartid
LEFT JOIN (
          SELECT SC1.PartID, SC1.DateAdded,RN= ROW_NUMBER() OVER (PARTITION BY SC1.PartID ORDER BY SC1.DateAdded DESC)
          FROM StatusChanges SC1
          LEFT JOIN StatusChanges SC2 ON SC1.PartID=SC2.PartID AND SC2.rnAsset=SC1.rnAsset-1
          WHERE (SC1.Status<>SC2.Status OR SC2.HistoryID IS NULL)) SC
ON (A.LocStatus='Stored' OR A.LocStatus='Marketed') AND A.aPartid=SC.PartID AND SC.rn = 1
WHERE ((A.isMarketed=1 AND (ParentA.isMarketed IS NULL OR ParentA.isMarketed=0)) )

Query2:
SELECT
    A.[AssetMarketingID],B.PartID, aCompany.Company 'PotentialCustomer', A.isActive,
    ISNULL(CAST(Lease AS bit),0) 'Lease', ISNULL(CAST(Exchange AS bit),0) 'Exchange',
    ISNULL(CAST(Sale AS bit),0) 'Sale' ,DocumentStage,ContactTB.FirstName + ' ' + ContactTB.LastName 'Contact',
    A.ContactDate,A.Status,B.Amount, A.DateCreated, [Notes]
FROM aAssetMarketing A
LEFT JOIN aAssetMarketingAssets B ON A.AssetMarketingID=B.AssetMarketingID
LEFT JOIN aCompany On [PotentialCustomerID]=COid
LEFT JOIN aCompanyContact ContactTB ON [MarketingContactID]=ContactID
LEFT JOIN (
          select AssetMarketingID,max(case when DealStructure = 'Exchange' then 1 ELSE 0 end) Exchange,
          max(case when DealStructure = 'Lease' then 1 Else 0 end) Lease,
          max(case when DealStructure = 'Sale' then 1 Else 0 end) Sale
FROM [aAssetMarketingDealStructure]
JOIN #tmp A ON
A.SerialNumber, A.PartNumber, Location, A.Fund, Disposition, DocumentStage, Lease, Sale
GROUP BY AssetMarketingID) DS
    ON DS.AssetMarketingID=A.AssetMarketingID
ORDER BY A.ContactDate DESC

A: Another way:
    WITH StatusChanges AS
(
    SELECT HistoryID,PartID,Status, DateAdded, rnAsset = ROW_NUMBER() OVER (PARTITION BY PartID ORDER BY DateAdded)
    FROM aAssetHistory
)

    SELECT X.SerialNumber, X.PartNumber, X.ProjectName, X.ProjectNumber, X.AssetDescription, X.Available, X.Location, X.LocStatus, X.AssetComment, X.Disposition, X.Fund, X.isMarketed,
                Y.PotentialCustomer, Y.Lease, Y.Exchange, Y.Sale, Y.DocumentStage, Y.Contact, Y.ContactDate, Y.Amount, Y.Notes
FROM
(
SELECT A.isMarketed,A.AssetDescription,A.aPartID,A.SerialNumber,A.PartNumber,
   A.Location,A.Vintage,Ap.Fund,A.ProjectNumber,AP.ProjectName ,
(SELECT Top 1 Disposition FROM aAssetDisposition AD WHERE (A.aPartid = AD.AssetID)) As Disposition, A.LocStatus ,
  CASE
     WHEN A.LocStatus='In Repair' THEN EstimatedCompletion
     WHEN A.LocStatus like '%lease%' THEN IIF(ProjectedReDeliveryDate='1/1/1900',LeaseExpiry,ProjectedReDeliveryDate)
     WHEN A.LocStatus='Stored' OR A.LocStatus='Marketed' THEN SC.DateAdded
   END 'Available'
 ,A.AssetComment, Cast(ISNULL((SELECT Top 1 1 FROM aAssetMarketingDocuments AMDocs WHERE A.aPartid = AMDocs.aPartid),0) As bit) Attachment
FROM aAsset A
INNER JOIN aProject AP On A.ProjectNumber=AP.ProjectNumber
LEFT JOIN aAsset ParentA  On A.ParentACPartID=ParentA.aPartid
LEFT JOIN aEngineShop ES ON A.LocStatus='In Repair' AND ES.PartID=A.aPartid
LEFT JOIN vLeasedAsset LA ON A.LocStatus like '%lease%' AND LA.aPartID=A.aPartid
LEFT JOIN (
          SELECT SC1.PartID, SC1.DateAdded,RN= ROW_NUMBER() OVER (PARTITION BY SC1.PartID ORDER BY SC1.DateAdded DESC)
          FROM StatusChanges SC1
          LEFT JOIN StatusChanges SC2 ON SC1.PartID=SC2.PartID AND SC2.rnAsset=SC1.rnAsset-1
          WHERE (SC1.Status<>SC2.Status OR SC2.HistoryID IS NULL)) SC
ON (A.LocStatus='Stored' OR A.LocStatus='Marketed') AND A.aPartid=SC.PartID AND SC.rn = 1
WHERE ((A.isMarketed=1 AND (ParentA.isMarketed IS NULL OR ParentA.isMarketed=0)))
) X LEFT JOIN

(SELECT A.[AssetMarketingID],B.PartID, aCompany.Company 'PotentialCustomer', A.isActive,
     ISNULL(CAST(Lease AS bit),0) 'Lease', ISNULL(CAST(Exchange AS bit),0) 'Exchange',
     ISNULL(CAST(Sale AS bit),0) 'Sale' ,DocumentStage,ContactTB.FirstName + ' ' + ContactTB.LastName 'Contact', A.ContactDate,A.Status,B.Amount, A.DateCreated, [Notes]
FROM aAssetMarketing A
LEFT JOIN aAssetMarketingAssets B ON A.AssetMarketingID=B.AssetMarketingID
LEFT JOIN aCompany On [PotentialCustomerID]=COid
LEFT JOIN aCompanyContact ContactTB ON [MarketingContactID]=ContactID
LEFT JOIN (
          select AssetMarketingID,
          max(case when DealStructure = 'Exchange' then 1 ELSE 0 end) Exchange,
          max(case when DealStructure = 'Lease' then 1 Else 0 end) Lease, max(case when DealStructure = 'Sale' then 1 Else 0 end) Sale
FROM [aAssetMarketingDealStructure]
GROUP BY AssetMarketingID) DS ON DS.AssetMarketingID=A.AssetMarketingID
) Y
On X.aPartid = Y.PartID


text:
Q: Receiving "syntax error, unexpected '<'" in PHP This is my script:
function Secu($variable)

{
$variable = mysql_real_escape_string(htmlspecialchars(stripslashes(nl2br(trim($variable)))));
return $variable;
}
function Redi($lien)
{
echo <script type="text/javascript">document.location.href=\.$lien.='/index.php';</script>  ;
function PassHash($mdp_hashed)
{
$mdp_hashed = Secu(md5($mdp_hashed));
return $mdp_hashed;
}
if (isset($_SESSION['username']))
$pseudo = Secu($_SESSION['username']);
$sql_user = mysql_query("SELECT * FROM users WHERE username = ".$pseudo." LIMIT 1") or die(mysql_error());
$row_user = mysql_num_rows($sql_user);
}

I am getting this:

ERROR: syntax error, unexpected '<'

A: PHP cannot parse line 10 of your code. You want to enclose your argument to echo function in the double quotes, as well as escape backslash, like this:
echo "<script type='text/javascript'>document.location.href=\\".$lien."=/index.php';</script>" ;

A: Your problem happens in the line:
echo <script type="text/javascript">document.location.href=\.$lien.='/index.php';</script>  ;

You need to put the string in quotes - so it becomes
echo "<script type=\"text/javascript\">document.location.href=\\".$lien."='/index.php';</script>"  ;

There may be other errors...

A: Looks like you just need to put quotes around the string you are trying to echo!
echo '<script type="text/javascript">document.location.href=\.$lien.='/index.php';</script>';


text:
Q: Extracting the data from SQL Server filtered by username I have a huge table tableA in my database. I have to extract the entries made into this tableA by userA.
My aim is to append this data in one more server where we give the build.
The query
select *
from tableA
where name = 'userA'

will give the select statements. But how to get the insert statements as a script, so that when I run in a new db, all the entries should be inserted into the new table?
To conclude, I want to extract and give the script to a build person of all the records made by me as a script.

A: Do you need a script to insert into a new table (TableB) from the table A?
If the table are in the same server, you need only make:
Insert into TableB (Col1, Col2, Col3)
select Col1, Col2, Col3 from TableA

If the tables are in a different server. First you have to make a Linked Server between the servers and after execute the script
Insert into Server2.TableB (Col1, Col2, Col3)
select Col1, Col2, Col3 from Server1.TableA

A: As a starting point, if you don't have columns with NULL values you could try this sequence of queries:
#get fields in a mysql variable

select   GROUP_CONCAT(CONCAT('`', `column_name`, '`'))
from `information_schema`.`COLUMNS` where TABLE_NAME='tableA' into @fields;

#get the query which will generate the insert command in a variable

select CONCAT("SELECT CONCAT(\'INSERT INTO tableA(",@fields,
")VALUES(\\\'\',CONCAT_WS(\"\',\'\",",@fields,
"),\"\');\") as `INSERT COMMAND` from `tableA` where `name`='userA'")
into @generateInsertCommand;

#execute the query which will generate insert command

PREPARE stmt FROM @generateInsertCommand;
EXECUTE stmt;

it should generate something like this:
INSERT INTO tableA(`id`,`date1`,`int1`,`name`)VALUES('4','2015-10-21','127','userA');
INSERT INTO tableA(`id`,`date1`,`int1`,`name`)VALUES('5','2015-10-20','327','userA');


text:
Q: How to define `TcpOutboundGateway` bean in Java class configuration When I tried to define TcpOutboundGateway bean, I found that class doesn't have requestChannel and replyChannelName setters. How can I correctly define that bean in my Java class configuration?
Which Java class configuration is equal to the XML configuration presented below?
<int-ip:tcp-outbound-gateway id="outGateway"
        request-channel="input"
        reply-channel="clientBytes2StringChannel"
        connection-factory="client"
        request-timeout="10000"
        reply-timeout="10000"/>

A: This code is equal to client xml configuration presented by the link.
public static final String STRING_TO_BYTES_CHANNEL = "stringToBytesChannel";
public static final String REQUEST_CHANNEL = "requestChannel";

private String host = "localhost";
private int port = 2020;

@Bean
public TcpNetClientConnectionFactory connectionFactory() {
    TcpNetClientConnectionFactory factory = new TcpNetClientConnectionFactory(host, port);
    factory.setSingleUse(true);
    factory.setSoTimeout(10000);
    return factory;
}

@Bean
public MessageChannel requestChannel() {
    return new DirectChannel();
}

@Bean
public MessageChannel stringToBytesChannel() {
    return new DirectChannel();
}

@Bean
@Transformer(inputChannel = STRING_TO_BYTES_CHANNEL)
public ObjectToStringTransformer objectToStringTransformer() {
    return new ObjectToStringTransformer();
}

@Bean
@ServiceActivator(inputChannel = REQUEST_CHANNEL)
public TcpOutboundGateway outboundGateway() {
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(connectionFactory());
    gateway.setReplyChannel(stringToBytesChannel());
    gateway.setRequestTimeout(10000);
    gateway.setRemoteTimeout(10000);
    return gateway;
}

@MessagingGateway(defaultRequestChannel = REQUEST_CHANNEL)
public interface RequestGateway {
    String send(String message);
}


text:
Q: Is the standard's ODR example correct? Before you answer, observe that another question is closely related.
The C++17 standard (draft here), sect. 6.2(2.8), gives the following example:
struct S { static const int x = 0; };
const int &f(const int &r);
int n = b ? (1, S::x) // S::x is not odr-used here
          : f(S::x);  // S::x is odr-used here, so a definition is required

The example's "odr" means, "one-definition rule," but the example's comment, "S::x is not odr-used here," looks like nonsense to me. Is it?
I am no language lawyer but, unfortunately, the comment conveys no plausible or approximate idea to me. This suggests that I am missing a concept.
On the other hand, a 1600-page document like the C++17 standard can make some mistakes. I do not criticize but merely wish to ensure that I have understood.
Is the comment nonsense or does it mean something sensible? How or why, please?


text:
Q: Help with plotting a logarithmic spiral I'm trying to find the formula to plot the following spiral:
It grows  at a rate of √2 for every 45 degrees of rotation, so for example starting at 0 degrees (at 45 degree increments), it expands thus:0, 0.7, 1, 1.41, 2, 2.82, 4 etc... But I want to be able to find the distance from the centre at any angle, not just at the 45 degree increments.
Can anyone help with this please?
Many thanks
Paul uk

A: Such a spiral has a polar representation of the form
$$r(\phi)=C e^{\lambda\phi}\qquad(-\infty<\phi<\infty)$$
with a certain constant $\lambda\ne0$. Your condition amounts to
$$e^{\lambda\pi/4}=\sqrt{2}\ ,$$which translates into
$$\lambda={2\over\pi}\log 2\ .$$

A: The simple way to write what you are asking is $r=A (\sqrt 2)^{\frac \theta {45^\circ}}$ where $A$ is the radius at $\theta=0$.  As $\theta$ increases by $45^\circ$ the exponent of $\sqrt 2$ increases by $1$.
You could be more sophisticated and use $e$ as the base, saying $r=Ae^{\ln \sqrt 2\cdot \frac {\theta}{45^\circ}}$.  If you have an $e^x$ button and no $x^y$ button that will be preferable.


text:
Q: call a function in angularjs controller from html and scope variable is not defined I am a newbie in angularjs and need to know how to call a function which is define in controller from html in angularjs
I have wrote a code html
 First.html

<input type="text" ng-model="model.name" name="name" />

 Second.html

{{model.familyname}}
 // it displays the value

Is this way is correct or is there any other way to call a function. Also when init() is called scope variable is undefined
$scope.init = function () {
      alert($scope.model.name); // it displays undefined

    };

Any help is very much appreciated

A: ngInit directive is meant to run an expression and assign a scope variable. There is a nice warning in the docs about using it:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

https://docs.angularjs.org/api/ng/directive/ngInit
Instead of using ngInit, I would suggest running the function in the controller:
controllerFunction($scope) {
    $scope.someFunction = someboundfunction;
    //etc...

    activate();

    function activate() {
        // do some activation stuff
    }

    function someboundfunction() {
        //...
    }
}

The coding style of placing bindable members at the top, keeps me from going crazy when writing big controllers that have activation logic. It's here, if you're interested in that.

A: You need to keep things you want to use inside this controller to make it worked.

angular.module('TestApp', []);

angular.module('TestApp')
  .controller('formCtrl', ['$scope', '$window', function($scope, $window) {
    $scope.model = {
      name: 'Default name'
    };

    $scope.alertName = function(where) {
      alert(where + ': ' + $scope.model.name);
    };

    $window.onload = function() {
      // will be called after ng-init
      $scope.alertName('On Load');
    };

    // call it directly from controller
    $scope.alertName('From controller');
  }]);

      <input type="text" ng-model="model.name" />
      <button ng-click="alertName()">Alert this name</button>

{{ model.name }}

A: Welcome to the magical world of AngularJS. Angular could be a little overwhelming at first, but don't give up. You're going in the right direction.
A few suggestions for the code you have written -
- You need to encapsulate your complete code inside the controller to be able to process data to and from it.
- I am assuming you already have initialized your app using ng-app or some other ng-someName
- Since, ng-init is used to initialize a parameter/method, you don't need to mention it as such in your code. $scope will take care of it automatically (It's cool, right!)
So your code would look like something below after implementing the suggestions above -
    //html code

       {{ Username }}
//angular.js
 app.controller('formCtrl', function($scope) {
    $scope.Username = '';
 });

Let the magic begin! ;)


text:
Q: VTT(Subtitles) is not working from external url I am trying to play the subtitle of a movie from an external url but it doesn't work and when I try to add vtt file whcih is loacally stored then it works. Below are the codes
<video id="video" controls preload="metadata">
   <source src="video/sintel-short.mp4" type="video/mp4">
   <track label="English" kind="subtitles" srclang="en" src="http://devcache.filmflexmovies.com/Test/Movies/2016/6/28/SDFEATUREMOVIE/Creed ENG.VTT" default>
</video>
Above code doesn't work. But when I copied the content of vtt it works.
<video id="video" controls preload="metadata">
   <source src="video/sintel-short.mp4" type="video/mp4">
   <track label="English" kind="subtitles" srclang="en" src="abc.VTT" default>
</video>
Please help.

A: It sounds like you are being blocked by a crossorigin access issue. To access VTT files from a different domain, you must satisfy two conditions:

*

*Add the right CORS headers to the site hosting the VTT file. You may not have access to this site, but thankfully it looks like right header is already being used: Access-Control-Allow-Origin: *.

*Add the crossorigin="anonymous" attribute to your pages's audio/video element. Something like this:

<video id="video" crossorigin="anonymous" autoplay controls preload="metadata">
  <source src="video/sintel-short.mp4" type="video/mp4" />
  <track label="English" kind="subtitles" srclang="en" src="http://devcache.filmflexmovies.com/Test/Movies/2016/6/28/SDFEATUREMOVIE/Creed ENG.VTT" default/>
</video>

I hope this works for you.


text:
Q: Разность maxRange акселлерометра и его истинных показаний в Android Studio
public void SensorData()
{

SensorManager sensorManager=
(SensorManager)currentActivity.getSystemService(Context.SENSOR_SERVICE);

    Sensor defaultacc =
    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    maxrange = defaultacc.getMaximumRange();
}

maxrange показывает что сенсор может мерить до 39 м.с^2
Однако, код ниже
public void onSensorChanged(SensorEvent event)
{

    if(event.sensor.getType()== Sensor.TYPE_ACCELEROMETER){
        float[] values= event.values;

        ax= values[0]; //Вот эти значения осей не доходят даже до 20 м/c^2
        ay= values[1];
        az= values[2];

}

Показывает максимальные результаты в 2 раза меньше - не более 19 с копейками м/c^2
В чем дело? Есть ли возможность поднять порог до 39 м\с^2, как написано в инфо о сенсоре? Тестировал на нескольких телефонах.

A: На многих телефонах некоторые сенсоры показывают неверные максимальные значения.
Как решить?
1) Попросить пользователя очень сильно потрясти телефон и замерить(т.е. своеобразная калибровка).
2) Через native снимать данные напрямую. Тут много сложностей разные производители сенсоров.
Вобщем первоочередная задача выяснить кто именно дает неправильные данные.
Может даже сам производитель немного урезать.


text:
Q: Can I set up Kate to always fold (collapse) all foldable regions when opening a code file? I'd like to set up Kate so that, if I open, for example, a C++ file, all classes it contains are folded? But not only the root levels, when I unfold a class, I'd like methods inside it to be initially folded too. Etc. Is it possible?

A: From what I'm seeing, you won't be able to achieve this without modifying the kate's code. I would suggest putting in a formal feature request (a wish) on their tracking system.
It's a feature that I would want as well :)


text:
Q: Is the inner product distributive in this sense? Let's say we have $|\langle x|y\rangle|^2=\langle y|x\rangle\langle x|y\rangle$. I have the projection operator $\mathbb{P}=|x\rangle\langle x|$, and a projection operator on the subspace $\mathbb{P}=|x,1\rangle\langle x,1|+|x,2\rangle\langle x,2|$.
If I were to find the probability that a measurement will find the result $x$, then I would write
$$P(x)=\langle y|\mathbb{P}|y\rangle=\langle y|(|x,1\rangle\langle x,1|+|x,2\rangle\langle x,2|)|y\rangle$$
My question is, does this distribute? Meaning, for all cases (and if not all then for what cases) can we write this as
$$P(x)=\langle y|x,1\rangle\langle x,1|y\rangle+\langle y|x,2\rangle\langle x,2|y\rangle$$
$$P(x)=|\langle x,1|y\rangle|^2+|\langle x,2|y\rangle|^2 $$

A: The answer is yes.  In particular, this is a routine consequence of the usual distributive property for linear operators:
$$
\langle y|(|x,1\rangle\langle x,1|+|x,2\rangle\langle x,2|)|y\rangle = \\
(\langle y|x,1\rangle\langle x,1|+\langle y|x,2\rangle\langle x,2|)|y\rangle =\\
\langle y|x,1\rangle\langle x,1| y \rangle+\langle y|x,2\rangle\langle x,2|y\rangle
$$


text:
Q: Does FSCK repair / mark bad sectors as it scans and, is it possible to resume a scan from an offset? System: macOS 10.14.6
Overview:
One of the HDD in the system was giving issues and I suspected the old disk was dying. I wanted to check for bad sectors on it. It uses the Mac OS Extended (Journaled) filesystem. So I started a scan of the disk with fsck_hfs:
bash-3.2# fsck_hfs -S -E /dev/disk0

But even after more than 12-13 hours overnight it had only scanned around 66% of the 1TB drive:
** /dev/rdisk0 (NO WRITE)
Scanning entire disk for bad blocks
Scanning offset 6615812001408 of 1000204886016 (66%)

and I had to interrupt it as the system was needed.
Doubts:

*

*Does FSCK mark the bad sectors as it scans for it (or does it do it only do this after the scan is complete?)

*If the first case is true, is there any option to resume scanning from the offset specified in the status message (i.e from block 6615812001408)?

*Is there any better system tools to scan disks for bad sectors which supports resume if the operation has to be interrupted?

A: *

*Does FSCK mark the bad sectors as it scans for it (or does it only do this after the scan is complete?)

---> No, bad sector on a drive is a sign of permanent damage to the drive. Unless you have reason to believe that your drive marked these sectors as bad incorrectly, you cannot "fix" them.
It means that a part of your drive is damaged to the extent that it can no longer reliably be read from and/or written to.

*If the first case is true, is there any option to resume scanning from the offset specified in the status message (i.e from block 6615812001408)?

---->There is no way to resume as the program needs to know the complete state of the filesystem in order to be able to work.
You could have typed ^Z to stop the program and later run fg to resume it or just leave it alone.

*Is there any better system tools to scan disks for bad sectors which support resumes if the operation has to be interrupted?

---->To check the physical condition of your disk it's best to install smartmontools
Sudo yum install smartmontools

Use the smartctl command to read out this status. For example to read all attributes from the first disk call
sudo smartctl --all /dev/sda

Hope this helps.


text:
Q: Bug: "Unspecified error" some of the time in IE11 in iframe Steps To Reproduce

*

*Open http://cygnetuat.sterlingdatarooms.com/PDFTronClientTest/ in IE11

*Wait for the application to load in the iframe
The current behavior
Sometimes an "Unspecified error" will appear in the console and the viewer in the iframe won't load

Unfortunately, it is not 100% reproducible. Sometimes the error won't occur. I'm also having trouble creating a minimal sample to reproduce this.
The expected behavior
There is no error.


text:
Q: Custom space tokenization with Spacy Spacy tokenizer's behavior is to squash single spaces into previous token's whitespace property and more than two consecutive spaces are merged to form single separate token. A single space at start of a sentence also forms a single token. These space only tokens have pos_ as SPACE.
I want a way to modify this behavior so that even consecutive spaces are added to the whitespace property of the previous token instead of forming a separate token.
Example:
sentence          ' Is this  working properly.'
Current behaviour of the tokenizer -
sentence.tokens               : [' ', 'Is', 'this', '  ', 'working', 'properly', '.']
token.whitespace : ['', ' ', ' ', '', ' ', '', ''] (either 0 or 1 spaces)
Expected custom behaviour of the tokenizer -
sentence.tokens               : [' ', 'Is', 'this', 'working', 'properly', '.'] (first space can't be avoided)
token.whitespace : ['', ' ', '  ', ' ', '', ''] (0 or more spaces)
I can do this with a loop after tokenization and setting a new ._.whitespaces custom spacy property for each token. But this would involve converting the doc object to list of tokens which I want to avoid because the doc object provides some nice properties over all tokens. If I were to construct new doc object with tokens without spaces using tokenizer.tokens_from_list, I won't get proper POS tags for the tokens since the word's text would contain spaces.


text:
Q: bash php silence segfault I need to prevent all php output, https://stackoverflow.com/a/617184/1695680 covers how to do this in general and for exception, errors, syntax errors so far it has worked, but.
php to produce a segfault in the pcre extension:
https://ilia.ws/archives/5_Top_10_ways_to_crash_PHP.html
<?php
# prce-bug.php

preg_match('/(.(?!b))*/', str_repeat("a", 10000));

In my testing, this still outputs:
user@host ~/crash-php $ php pcre-bug.php
Segmentation fault (core dumped)

user@host ~/crash-php $ php pcre-bug.php  >/dev/null 2>&1
Segmentation fault (core dumped)

So even with shell output redirection, output is getting to my terminal.

A: I found that using a new sh shell instance will capture system reported process deaths, like Segmentation Fault and Killed.
sh -c 'php pcre-bug.php' >/dev/null 2>&1

However, input arguments do not go to php, but rather to the sh instance which does nothing with them.

A: Output redirection is applied to the process, however the segfault message is being generated by bash itself as a result of the child process dying with a segfault.
One solution would be to do something like this:
echo `php pcre-bug.php >/dev/null 2>&1`

A: You can use compound commands { }:
$ { php pcre-bug.php; } &>/dev/null
$
$ echo $?
139

From Bash Manual -> 3.2.4 Compound Commands -> 3.2.4.3 Grouping Commands and man bash:

Compound Commands
{ list; }
list is simply executed in the current shell environment. list must be
  terminated with a newline or semicolon.
This is known as a group command. The return status is the exit status
  of list. Note that unlike the metacharacters ( and ), { and } are
  reserved words and must occur where a reserved word is permitted to be
  recognized.
Since they do not cause a word break, they must be separated from list
  by whitespace or another shell metacharacter.

However, using ( ) doesn't work and I don't know why:
$ ( php pcre-bug.php ) &>/dev/null
Segmentation fault (core dumped)


text:
Q: Можно ли без пакета анаконда реализовать задачу ML У нас есть стенд IBM Power AI,в котором нет пакета Anaconda, но есть Pytnon 3 и Jupyter. Есть ли возможность без библиотек реализовать задачу ML???

A: Библиотека - это просто кто-то вместо вас уже  потрудился и написал соответствующие программы. А Anaconda просто для вашего удобства собрала эти программы и дала возможность удобной их загрузки. Не хотите или не можете их использовать, считаете, что реализации в этих библиотеках неэффективны - никто не заставляет их использовать. Пишите свои.
Любую задачу ML можно реализовать на любом языке программирования - хоть Python, хоть C++, хоть Java, хоть R, Julia или Fortran. Вон, даже на JavaScript есть реализации. Но, естественно, для этого надо изучить - и весьма глубоко - соответствующие методы и алгоритмы ML, а также профессионально владеть соответствующим языком.
И еще: Jupyter - это среда разработки. Другими словами - особый тип IDE. И пользование ею -  никак не обязательный вариант организации работы разработчика или исследователя.


text:
Q: Can the shield gate be reopened once it's closed? This is what the Shield gate looks like from the underside:

It works by physically holding the shield open, not unlike holding a rubber band open like this:

To close the gate, the two retractable dam-like structures are raised, letting the shield snap shut over the opening:

This leaves a solid shield underneath the gate, and we know it's solid because

 not all of Blue Squadron makes it through before the gate is closed, and several X-Wings physically crash into and slide across the surface of the shield as if they had crashed into the ground.

It doesn't appear possible to push anything solid through the shield, including those structures.  Yet there must be a way to recover the "field aperture" and regain ingress and egress while maintaining the shield.
How does the Shield Gate reopen after it's closed?

A: I feel it's likely that the entire shield would have to be temporarily taken offline and the Shield Gate reset in order to recover the opening.  This wouldn't be quick or easy.  Consider the quote from the movie:

There's fighting on the beach.  They've locked down the base.  …they've closed the shield gate.
  K-2SO | Rogue One: A Star Wars Story

His tone implies a sense of finality—that once that gate has been closed, there's no way the team is getting off that base anytime soon, dead or alive.

A: From the research I have done it looks like the book and the movie are a little different... shocker. Using the details from the answer for this question here the gate is actually three stages: The planetary shield, gate housing, and an inner shield for the gate itself. This makes a lot of sense.
A statement made by Rogue One co-producer John Swartz here makes the idea that the gate in the film is just two stages: One massive shield that encompassed the entire planet and then a "gate barrier" that moved two massive wedges into and out of position. The two wedges that were used to hold the gate open only work in one lateral direction, otherwise it would have been a giant ring that was raised and lowered to open and close the gate. (Though that does not really apply to your question I thought that was interesting from watching the movie...)
So we can all see the giant wedges that are being removed from blocking the shield to allow it close. They are slow moving and in contrast to the co-producer's point "punching" through puts the image of more speed and force in my mind. Therefore, in my mind I see those gates that hold the shield open more like mirrors than dams.
Given that a craft can not simply punch through at a high enough speed there is something else the Empire has involved that would allow the wedges to move into position. Lowering the entire planet shield to "re-arm" would almost defeat the purpose as well as the name gate; and from the comment of "punching through" they do not lower the shield. I am still looking to see if there is any mention of a material or coating for the wedges of the gate that makes them special, but i do not think that the movie was worried about this.
Edit:
I was hoping this article would have more details, but it does not. Still very interesting to see the concept art and some of the earlier ideas.


text:
Q: Error when I try to create files using wsimport on a WSDL exposed over https I am using Apache Geronimo Server for my Development. I need to generate code from a WSDL exposed over https. I used the following command:
wsimport -keep -verbose https://devurl:7443/process-engine/soap/CustomerByNumber_v1?wsdl

But I am getting this error:

parsing WSDL...
[ERROR] Received fatal alert: protocol_version
Failed to read the WSDL document: https://devurl:7443/process-engine/soap/CustomerByNumber_v1?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not wsdl:definitions.
[ERROR] failed.noservice=Could not find wsdl:service in the provided WSDL(s):
At least one WSDL with at least one service definition needs to be provided.
Failed to parse the WSDL.

When we hit the WSDL URLs it has a username/password authentication.
How can I solve this problem?

A: The error message mentions the possible reasons:

*

*could not find the document;

*the document could not be read;

*the root element of the document is not <wsdl:definitions>.

You mention that the service requires username/password authentication. Is that the case for accesing the WSDL also? So the protocol might not necessarily be the problem.
Do the following:

*

*open the WSDL URL in the browser. Your browser will have no issue with HTTPS.

*provide username/password if it is required to access the WSDL.

*make sure the document that opens is a WSDL and contains a <wsdl:definitions> root element.

*download the WSDL to your computer with a .wsdl extension.

*use wsimport with this file: wsimport -keep -verbose yourSavedFile.wsdl


text:
Q: Server error in '/' application on selecting any country list from dropdown list in sitecore I have sucessfully redirect one of my page to 404 error page using redirection in sitecore. Problem is when i am selecting any country from dropdown list i am getting below error :

"Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.
  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.
  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."

I don't want to compromise with security by setting 'enableEventValidation = false'. By doing so its working fine but i am in need of some alternate solution. And, yes my dropdown binding is inside !postback too.
and even I tried to register ClientScriptManager.RegisterForEventValidation method as suggested in one of blog but it did not worked.
Some code part of 404 page is :
using System;

using Business;

using Sitecore.Data.Items;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Sitecore.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using Sitecore.Diagnostics;
using System.Web;
using Sitecore.Data.Fields;

/// <summary>
/// title link list control
/// </summary>
public partial class ErrorPage_Link_List : System.Web.UI.UserControl
{
    int counter = 0;

    /// <summary>
    /// Gets the datasource item.
    /// </summary>
    /// <value>
    /// The datasource item.
    /// </value>
    internal Item DatasourceItem
    {
        get { return this.GetDataSourceItem(); }
    }

    /// <summary>
    /// Gets the title.
    /// </summary>
    /// <value>
    /// The title.
    /// </value>
    protected string Title
    {
        get { return DatasourceItem.Name; }
    }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        base.Render(writer);

        // Apply Response Headers
        HttpContext.Current.Response.TrySkipIisCustomErrors = true;
        HttpContext.Current.Response.StatusCode = 404;
        HttpContext.Current.Response.StatusDescription = "404 Not Found";
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //gets the items that has the Checkbox "Show In Sitemap" Checked from, current item datasource
            //and innovative aproach and about avanade
            var source = DatasourceItem.Children.Where(c => c["Show in SiteMap"] == "1").ToList();

            Item innovApproach = Sitecore.Context.Database.GetItem(Constants.ItemsID.InnovativeApproach);
            foreach (Item item1 in innovApproach.Children.Where(c => c["Show in SiteMap"] == "1"))
            {
                source.Add(item1);
            }

            source.Add(Sitecore.Context.Database.GetItem(Constants.ItemsID.CustomerResults));

            Item servAndSol = Sitecore.Context.Database.GetItem(Constants.ItemsID.AboutAvanade);
            foreach (Item item in servAndSol.Children.Where(c => c["Show in SiteMap"] == "1"))
            {
                source.Add(item);
            }

            rptSection.DataSource = source;
            rptSection.DataBind();
        }
        catch (Exception ex)
        {
            Log.Error(string.Format("ErrorPage_Link_List.PageLoad() - {0}", ex.Message), ex, ex.TargetSite);
        }
    }

    /// <summary>
    /// Working with sections
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rptSection_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {

            //Finding item title, rptLinkItem repeater and the actual item to work with.
            HtmlGenericControl clearDiv = e.Item.FindControl("clearDiv") as HtmlGenericControl;
            HtmlGenericControl itemTitle = e.Item.FindControl("title") as HtmlGenericControl;
            HtmlGenericControl subtitle = e.Item.FindControl("subtitle") as HtmlGenericControl;
            Repeater rptLinkItem = e.Item.FindControl("rptLinkItem") as Repeater;
            Item srcItem = (Item)e.Item.DataItem;
            IEnumerable<Item> dataSource = null;
            if (srcItem.ID.ToString().Equals(Constants.ItemsID.Careers2))
                dataSource = ((Sitecore.Data.Fields.MultilistField)srcItem.Fields[Constants.Fields.SiteMap]).GetItems().ToList();
            else
                dataSource = SitecoreExtensions.GetItemsFromCustomMultiList(srcItem, Constants.Fields.SiteMap).Where(c => c.IsActive()).ToList();
            if (dataSource.Count() > 0)
            {
                if (!string.IsNullOrEmpty(srcItem[Constants.Fields.SectionName]))
                {
                    itemTitle.InnerHtml = srcItem[Constants.Fields.SectionName];
                }
                else
                {
                    itemTitle.InnerHtml = srcItem[Constants.Fields.Title];
                }

                //Bind the rptLinkItem repeater with the item children that are active
                rptLinkItem.DataSource = dataSource;
                rptLinkItem.DataBind();

                counter++;
                if (counter == 4)
                {
                    clearDiv.Attributes.Add("class", "clearBoth");
                    counter = 0;
                }

            }

        }
        catch (Exception ex)
        {
            Log.Error(string.Format("ErrorPage_Link_List.rptSection_ItemDataBound() - {0}", ex.Message), ex, ex.TargetSite);
        }
    }

    /// <summary>
    /// Working with link items
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rptLinkItem_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            //Finding item title and the actual item to work with.
            HtmlAnchor itemTitle = e.Item.FindControl("linkItem") as HtmlAnchor;
            Item srcItem = (Item)e.Item.DataItem;

            itemTitle.InnerText = srcItem["Title"];

            if (srcItem.HasPresentation())
            {
                //itemTitle.HRef = srcItem.Paths.FullPath;
                itemTitle.HRef = Sitecore.Links.LinkManager.GetItemUrl(srcItem);
            }
            else
            {
                var itemChild = ((Sitecore.Data.Fields.MultilistField)srcItem.Fields["Position override"]).GetItems().First();
                itemTitle.HRef = Sitecore.Links.LinkManager.GetItemUrl(itemChild);
            }
            if (srcItem.ID.ToString().Equals(Business.Constants.ItemsID.SearchJobsPage))
            {

                LinkField url = srcItem.Fields[Business.Constants.Fields.LinkUrlSection];
                itemTitle.HRef = url.Url;
                itemTitle.Target = url.Target;
            }

            if (srcItem.ID.ToString().Equals(Business.Constants.ItemsID.FeaturedCaseStudies))
            {
                //Redirect Featured-Case-Studies to Customer-Results
                Item item = Sitecore.Context.Database.Items.GetItem(Constants.ItemsID.CustomerResults);
                itemTitle.InnerText = itemTitle.Title = srcItem[Constants.Fields.Title];
                itemTitle.HRef = Sitecore.Links.LinkManager.GetItemUrl(item);
            }   /* End Defect no 208947 and */
        }
        catch (Exception ex)
        {
            Log.Error(string.Format("ErrorPage_Link_Lis.rptLinkItem_ItemDataBound() - {0}", ex.Message), ex, ex.TargetSite);
        }
    }

}

}`

A: It looks like you need to do your databinding within a !IsPostback block rather than every page load.
There are similar scenarios here.
"Invalid postback or callback argument" with Databound controls

A: I got it on code review of above code, the response headers:
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
  HttpContext.Current.Response.StatusCode = 404;
  HttpContext.Current.Response.StatusDescription = "404 Not Found";
  HttpContext.Current.Response.End();
were the main issue of this, presence of HttpContext.Current.Response.End(); was being harmful in code and it was never needed for any type of connection in website so I removed the same and problem got resolved.  I have understood that any code after Response.End() will not execute. Hope its right to do so.
Now my error page is working fine.
Can get more explanation from [Response.End() vs HttpContext.Current.ApplicationInstance.CompleteRequest()


text:
Q: Finding matrices $X,Y$ such that $XY - YX = \left[\begin{smallmatrix}0&1&1\\1&0&1\\1&1&0\end{smallmatrix}\right]$
Can anyone help me to find the matrices $X$ and $Y$ such that
$$XY - YX = \begin{bmatrix} 0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0   \end{bmatrix}$$

I was trying to randomly choose  $A , B$ and test if they work.

A: If the field is of characteristic zero, there are infinitely many solutions. One class of solutions that can be easily obtained is given by a diagonal matrix $X$ with distinct diagonal entries. E.g.
$$
X=\pmatrix{0\\ &1\\ &&2}\Rightarrow Y=\pmatrix{\ast&-1&-\frac12\\ 1&\ast&-1\\ \frac12&1&\ast}
$$
where the entries marked by asterisks are arbitrary.
More specifically, when an $n\times n$ matrix $A$ has a zero diagonal (i.e. it is a hollow matrix) and $X=\operatorname{diag}(x_1,\ldots,x_n)$ has distinct diagonal entries, the equation $XY-YX=A$ gives rise to $(x_i-x_j)y_{ij}=a_{ij}$. Therefore $y_{ij}=a_{ij}/(x_i-x_j)$ when $i\ne j$ and $y_{ii}$ is arbitrary.
More generally, over an arbitrary field, it is known that every traceless matrix (including but not limited to hollow matrices) can be written as a commutator. See A. A. Albert and Benjamin Muckenhoupt (1957), On matrices of trace zeros, Michigan Math. J., 4(1):1-3.

A: A complementary answer to the answer by user1551.
Let $A:=\begin{bmatrix} 0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0   \end{bmatrix}$.
Let us use notation $[X,Y]:=XY-YX$.
Let $F_X : Y \mapsto [X,Y]$.
It is a linear operator from the vector space of $3 \times 3$ matrices on itself.
For any $X \ne 0$, the kernel $K$ of $F_X$ has in general a dimension 3 with basis $\{I_3, X, X^2\}.$
Indeed; or any $n$, $ \ F_X(X^n)=[X,X^n]=X^{n+1}-X^{n+1}=0$, therefore $X^n$ belongs to $K$ for any $n$ but because of Cayley-Hamilton theorem, powers above $2$ can be expressed as polynomials in $I,X,X^2$. For a completely rigorous proof, see this answer.
Therefore if $(X_0,Y_0)$ is a solution to the equation $[X,Y]=A$, $(X_0,Y_0+aI+bX_0+cX_0^2)$  is as well a solution, for any $a,b,c \in \mathbb{R}$.
Connected: https://math.stackexchange.com/q/1223984.
Remark: Operator $F_X$ could be given a form using Kronecker product.


text:
Q: spam problem related to reverse dns config I have a client whose ISP recently switched their circuit and static IP to an IP that was already blacklisted for SPAM (nice).
The client is running Windows SBS 2003 with Exchange 2003 and DNS for the mail system is managed by GoDaddy.com.
When I ran the smtp test at  http://mxtoolbox.com (MXTB) I was receiving a warning 'Reverse DNS does not match SMTP Banner' after the IP switch and updating the hosted DNS records (A, MX, etc...) at GoDaddy.  I was able to squash that warning by setting the FQDN and Masquerade domain on advanced delivery options for the SMTP service in Exchange to the value returned on reverse DNS at MXTB (i.e., pool-##-###-###-##.fairpoint.east.myfairpoint.net - guess who gave us a dirty IP).  I also added an SPF record for all A records on the GoDaddy account.  It's been about 12 hours since these changes were made but my client's domain is still showing on a couple blacklists, spamrats in particular and when I use their delist form it still complains about a failed reverse DNS lookup.
Here are the lookups I get in terminal (obfuscated):
nslookup 66.###.###.53
Non-authoritative answer:
53.###.###.66.in.addr.arpa     name = pool-66-###-###-53.man.east.myfairpoint.net
nslookup clientdomain.com
Non-authoritative answer:
Name:     clientdomain.com
Address: 66.###.###.53
Not being an Exchange expert I could use some direction and/or a sanity check:
1 - should FQDN and masquerade in Exchange be set to the long form name noted (pool-##-###-###-##.fairpoint.east.myfairpoint.net) or just mail.clientdomain.com?
2 - is this likely a propagation problem and I just need to be more patient?
3 - shouldn't the ISP be able to resolve the reverse lookup correctly for us since they own the IP?
Right now client users are being bounced by some (not all) mail servers on send related to being listed.
Many thanks.

A: A couple of things I would recommend. In my opinion this may be the easiest way to set things up without getting in to a lot of unneccessary details. For more info than I'm providing, follow the link that SmallClanger posted in his answer.

*

*You don't need to set the masquerade domain but you should set the FQDN on the SMTP virtual server in Exchange.

*Set the FQDN in Exchange to match the name you're going to set in your MX record. This is probably going to be something akin to mail.clientdomain.com.

*Set your SPF record to "v=spf1 mx -all".

*Ask the ISP to create or modify the PTR record to match the FQDN that you set on Exchange.
This is a very simple answer that does not consider any additional variables or a more complex set up or requirements.

A: Sorry if i haven't read your post carefully enough, but you realize the reverse record is 'owned' by your ISP? You say you changed some record at GoDaddy... just wondering if you're getting your forward and reverse records confused. If so, contact your ISP and have them set their DNS for the IP to your FQDN
What i'm trying to say is that where DNS is concerned...

*

*you have the right to tell the world: "foodomain.com." points to "1.2.3.4"

but

*

*your ISP is the one who can tell the world: "1.2.3.4" points to "foodomain.com."

If both records don't match, it causes problems with certs, etc

A: Often it just takes time for blocklists to drop IPs from their lists. Depending on their implementation it could be 24 hours, or it could be a month. Each list's own FAQ should tell you how long. They often have a removal request system you can go through if the delay is going to be too long. (Some will even charge for express de-listing, as if this wasn't a massive conflict of interest.)
It isn't necessary for the PTR record for your IP to match either the SMTP EHLO or the mail domain. It wouldn't hurt, but in many cases (especially if you don't have a static IP), it's impossible.  I don't recommend going the other way and setting your EHLO greeting to match the PTR record, since that certainly won't match your mail domain, which is certain to result in more dropped mail than you're currently seeing.
Any recipient that blocks because the PTR doesn't match is broken.


text:
Q: Express.js - abort request on timeout I am exploring ways to abort client requests that are taking too long, thereby consuming server resources.
Having read some sources (see below), I tried a solution like the following (as suggested here):
const express = require('express');
const server = express();
server
    .use((req, res, next) => {
        req.setTimeout(5000, () => {
            console.log('req timeout!');
            res.status(400).send('Request timeout');
        });
        res.setTimeout(5000, () => {
            console.log('res timeout!');
            res.status(400).send('Request timeout');
        });
        next();
    })
    .use(...) // more stuff here, of course
    .listen(3000);

However, it seems not to work: the callbacks are never called, and the request is not interrupted.
Yet, according to recent posts, it should.
Apart from setting the timeout globally (i.e. server.setTimeout(...)), which would not suit my use case,
I have seen many suggesting the connect-timeout middleware.
However, I read in its docs that
While the library will emit a 'timeout' event when requests exceed the given timeout, node will continue processing the slow request until it terminates.
Slow requests will continue to use CPU and memory, even if you are returning a HTTP response in the timeout callback.
For better control over CPU/memory, you may need to find the events that are taking a long time (3rd party HTTP requests, disk I/O, database calls)
and find a way to cancel them, and/or close the attached sockets.

It is not clear to me how to "find the events that are taking long time" and "a way to cancel them",
so I was wondering if someone could share their suggestions.
Is this even the right way to go, or is there a more modern, "standard" approach?
Specs:

*

*Node 12.22

*Ubuntu 18.04

*Linux 5.4.0-87-generic

Sources:

*

*Express.js Response Timeout

*Express.js connect timeout vs. server timeout

*Express issue 3330 on GitHub

*Express issue 4664 on GitHub
Edit:
I have seen some answers and comments offering a way to setup a timeout on responses or "request handlers": in other words, the time taken by the middleware is measured, and aborted if it takes too long. However, I was seeking for a way to timeout requests, for example in the case of a client sending a large file over a slow connection. This happens probably even before the first handler in the express router, and that is why I suspect that there must be some kind of setting at the server level.

A: Before rejecting long request, I think, it's better to measure requests, find long ones, and optimize them. if it is possible.
How to measure requests?
Simplest way it is to measure time from start, till end of request. You'll get Request Time Taken = time in nodejs event loop + time in your nodejs code + wait for setTimeout time + wait for remote http/db/etc services
If you don't have many setTimeout's in code, then Request Time Taken is a good metric.
(But in high load situations, it becomes unreliable, it is greatly affected by time in event loop )
So you can try this measure and log solution
http://www.sheshbabu.com/posts/measuring-response-times-of-express-route-handlers/
How to abort long request
it all depends on your request handler
Handler does Heavy computing
In case of heavy computing, which block main thread, there's noting you can do without rewriting handler.
if you set req.setTimeout(5000, ...) - it fires after res.send(), when main loop will be unlocked
 function (req, res) {
  for (let i = 0; i < 1000000000; i++) {
    //blocking main thread loop
  }
  res.send("halted " + timeTakenMs(req));
}

So you can make your code async, by injecting setTimeout(, 0) some where;
or move computing to worker thread
Handler has many remote requests
I simulate remote requests with Promisfied setTimeout
async function (req, res) {
    let delayMs = 500;
    await delay(delayMs); // maybe axios http call
    await delay(delayMs); // maybe slow db query
    await delay(delayMs);
    await delay(delayMs);
    res.send("long delayed" + timeTakenMs(req));
  }

In this case you can inject some helpers to abort your request chain
blockLongRequest - throws error if request time is too big;
async function (req, res) {
    let delayMs = 500;
    await delay(delayMs); // mayby axios call
    blockLongRequest(req);
    await delay(delayMs); // maybe db slow query
    blockLongRequest(req);
    await delay(delayMs);
    blockLongRequest(req);
    await delay(delayMs);
    res.send("long delayed" + timeTakenMs(req));
  })

single remote request
function (req, res) {
    let delayMs = 1000;
    await delay(delayMs);
    //blockLongRequest(req);
    res.send("delayed " + timeTakenMks(req));
}

we don't use blockLongRequest because it's better to deliver answer instead of error.
Error may trigger client to retry, and you get your slow requests doubled.
Full example
(sorry for TypeScript, yarn ts-node sever.ts )
import express, { Request, Response, NextFunction } from "express";

declare global {
  namespace Express {
    export interface Request {
      start?: bigint;
    }
  }
}

const server = express();
server.use((req, res, next) => {
  req["start"] = process.hrtime.bigint();
  next();
});
server.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.error("Error captured:", err.stack);
  res.status(500).send(err.message);
});

server.get("/", function (req, res) {
  res.send("pong " + timeTakenMks(req));
});
server.get("/halt", function (req, res) {
  for (let i = 0; i < 1000000000; i++) {
    //halting loop
  }
  res.send("halted " + timeTakenMks(req));
});
server.get(
  "/delay",
  expressAsyncHandler(async function (req, res) {
    let delayMs = 1000;
    await delay(delayMs);
    blockLongRequest(req); //actually no need for it
    res.send("delayed " + timeTakenMks(req));
  })
);
server.get(
  "/long_delay",
  expressAsyncHandler(async function (req, res) {
    let delayMs = 500;
    await delay(delayMs); // mayby axios call
    blockLongRequest(req);
    await delay(delayMs); // maybe db slow query
    blockLongRequest(req);
    await delay(delayMs);
    blockLongRequest(req);
    await delay(delayMs);
    res.send("long delayed" + timeTakenMks(req));
  })
);

server.listen(3000, () => {
  console.log("Ready on 3000");
});

function delay(delayTs: number): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, delayTs);
  });
}
function timeTakenMks(req: Request) {
  if (!req.start) {
    return 0;
  }
  const now = process.hrtime.bigint();
  const taken = now - req.start;

  return taken / BigInt(1000);
}
function blockLongRequest(req: Request) {
  const timeTaken = timeTakenMks(req);
  if (timeTaken > 1000000) {
    throw Error("slow request - aborting after " + timeTaken + " mks");
  }
}

function expressAsyncHandler(
  fn: express.RequestHandler
): express.RequestHandler {
  return function asyncUtilWrap(...args) {
    const fnReturn = fn(...args);
    const next = args[args.length - 1] as any;
    return Promise.resolve(fnReturn).catch(next);
  };
}

I hope, this approach helps you to find an acceptable solution


text:
Q: apache tomcat creating new instance of sqlite database in java I am using an sqlite database in java using xerial sqlite jdbc driver in order to store some data, 1 connection at a time.
It worked fine until I decided to use Apache tomcat on my server instead of java sockets (used for testing) and I noticed my queries yielded null results despite data being on the database.
I searched this issue and apparently tomcat creates a new instance of this database, which has the same tables but has no data.
I tried moving my database into the resource folder but this did not help.
public static Connection getConn() throws SQLException {
      if(c == null){
         c = DriverManager.getConnection("jdbc:sqlite:database.db");
      }
      return c;
   }

this is how the code connects to the database. I believe moving the database and changing the address should solve the issue but I dont know where to.
thanks!

A: You should be able to use the full path to your existing database file in your JDBC URL - so, something like:
"jdbc:sqlite:/path/to/your/mysqlite.db"

If you are on Windows, then it might look like this:
"jdbc:sqlite:C:/path/to/your/mysqlite.db"

These are examples of absolute paths.
In your case, the database location in your JDBC URL is simply mysqlite.db, with no additional path information. This is a relative path, because it does not start with a slash or a drive letter.
This means the location of the DB file is relative to the working directory of the Java program (where the program was started). In the case of Tomcat, that is typically the CATALINA_HOME/bin directory - where CATALINA_HOME is typically the location where Tomcat was installed. (This may vary depending on how Tomcat was installed and launched.)
I would recommend you keep the database file in a separate location from Tomcat.
(SQLite will create a new, empty database in the specified location, if one does not already exist - so it's not Tomcat which is creating it, but rather the SQLite driver).


text:
Q: Warning message when launch a map by UIApplication sharedApplication I link the following openMap method to a button. The method does work but there is an error message at
NSLog(urlText);

The message shows format string is not a literal (potentially insecure).
Does anyone know how to eliminate this warning?
-(IBAction)openMap:(id)sender{
    NSString* addressText = @"New York";
    addressText =  [addressText stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
    NSString* urlText = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", addressText];
    NSLog(urlText);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]];
}

A: Change the NSLog to,
NSLog(@"%@", urlText);

Or, remove the NSLog completely ;-)