text:
Q: Recreating secure token functionality from C# into Java I have an application I am converting from C# to Java (eventually I want to make this an android app).
To give some background: the application connects to a web server, with a JSON formatted request for a 'key' to log in. Within the JSON is a token which is generated by the following code:
public static string GenToken(string secret, string str)
    {
        string token;
        using (var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(str)))
        {

            using (var hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret)))
            {
                var hash = hmac.ComputeHash(stream);
                var hashStr = BitConverter.ToString(hash);
                token = string.Format("{0}.{1}", hashStr.Replace("-", ""), str);

            }
        }

        return Convert.ToBase64String(Encoding.UTF8.GetBytes(token));
    }

The closest I have found is some code I found here but this is still not producing the same result as the C# code.
What I need is something that will produce the same result in Java as this bit of c# code. Otherwise the authentication fails.
For reference, I am testing using the values:
secret = 7353388933d07b2a1ef462c9d3f4e8ca;
str = {"userId":"bcf4fc83-291a-11e7-9def-06948e004f29","expires":1516015203090}

This outputs
OTQyMDk1NTI2Mzc3NDYyRjk1RTYzQzUzNUVCNzg3MDQ1NjlBNDQ5OEM1MTM1N0I2QTQ3REY1OTA5M0Q3MjMzQS57InVzZXJJZCI6ImJjZjRmYzgzLTI5MWEtMTFlNy05ZGVmLTA2OTQ4ZTAwNGYyOSIsImV4cGlyZXMiOjE1MTYwMTUyMDMwOTB9

EDIT
I have gotten as far as realising that
using (var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(str)))

Is producing a hex value of
 7B-22-75-73-65-72-49-64-22-3A-22-62-63-66-34-66-63-38-33-2D-32-39-31-61-2D-31-31-65-37-2D-39-64-65-66-2D-30-36-39-34-38-65-30-30-34-66-32-39-22-2C-22-65-78-70-69-72-65-73-22-3A-31-35-31-36-30-31-35-32-30-33-30-39-30-7D

Which I have been able to do with the following in Java (removing the need to replace the dashes)
public static String toHex(String arg) {
    return String.format("%040X", new BigInteger(1, arg.getBytes(StandardCharsets.UTF_8)));
}

But I'm well and truly stuck after this point.
Thanks in advance

A: The C# code:

*

*converts the hash to its hexadecimal representation hashStr. To convert a byte array to a hexadecimal string in Java see this post.

*removes "-" that were introduced by BitConverter. You won't need to do this in Java, since adding "-" is specific to BitConverter.

*concatenates hashStr and str with a dot in between to get a token. This is trivial in Java: token = hashStr + "." + str.

*converts the token to a base64 encoding. To do this in Java, use Base64.encodeBase64String as was done in your example
The code you're referring to does not perform these steps. Did you consider adding these steps to the Java code?


text:
Q: make dataframe from data in textfile I got textfile in unorganized way that I need to make from it an organized dataframe.
I used the code:
text = sc.textFile(...)
log = text.map (...).filter(...)

so each element in log is in the following format from the text:
name: server-link
description: success scanning
auth_code: 123456789

now, I want to make a dataframe with the column names ['Name', 'Description', 'auth_code'] that will be contains all the information from all the elements in log.
How can i do it?
Thanks!

A: One way of building dataframes is to first create a normal python list of lists, where the first line contains the column headings, and the rest of the lines are the dataframe values. Such a list-list is then turned into a dataframe by the command:
df = pd.DataFrame(table[1:], columns=table[0])

In your case you want to read your input three lines at a time and from that build the table. E.g. something like (not tested):
lines = text.split('\n')
table = [('name','description','auth_code')]
i=0
while i<len(lines):
    row = [line[3*i+j].split(': ')[1]
           for j in range(3)]
    table += [row]
    i+= 1
df = pd.DataFrame(table[1:],columns=table[0])

redpajama_set_name: RedPajamaStackExchange


text:
Q: "ReferenceError: angular is not defined" with code that was already used before successfully I get "ReferenceError: angular is not defined". The funny thing is, I copied the structure of my app from another working Webapp I made and just changed the names so far, I have no idea what I may have changed that causes trouble now.
I double checked the order of the script tags and tried every other solution I found but nothing's worked so far.
This is my HTML:
<!DOCTYPE html>

    <title>Vet & Care Webapp</title>
    <meta charset="utf-8">
    <meta name="robots" content="noindex,nofollow">
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />

    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="Vet & Care">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

And my module and MainCtrl in app.js:
var app = angular.module('VetCare', ['ngCookies', 'ngRoute', 'ngAnimate', 'ui.bootstrap']);

app.controller('MainCtrl', ['$scope', '$cookies', '$window', function($scope, $cookies, $window) {

    $scope.redirect = function () {
        //some code
    };
}]);

A: Try moving your scripts to the bottom of your body.
When angular.min.js is loaded, angular walks the DOM and bootstraps the ng-app. In this case your dom is empty when angular walks your DOM.
By having your scripts at the bottom of the body block, angular will walk the DOM and bootstraps the app when the DOM is ready.
It'll also optimize the loading of your webpage by rendering the page while the JS files are being downloaded.

A: Have you tried moving the scripts from  to above the app.js at the end of body?

If that doesn't help, do you get the correct response from loading angular.min.js in network tab in developer tools ?


text:
Q: scrollTop() not working after applying overflow values with jQuery? I'm using Chris Coyier's plugin (actually, it is a modified version by Devin Sturgeon) to animate scrolling to anchor links:
// Easing for links pointing to anchors
$(document).ready(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

It works perfectly until I apply overflow values with jQuery. For example, after I close a modal window, this piece of code is in charge of hiding horizontal overflow and setting vertical overflow to auto:
$('.file-content a.close-reveal-modal').on('click', function() {
  $('html, body').css({
    'overflow-y' : 'auto',
    'overflow-x' : 'hidden'
  });
});

After those values are applied, the plugin to animate scrolling to anchor links stops working, clicking on them doesn't produce any result whatsoever. If I remove the code in charge of setting the overflows when closing a modal, Chris' plugin works like a charm every single time.
Why is this happening?
Any sort of help will be very much appreciated!

A: I don't know if this could help you, but here is a hint that I have found:
http://upshots.org/javascript/jquery-get-real-height-of-hidden-or-overflow-hidden-elements
Did you try to debug it?
Because I suspect that in your example

target.offset().top

returns zero


text:
Q: C#-like extension methods in PHP? I like the way in C# where you can write an extension method, and then do things like this:
string ourString = "hello";
ourString.MyExtension("another");

or even
"hello".MyExtention("another");

Is there a way to have similar behavior in PHP?

A: I have another implementation for that in PHP >= 5.3.0 and its like a Decorator that Northborn Design explained.
All we need is an API to create extensions and a decorator to apply the extensions.
We have to remember that on C# extension methods they do not break the encapsulation of the object extended, and they do not modify the object (no point for that, instead implementing the method would be more effective). And the extensions methods are pure static and they receive the instance of the object, like in the example below (C#, from MSDN):
public static int WordCount(this String str)
{
    return str.Split(new char[] { ' ', '.', '?' },
                     StringSplitOptions.RemoveEmptyEntries).Length;
}

Of course we do not have String objects in PHP, but for all other objects we can create generic decorators to that kind of wizardry.
Lets see my implementation for that:
The API:
<?php

namespace Pattern\Extension;

/**
 * API for extension methods in PHP (like C#).
 */
class Extension
{
    /**
     * Apply extension to an instance.
     *
     * @param object $instance
     * @return \Pattern\Extension\ExtensionWrapper
     */
    public function __invoke($instance)
    {
        return Extension::apply($instance);
    }

    /**
     * Apply extension to an instance.
     *
     * @param object $instance
     * @return \Pattern\Extension\ExtensionWrapper
     */
    public static function apply($instance)
    {
        return new ExtensionWrapper($instance, \get_called_class());
    }

    /**
     * @param mixed $instance
     * @return boolean
     */
    public static function isExtensible($instance)
    {
        return ($instance instanceof Extensible);
    }
}
?>

The Decorator:
<?php

namespace Pattern\Extension;

/**
 * Demarcate decorators that resolve the extension.
 */
interface Extensible
{
    /**
     * Verify the instance of the holded object.
     *
     * @param string $className
     * @return bool true if the instance is of the type $className, false otherwise.
     */
    public function holdsInstanceOf($className);

    /**
     * Returns the wrapped object.
     * If the wrapped object is a Extensible the returns the unwrap of it and so on.
     *
     * @return mixed
     */
    public function unwrap();

    /**
     * Magic method for the extension methods.
     *
     * @param string $name
     * @param array $args
     * @return mixed
     */
    public function __call($name, array $args);
}
?>

And the generic implementation:
<?php

namespace Pattern\Extension;

/**
 * Generic version for the Extensible Interface.
 */
final class ExtensionWrapper implements Extensible
{
    /**
     * @var mixed
     */
    private $that;

    /**
     * @var Extension
     */
    private $extension;

    /**
     * @param object $instance
     * @param string | Extension $extensionClass
     * @throws \InvalidArgumentException
     */
    public function __construct($instance, $extensionClass)
    {
        if (!\is_object($instance)) {
            throw new \InvalidArgumentException('ExtensionWrapper works only with objects.');
        }

        $this->that = $instance;
        $this->extension = $extensionClass;
    }

    /**
     * {@inheritDoc}
     * @see \Pattern\Extension\Extensible::__call()
     */
    public function __call($name, array $args)
    {
        $call = null;
        if (\method_exists($this->extension, '_'.$name)) {
            // this is for abstract default interface implementation
            \array_unshift($args, $this->unwrap());
            $call = array($this->extension, '_'.$name);
        } elseif (\method_exists($this->extension, $name)) {
            // this is for real implementations
            \array_unshift($args, $this->unwrap());
            $call = array($this->extension, $name);
        } else {
            // this is for real call on object
            $call = array($this->that, $name);
        }
        return \call_user_func_array($call, $args);
    }

    /**
     * {@inheritDoc}
     * @see \Pattern\Extension\Extensible::unwrap()
     */
    public function unwrap()
    {
        return (Extension::isExtensible($this->that) ? $this->that->unwrap() : $this->that);
    }

    /**
     * {@inheritDoc}
     * @see \Pattern\Extension\Extensible::holdsInstanceof()
     */
    public function holdsInstanceOf($className)
    {
        return \is_a($this->unwrap(), $className);
    }
}
?>

The Use:
Assume a Third party Class exists:
class ThirdPartyHello
{
    public function sayHello()
    {
        return "Hello";
    }
}

Create your extension:
use Pattern\Extension\Extension;

class HelloWorldExtension extends Extension
{
    public static function sayHelloWorld(ThirdPartyHello $that)
    {
        return $that->sayHello().' World!';
    }
}

Plus: For Interface Lovers, create an Abstract Extension:
<?php
interface HelloInterfaceExtension
{
    public function sayHelloFromInterface();
}
?>
<?php
use Pattern\Extension\Extension;

abstract class AbstractHelloExtension extends Extension implements HelloInterfaceExtension
{
    public static function _sayHelloFromInterface(ThirdPartyOrLegacyClass $that)
    {
        return $that->sayHello(). ' from Hello Interface';
    }
}
?>

Then use it:
////////////////////////////
// You can hide this snippet in a Dependency Injection method

$thatClass = new ThirdPartyHello();

/** @var ThirdPartyHello|HelloWorldExtension $extension */
$extension = HelloWorldExtension::apply($thatClass);

//////////////////////////////////////////

$extension->sayHello(); // returns 'Hello'
$extension->sayHelloWorld(); // returns 'Hello World!'

//////////////////////////////////////////
// Abstract extension

$thatClass = new ThirdPartyHello();

/** @var ThirdPartyHello|HelloInterfaceExtension $extension */
$extension = AbstractHelloExtension::apply($instance);

$extension->sayHello(); // returns 'Hello'
$extension->sayHelloFromInterface(); // returns 'Hello from Hello Interface'

Pros:

*

*Very similar way of C# extension methods in PHP;

*Cannot test directly an extension instance as an instance of the extended object, but this is nice because its more secure because we can have places where the instance of that classe is not extended;

*As the intent of a framework to improve agility of the team you have to write less;

*The extension use seems to be part of the object but its is just decorated (maybe this is interesting to teams to develop fast but review in future the implementation of that extended object if legacy is involved);

*You can use the static method of the extension directly for performance improvements but doing that you lose the capacity to mock parts of your code (DI is highly indicated).

Cons:

*

*The extension must be declared to the object, Its is not just as an import like in C#, you must "decorate" the desired instance to give extension to it.

*Cannot test directly an extension instance as an instance of the extended object, more code to test using the API;

*Performance drawbacks because of the use of magic methods (but when performance is needed we change language, recreate the core, use minimalist frameworks, assembler if its needed);

Here a Gist for that Api: https://gist.github.com/tennaito/9ab4331a4b837f836ccdee78ba58dff8

A: Since PHP 5.4 there are traits which can be used as extension methods.
Example:
<?php
trait HelloWorld {
    public function sayHelloWorld() {
        echo 'Hello World';
    }
}

class MyHelloWorld {
    use HelloWorld;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHelloWorld();
$o->sayExclamationMark();
?>

result:
Hello World!

Once You include a trait to a class, lets call it for example with a name Extension, You can add any methods You want and locate them elsewhere. Then in that example the use Extension becomes just one-time decoration for the extendable classes.

A: Moving away from the issue of non-object primitives in PHP, when dealing with actual classes in PHP, if your environment is sane, chances are you can decorate a given class to sort-of § emulate extension methods.
Given an interface and implementation:
interface FooInterface {
    function sayHello();
    function sayWorld();
}

class Foo implements FooInterface {
    public function sayHello() {
        echo 'Hello';
    }
    public function sayWorld() {
        echo 'World';
    }
}

So long as any dependencies on Foo are actually dependent on the interface FooInterface (this is what I mean about sane) you can implement FooInterface yourself as a wrapper to Foo, forward calls to Foo when necessary, and add additional methods as you need:
class DecoratedFoo implements FooInterface {
    private $foo;
    public function __construct(FooInterface $foo) {
        $this->foo = $foo;
    }
    public function sayHello() {
        $this->foo->sayHello();
    }
    public function sayWorld() {
        $this->foo->sayWorld();
    }
    public function sayDanke() {
        echo 'Danke';
    }
    public function sayShoen() {
        echo 'Shoen';
    }
}

The methods sayHello() and sayWorld() are patched through to the containing Foo object, however we've added sayDanke() and sayShoen().
The following:
function acceptsFooInterface(FooInterface $foo) {
    $foo->sayHello();
    $foo->sayWorld();
}

$foo = new Foo();
acceptsFooInterface($foo);

Works as expected, yielding HelloWorld; but so does this:
$decoratedFoo = new DecoratedFoo($foo);
acceptsFooInterface($decoratedFoo);

$decoratedFoo->sayDanke();
$decoratedFoo->sayShoen();

Which results in HelloWorldDankeShoen.
This is a limited use of the potential in the decorator pattern; you can modify the behavior of the implemented methods, or simply not forward them at all (however, we want to maintain the intended behavior by the original class definition in this example)
Is this a one-to-one solution for implementing extension methods (as per C#) in PHP? Nope, definitely not; but the extensibility afforded by this approach will help solve problems more loosely.

§ Figured I'd elaborate based on some chat conversation of the subject: you're never going to replicate it (not today, and probably not tommorow) in PHP, however the key in my answer is design patterns. They provide the opportunity to port strategies from one language to another when you can't necessarily (typically, or ever) port features.

A: You could if you reimplemented all your strings as objects.
class MyString {
    ...
    function foo () { ... }
}

$str = new MyString('Bar');
$str->foo('baz');

But you really wouldn't want to do this. PHP simply isn't an object oriented language at its core, strings are just primitive types and have no methods.
The 'Bar'->foo('baz') syntax is impossible to achieve in PHP without extending the core engine (which is not something you want to get into either, at least not for this purpose :)).

There's also nothing about extending the functionality of an object that makes it inherently better than simply writing a new function which accepts a primitive. In other words, the PHP equivalent to
"hello".MyExtention("another");

is
my_extension("hello", "another");

For all intends and purposes it has the same functionality, just different syntax.


text:
Q: Font Awesome 5.12.1: Brand Icons are rendered but solid icons not The problem
In my new project, I'm integrating Font Awesome by the use of the kit code. It is a free licence with the latest version enabled covering both solid and brand icons.
While brand icons appear without any problems, I'm not able to make solid icons work, i.e. they are shown as boxes.
My approach so far

*

*Checked the spelling of font-family: no mistakes

*Checked unicodes: anything okay

*Tried other solid icons: same problem

*Tried i-class approach: strangely works for solid icons, too.

So, what am I doing wrong? This problem is driving me nuts; and I have the dim feeling that the solution is just super easy.
Cheers
The Code

/* Font Awesome */

#benefits .wd-brand-icons::before {
  font-family: "Font Awesome 5 Brands";
  font-size: 48px;
  margin-left: -75px;
  margin-top: -5px;
  position: absolute;
}

#benefits .wd-solid-icons::before {
  font-family: "Font Awesome 5 Free";
  font-size: 48px;
  margin-left: -75px;
  margin-top: -5px;
  position: absolute;
}

#benefits p.wd-icons {
  margin-left: 75px;
}

.wd-html5::before {
  content: "\f13b"; /* Brand icon works */
}

.wd-security::before {
  content: "\f3ed"; /* Solid icon does not */
}

.wd-plan::before {
  content: "\f542";
}

.wd-consulting::before {
  content: "\f4c4";
}

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                  HeadlineLorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos praesentium eveniet pariatur doloremque nemo soluta.

                  HeadlineLorem ipsum dolor sit amet, consectetur adipisicing elit. Porro quam error reprehenderit, veniam omnis, cum sequi fugit unde placeat nobis.

                  HeadlineLorem ipsum dolor sit amet, consectetur adipisicing elit. Illum quasi minima non, quia laudantium dignissimos, molestias dolore!

                  HeadlineLorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati, vel enim quos. Totam laudantium accusantium.


text:
Q: SQL query to join table with XML element and get nested element properties I have XML like below
<Parent>
    <BOMLine>
    **<partnumber>abc</partnumber>**
    <SortOrder>0</SortOrder>
    <Component>
      <PartNo>SE3008</PartNo>
      <Comp>12P6383X012</Comp>
      <CompDesc>SQ Controller</CompDesc>
      <Qty>1</Qty>
    </Component>
    <ChangeOrder>
      <Qty>10</Qty>
      <COId>AS</COId>
      <IsQtyLinked>false</IsQtyLinked>
    </ChangeOrder>
    <ChangeOrder>
      <Qty>10</Qty>
      <COId>AS1</COId>
      <IsQtyLinked>true</IsQtyLinked>
    </ChangeOrder>
  </BOMLine>
  <BOMLine> ....
</Parent>

and a temp table like this:

I want to join the xml and table on PartNumber properties and need the following output

And I don't want to use doc handle to handle xml,
Please help me to get the desired output.
I have tried following code, but I am confused how to get nested element from XML while joining.
DECLARE @TempTable TABLE (ID INT,
                          partnumber VARCHAR(200),
                          sortnumber INT)

INSERT INTO @TempTable (ID, partnumber, sortnumber)
VALUES (123, 'abc', 1)

  DECLARE @xml XML ='<Parent>
        <BOMLine>
        <partnumber>abc</partnumber>
        <SortOrder>0</SortOrder>
        <Component>
          <PartNo>SE3008</PartNo>
          <Comp>12P6383X012</Comp>
          <CompDesc>SQ Controller</CompDesc>
          <Qty>1</Qty>
        </Component>
        <ChangeOrder>
          <Qty>10</Qty>
          <COId>AS</COId>
          <IsQtyLinked>false</IsQtyLinked>
        </ChangeOrder>
        <ChangeOrder>
          <Qty>10</Qty>
          <COId>AS1</COId>
          <IsQtyLinked>true</IsQtyLinked>
        </ChangeOrder>
      </BOMLine>

     <BOMLine>
        <partnumber>abc</partnumber>
        <SortOrder>0</SortOrder>
        <Component>
          <PartNo>SE3008</PartNo>
          <Comp>12P6383X012</Comp>
          <CompDesc>SQ Controller</CompDesc>
          <Qty>1</Qty>
        </Component>
        <ChangeOrder>
          <Qty>10</Qty>
          <COId>AS</COId>
          <IsQtyLinked>false</IsQtyLinked>
        </ChangeOrder>
        <ChangeOrder>
          <Qty>10</Qty>
          <COId>AS1</COId>
          <IsQtyLinked>true</IsQtyLinked>
        </ChangeOrder>
      </BOMLine>
    </Parent> '

SELECT  TT.ID,
       TT.partnumber,
       B.CO.value('(Qty/text())[1]','int') AS Qty,
       B.CO.value('(COId/text())[1]','char(2)') AS COId,
       B.CO.value('(IsQtyLinked/text())[1]','varchar(5)') AS IsLinked
FROM @TempTable TT
     CROSS APPLY @xml.nodes('Parent/BOMLine') P(BOM)
     CROSS APPLY P.BOM.nodes('./ChangeOrder') B(CO)
WHERE TT.partnumber = P.BOM.value('(partnumber/text())[1]','varchar(3)');

A: You were close. This is the way I would do it with the sample data you've supplied:
SELECT TT.ID,
       TT.partnumber,
       B.CO.value('(Qty/text())[1]','int') AS Qty,
       B.CO.value('(COId/text())[1]','char(2)') AS COId,
       B.CO.value('(IsQtyLinked/text())[1]','varchar(5)') AS IsLinked
FROM @TempTable TT
     CROSS APPLY @xml.nodes('Parent/BOMLine') P(BOM)
     CROSS APPLY P.BOM.nodes('./ChangeOrder') B(CO)
WHERE TT.partnumber = P.BOM.value('(partnumber/text())[1]','varchar(3)');

Note I use nodes twice, once to get a row for each BOMLine, another for each ChangeOrder. I then use the WHERE to create an implicit JOIN to the table (@TempTable).
As this is sample data, note you may need to change the return data types from the XML to something more appropriate for your real data.


text:
Q: Replacing same strings but with different string values? This is the question.
(1)__ is also a  star.(2)__ revolves around the Sun.
edittext1: _______
edittext2: _______
So in the first blank, I am showing what the user type in edit text.
If he  types Sun,then the output will be like below.
(1)_Sun_is also a  star.(2)__ revolves around the Sun.
edittext1: Sun
edittext2: _______
So for (1) I am replacing "__" with my edit text value,as above.
How to do it with (2).
I tried the same logic with (2) but it replaces the first value also.
(1)Planets is also a  star.(2)Planets revolves around the Sun.
edittext1: Sun
edittext2: Planets
public class MainActivity extends AppCompatActivity {

    EditText ed1,ed2,ed3;
    String edtv1,edtv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ed1= (EditText) findViewById(R.id.editText);
        ed2= (EditText) findViewById(R.id.editText2);
        ed3= (EditText) findViewById(R.id.editText3);
        final TextView tv = (TextView) findViewById(R.id.textView);

        final String sentence = tv.getText().toString();

        if (ed1 != null) {
            ed1.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                    tv.setText(String.format("%s_", sentence.replace("__", "_" + s.toString())));
                }
            });
            edtv1 = ed1.getText().toString();

        }
        if (ed2 != null) {
            ed2.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                    tv.setText(String.format("%s_", sentence.replace("__", "_" + s.toString())));
                }
            });
            edtv2 = ed2.getText().toString();

        }

    }
}

The above is the full code.

A: String string = "(1)__ is also a star.(2)__ revolves around the Sun.";
//First do a string split:
// then you'll have an array of strings
String[] parts = string.split("__");

in the 2nd edit text listener, you can change the end of the 2nd element of the parts array.
In the first, you can change the end of the first element , and so on.
To display, just print out the entire string array

A: You can't.
You have to make first and second blank different to do accurate replace. You can do this by put different number of underscore
String sentence = "(1)___ is also a star.(2)__ revolves around the Sun.";

sentence.replace("___", "Sun");
sentence.replace("__", "Planet");

or you can include the number to differentiate the blank
String sentence = "(1)__ is also a star.(2)__ revolves around the Sun.";

sentence.replace("(1)__", "(1)" + "Sun");
sentence.replace("(2)__", "(2)" + "Planet");

A: You can use function below:
String s = "1 abc 1 def";
Log.e("Test", replace(s, "1", "1test", "2test")); --> value: 1test abc 2test def
// fuction to replace
private String replace(String source, String toReplace, String... replacements) {
    StringBuilder stringBuilder = new StringBuilder(source);
    int startIndex = 0;
    for (int i = 0; i < replacements.length; i++) {
        int index = stringBuilder.indexOf(toReplace, startIndex);
        if (startIndex < 0) {
            break;
        }
        stringBuilder.replace(index, index + toReplace.length(), replacements[i]);
        startIndex = index + replacements.length;
    }
    return stringBuilder.toString();
}


text:
Q: Um problema para resolver com expressões lambdas Fiz isso, para retornar uma lista. Acontece que dá erro, dizendo que não tem como transformar uma expressão anônima no tipo passado(objeto).
public List<Liberacao> PegaLiberacao()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(lib => new
                {
                    lib.t1.TipoVenda,
                    lib.t1.Vencimento,
                    lib.t1.Juros,
                    lib.t1.Entrada,
                    lib.t1.Acrescimo,
                    lib.t1.Desconto,
                    lib.t1.Mensagem,
                    lib.t1.DataLib,
                    lib.t1.Vendedor,
                    lib.t1.Cliente,
                    lib.t1.Filial,
                    lib.t2.Produto,
                    lib.t2.Qtde,
                    lib.t2.Unitario,
                    lib.t2.Custo,
                    lib.t2.CustoDiario,
                    lib.t2.UltCondicao,
                    lib.t2.Total
                }).ToList();

            return lista;
        }

E o erro é esse, ao retornar a minha lista:

EDIT1:
Essa é a minha model:
public class Autoriza
    {
        InetContext contexto = new InetContext();
        Liberacao liberacao = new Liberacao();

        public List<Liberacao> PegaLiberacao()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(lib => new Liberacao
                {
                    TipoVenda = lib.t1.TipoVenda,
                    Vencimento = lib.t1.Vencimento,
                    Juros = lib.t1.Juros,
                    Entrada = lib.t1.Entrada,
                    Acrescimo = lib.t1.Acrescimo,
                    Desconto = lib.t1.Desconto,
                    Mensagem = lib.t1.Mensagem,
                    DataLib = lib.t1.DataLib,
                    Vendedor = lib.t1.Vendedor,
                    Cliente = lib.t1.Cliente,
                    Filial = lib.t1.Filial
                }).ToList();

            return lista;
        }

        public List<ItensLib> PegaItensLib()
        {
            var lista = contexto.ItensLibs.Join(
                contexto.Liberacoes,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(itens => new ItensLib
                {
                    Produto = itens.t1.Produto,
                    Qtde = itens.t1.Qtde,
                    Unitario = itens.t1.Unitario,
                    Custo = itens.t1.Custo,
                    CustoDiario = itens.t1.CustoDiario,
                    UltCondicao = itens.t1.UltCondicao,
                    Total = itens.t1.Total
                }).ToList();

            return lista;
        }
    }

Aqui vai
[Table("LIBERACAO")]
    public class Liberacao
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("ID_LIBERACAO")]
        public int IdLiberacao { get; set; }
        [Column("FLAG_LIBERACAO")]
        public byte FlagLiberacao { get; set; }
        [Column("ID_ORCAMENTO")]
        public float IdOrcamento { get; set; }
        [Column("ID_VENDEDOR")]
        public int IdVendedor { get; set; }
        [Column("VENDEDOR")]
        public string Vendedor { get; set; }
        [Column("ID_FILIAL")]
        public int IdFilial { get; set; }
        [Column("FILIAL")]
        public string Filial { get; set; }
        [Column("DATALIB")]
        public float DataLib { get; set; }
        [Column("HORALIB")]
        public float HoraLib { get; set; }
        [Column("ID_CLIENTE")]
        public int IdCliente { get; set; }
        [Column("CLIENTE")]
        public string Cliente { get; set; }
        [Column("TIPO_VENDA")]
        public string TipoVenda { get; set; }
        [Column("JUROS")]
        public float Juros { get; set; }
        [Column("DESCONTO")]
        public float Desconto { get; set; }
        [Column("VENCIMENTO")]
        public float Vencimento { get; set; }
        [Column("ACRESCIMO")]
        public float Acrescimo { get; set; }
        [Column("ENTRADA")]
        public float Entrada { get; set; }
        [Column("PRAZO")]
        public float Prazo { get; set; }
        [Column("TOTAL_LIQUIDO")]
        public float TotalLiquido { get; set; }
        [Column("MIN_TOTAL")]
        public float MinTotal { get; set; }
        [Column("USUARIO")]
        public string Usuario { get; set; }
        [Column("CUSTODIARIO")]
        public decimal CustoDiario { get; set; }
        [Column("MAX_COMI")]
        public decimal MaxComi { get; set; }
        [Column("VALOR_COMI")]
        public decimal ValorComi { get; set; }
        [Column("NOVA_COMI")]
        public decimal NovaComi { get; set; }
        [Column("MENSSAGEM")]
        public string Mensagem { get; set; }
        [Column("Menssagem_RET")]
        public string MensagemRet { get; set; }
        [Column("DataRetorno")]
        public decimal DataRetorno { get; set; }
        [Column("HoraRetorno")]
        public decimal HoraRetorno { get; set; }
        [Column("TempoProcesso")]
        public decimal TempoPrecesso { get; set; }
        [Column("Tipo")]
        public int Tipo { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Perc_Juros_Total")]
        public decimal PercJurosTotal { get; set; }
        [Column("FLAG_CULTURAVENCIDA")]
        public byte FlagCulturaVencida { get; set; }
        [Column("CULTURA")]
        public string Cultura { get; set; }
        [Column("CULTURA_VCTO")]
        public int CulturaVcto { get; set; }
        [Column("FLAG_PRORROGADO")]
        public byte FlagProrrogado { get; set; }
        [Column("VALOR_PRORROGADO")]
        public decimal ValorProrrogado { get; set; }
        [Column("DIAS_ATRASO")]
        public int DiasAtrazo { get; set; }
        [Column("ID_VENDEDOR2")]
        public int IdVendedor2 { get; set; }
        [Column("VENDEDOR2")]
        public string Vendedor2 { get; set; }
        [Column("COMISSAO_VEND2")]
        public decimal ComissaoVend2 { get; set; }
        [Column("FLAG_COTACAO")]
        public byte FlagCotacao { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda1 { get; set; }
        [Column("Flag_Receber_Atrasado")]
        public byte FlagReceberAtrazado { get; set; }
        [Column("Autorizou_Receber_Atrasado")]
        public string AutorizouReceberAtrazado { get; set; }

EDIT2:
Alterei para essa forma e funcionou
public IEnumerable<object> getAutoriza()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs, lib => lib.IdOrcamento, itens => itens.IdOrcamento, (lib, itens) => new { lib, itens })
                .Where(a => a.lib.IdOrcamento == a.itens.IdOrcamento)
                .Select(libera => new
                {
                    libera.lib.TipoVenda,
                    libera.lib.Vencimento,
                    libera.lib.Juros,
                    libera.lib.Entrada,
                    libera.lib.Acrescimo,
                    libera.lib.Desconto,
                    libera.lib.Mensagem,
                    libera.lib.DataLib,
                    libera.lib.Vendedor,
                    libera.lib.Cliente,
                    libera.lib.Filial,
                    libera.itens.Produto,
                    libera.itens.Qtde,
                    libera.itens.Unitario,
                    libera.itens.Custo,
                    libera.itens.CustoDiario,
                    libera.itens.UltCondicao,
                    libera.itens.Total
                }).ToList();

            return lista;
        }

A: Altere o Select para
.Select(lib => new Liberacao
{
    TipoVenda = lib.t1.TipoVenda,
    // e assim por diante
}

Obviamente isso só vai funcionar se você realmente for devolver uma lista de Liberacao.


text:
Q: element.width is returing undefined I keep trying to log element.width and it returns undefined

I want to get the attribute not clientWidth or offsetWidth or anything else.

A: For get the element width attribute, you could use the method getAttribute("width"), you can read about it on: getAttribute(). Or alternatively access the propery attributes.width.value (read Element.attributes). Example:

console.log(document.getElementById('element').getAttribute("width"))
console.log(document.getElementById('element').attributes.width.value)


text:
Q: How to create a button for downloading pdf file that is Present in solution explorer? I am trying to create a button in my view page of my ASP.NET CORE.
When user clicks that button a pdf file that is present in the solution(sln)
should download to the user.
 I tried a href="location" inside button

 download

Its not working.
Is there any other way?
Please help me with that.
Thanks in advance.

A: Check HTML5 download attribute
Just be sure to check the browser support.

A: Where is the pdf located in your file structure?
Any static files (such as this pdf document) must be located in the wwwroot folder of your dotnet core project.
Additionally, serving of static files must be enabled in your Startup.cs file's Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}


text:
Q: Does the ContentResolver notify all path variants? My content uri has a path depending on the content, e.g. content://controller/ContentItem/0/Favorites/RecentlyPlayed
I observed that when I insert something with this uri all other uris with a shorter path also be notified.
Example
I insert something at:
content://controller/ContentItem/0/Favorites/RecentlyPlayed

also notified:
content://controller/ContentItem/0/Favorites
content://controller/ContentItem/0
content://controller/ContentItem

Is this the usual behavior?
Ralph

A: Yes if you passed true for notifyForDescendents when registering that observer


text:
Q: Minimum requirements (especially screen size) for QGIs - Android I would like to try Qgis on Android devices, but before, I would like to know the minimum terminals requirements, and especially the screen size or resolution, what is the minimum screen size do you recommends? At least to don't have any trouble to use it (I tried it on my smartphone... but some menu where larger than the screen size, so I had to stop my smartphone)!
At the same time, if some people have already used it, do not hesitate to give more requirement (memory, cpu, etc.).
Thanks

A: have a look at http://hub.qgis.org/wiki/20/Tested_Devices
Basically, I suggest to get at least 7-8" that will allow 1280 x 800. The reference device is A Galaxy note 3 (because I own one)

A: On the link provided the Samsung Galaxy Note 8 is listed.
I attempted since October to install the nightly build and failed.  There were several methods I tried I installed Ministro, Ministro II, did it as root etc.
Then I just stumbled across a comment that the "external" sd card needed to be dismounted.
Dismounted my 64GB SD card and it worked.
The screen size (8") is just a tad to small, the status bar is cut approximately in half height wise.  Thus when it is supposed to be showing a scale of 8364 the map canvas covers just above where the middle horizontal stroke is in the "3".


text:
Q: Reach the value of CheckBoxes in a loop (VBA) I've seen other questions about this, but still can't make it work.
I've got six CheckBoxes and I can reach the value of them doing this...
Worksheets("MyWorksheet").CheckBox1.Value
But in my loop, I need to do something like this...
Worksheets("MyWorksheet").CheckBox(i).Value
or...
Dim Src1 = Worksheets("MyWorksheet").CheckBox1.Value
Dim i
i = 1
MsgBox Src & i

I know how to do this in JS, but I'm quite new to VBA and this format.
The CheckBoxes are put directly on the Worksheet and they're ActiveX.

A: This might do what you want:
Sub test()
    Dim shp
    For Each shp In Worksheets("MyWorksheet").Shapes
        If Left(shp.Name, 9) = "Check Box" Then
            MsgBox shp.Name & " is " & (shp.DrawingObject.Value = 1)
        End If
    Next
End Sub


text:
Q: Which google api should I use?(maps) I am making website that lists places on google maps(added by users) which api shuld I use to achieve it?
Is there anything for that or should I just load locations from my database and mark them on map on every reload?

A: Yes you will need a database to store the coordinates of locations added by your users and fetch and display them as per need on the map. The Google Maps Apiv3 is suitable for this.
To reduce burden from fetching the coordinates from the database every time on reload, you can use the concept of Caching which would fairly help to improve the overall performance.

A: For mapping you should use the Google Maps API v3, see the Articles section of the documentation for ideas on interfacing with a database.


text:
Q: can't get custom Dimension Value Google Analytics Android I'm using this code for setting custom dimension
tracker.send(new HitBuilders.ScreenViewBuilder()
  .set("&cd", "Home Screen")
  .build()
);

also tried this :
 mTracker.send(new HitBuilders.ScreenViewBuilder()
                        .set("&cd1", "premiumUser")
                        .build()
        );

and for getting value :
 mTracker.get("&cd1");

but nothing work ,I have no idea how to get the current set value for this dimension.
I used alot of resources but nothing works. Also I followed all steps for setting custom dimensions in my Account.
Any ideas?

A: Your code sets the custom dimension to a single hit and then reads from the tracker object. That's the reason reads don't work.
Assuming you want to add the "premiumUser" custom dimension to all subsequent hits, and its dimension index is 1, your code should be as follows:
mTracker.set("&cd1", "premiumUser");

Then you should be able to read it from tracker object:
mTracker.get("&cd1");

You can find documentation for Tracker here.
As a side comment, if you need to set a custom dimension for a single hit, there is a different method in HitBuilder which is recommended for this purpose:
mTracker.send(new HitBuilders.ScreenViewBuilder()
                    .setCustomDimension(1, "premiumUser")
                    .build()
    );


text:
Q: Interface builder is not opening in Xcode 9 I updated xcode version 9 on last friday. Everything is working fine, but when i am clicking on main.storyboard, it takes lot of time but still not opened. When i check my Activity monitor, the interface builder takes 11.39GB?
What should i do? I am unable to design my new screens.

Thanks in advance.

A: *

*Close Xcode

*Open Terminal and enter this command
rm -rf ~/Library/Developer/Xcode/DerivedData
This is worked for me.


text:
Q: Why is the general solution to a linear differential equation sought in the form of $Ce^{kx}$? Why is the solution to linear differential equations with constant coefficients sought in the form of $Ce^{kx}$ ?

A: I'm making a long reply to one of joo's comments:
Well, a linear differential equation with constant coefficients has the form $y' = Ay$ for some matrix $A$. Now the general solution with the initial value $y(0) = v$ is $y(t) = \exp(tA)v$, where $\exp(X) = \sum_{k=0}^\infty \frac 1{k!} X^k$ for all square matrices $X$ (it can be proved that this series is always convergent, just like the ordinary exponential series). This follows from the formula
$$
\tfrac d{dt}\exp(tA) = A\exp(tA),
$$
which is not at all trivial, but which is proved in much literature on the subject.
In the case where $A$ is diagonalizable, there exists a basis $v_1,\ldots,v_n$ for $\Bbb R^n$ of eigenvectors for $A$. Putting $V = (v_1,\ldots,v_n)$ in column form, $D:= V A V^{-1} = \begin{pmatrix}\lambda_1 & &0\\ & \ddots\\ 0& & \lambda_n\end{pmatrix}$ is a diagonal matrix, where $\lambda_i$ is the eigenvalue corresponding to $v_i$ (Exercise!). Now
$$
\exp(D)=\exp(V^{-1} A V) = \sum_{k=0}^\infty (V^{-1} A V)^k = \sum_{k=0}^\infty \underbrace{(V^{-1}AV)(V^{-1}AV)\cdots (V^{-1} A V)}_{\text{$k$ times}} = V^{-1}\big(\sum_{k=0}^\infty A^k\big)V = V^{-1}\exp(A)V.
$$
Similarly, $\exp(tD)=\exp(t V^{-1}AV)=V^{-1}\exp(tA)V$ for all $t\in\Bbb R$. Hence if $y$ is the solution from before, we have
$$
y = \exp(tA)v=V\exp(tD)V^{-1}v = V\begin{pmatrix}e^{\lambda_1 t} & & 0\\&\ddots&\\0&&e^{\lambda_n t}\end{pmatrix}V^{-1} v = \big(\sum_{i=1}^n e^{\lambda_i t}v_i\big) V^{-1} v,
$$
where the above expression for $\exp(tD)$ follows from the fact that $D^k = \begin{pmatrix}\lambda_1^k & &0\\ & \ddots\\ 0& & \lambda_n^k\end{pmatrix}$ for all $k\in\Bbb N$; hence $\exp(tD)$ is calculated entry-wise. Now the expression on the right is a linear combination of functions of the form $t\mapsto e^{\lambda_i t} v_i$, which was what you wanted to know.

A: Short answer: because it works, i.e., solutions of this form do exist (if we allow complex $k$). (Though they do not always form a basis of solutions, which is why we sometimes have to consider $x^j e^{kx}$ as well).
Perhaps you wanted to know how people came up with the idea of using exponential functions for this purpose. But what is the fundamental idea of exponential growth? It's a function whose rate of change is proportional to the value of the function. In symbols this becomes $y'=ky$, which is a differential equation with constant coefficients.  We can even define exponential functions as solutions of this equation (which is sometimes done). Whether or not this is done, the relation between $e^{kx}$ and $y'=ky$ is the major reason why we care about exponential functions at all. (We could just stick to rational exponents $x^{p/q}$ for all algebra purposes, why have real exponents?)
After seeing the relation of $\exp(kx)$ to first-order equations, it's relatively easy to see that it is related to higher-order equations too: taking a derivative several times just brings out the factor of $k$ several times.


text:
Q: How to call the angular4 function from the SSRS(Microsoft) Report? enter code herePlease help.
I want to pass the id parameter from ssrs report to angular4 function, below is the SSRS Code.
I used the HostListener but its not working, not able to call the function of Angular.
getting  the below error when i click in the Id parameter of the SSRS report.
The frame attempting navigation must be same-origin with the target if navigating to a javascript: url
SSRS Code :- HTMl Console View

21866

Angular Function
fetchProviderId(value) {
alert(value)
}

A: It's not like I'm SRSS expert. I can provide you a generic method to communicate between the Angular and external app. You need to use some intermediate object which is accessible by both ANgular and SRSS. If you run this app in the browser, you can use window object. So, the Angular component or service will contain code like this:
window.fetchProviderId = this.fetchProviderId;

this way fetchProviderId will be accessible globally and the href handler would work.


text:
Q: Is there any way to navigate inside frames on a webpage using Nightmare JS? I am having trouble using Nightmare js to access elements within a specific frame on a webpage that gets its elements from a different html file. These are frames, not iframes, so plugins such as iframe-manager do not work.
I also cannot go to the src page of the frame as what I am attempting to do opens another window when clicked on the frames html.
On the original webpage clicking the button on the frame reveals information within another frame on the webpage. It would be easier (and potentially possible, unlike other options) to navigate within frames on the original webpage.
Any guidance would be appreciated thanks.

A: Decided to cut my losses and switch to puppeteerJS
Unlike Nightmare, it supports switching to normal frames via their contentFrame() method and $
No shade on Nightmare though, its a good API, just lost support for this frankly archaic web design choice


text: Q: Matrix with a certain property related to rank Say I have a matrix $A \in \mathbb{R}^{n \times m}$ that has a rank of $r$ and a property of any $r$ columns of $A$ are linearly independent. Does this kind of matrix have a special name? Do they have other intriguing properties?


text:
Q: Maya Python & Pyside: pass value returned from a method with multiple args into another method I'm beginning some Python UI with Pyside in Maya 2016.
I am trying to make a function in my UI class that gets all the values of a few widgets.
Here's the function snippets from my class that are involved:
class UI_Window_to_Rename(uiWindow_form, uiWindow_base):

    def __init__(self, parent=getMayaWindow()):

        self.create_connections()

    def create_connections(self):

        self.maxDist_spinBox.valueChanged.connect(self.get_vert_distance)
        self.setVerts_btn.clicked.connect(self.get_all_settings)

    def get_vert_distance(self, value):

        return str(value)

    def get_all_settings(self):
    # This doesn't work. How to I pass the argument from
    #  get_vert_distance into this function?
# TypeError: get_vert_distance() takes exactly 2 arguments (1 given)

        vert_dist = self.get_vert_distance(value)

I basically want get_all_settings to manipulate the values of other functions I pass in. But I'm not sure how to do that since get_vert_distance uses 2 arguments.
Kind of similar to this question, but I think this is more complex?
Calling a variable from one function to another function in Python

A: I was going about this wrong. I should have just made a function to query the current value of the maxDist_spinBox widget with:
def get_all_settings(self):
    print self.maxDist_spinBox.value()

https://srinikom.github.io/pyside-docs/PySide/QtGui/QSpinBox.html?highlight=spinbox#PySide.QtGui.PySide.QtGui.QSpinBox.value


text:
Q: What is the difference between window.onload() and document.addEventListener('load', ..)? It seems to me that both events are fired when every resource and its dependent resources have finished loading. This rises some questions:

*

*Is there any difference between those events?

*Which event gets fired first?

*Which event could or should be preferred for adding an additional HTML element to the body after everything has been finished loading?

A: They do NOT do exactly the same thing, at least in Firefox.
The reason is that window.onload is equivalent to window.addEventListener("load"), not document.addEventListener("load").
Although, all documentation I have seen says that they are equivalent.

A: *

*As you say, they both do exactly the same thing. The advantage of addEventListener is that you can add more than one event listener to the load event.

*From some basic testing, it seems the listeners get called in the order they were set, though I don't know how reliable that is.

*You can use either method to do whatever you need.

A: 1- From what I know adding an event listening gives you more freedom especially in removing the controls you added
2- Nothing I know about that. But I assume it shouldn't be a big difference
3- The EventListener allows you to control the element and remove the control at will and thus should be more useful


text:
Q: Swipe gesture is not being called on a subview inside a present view controller I presented a view controller and I have a subview in it. I added a swipe gesture on the subview. The swipe gesture is not being called. Instead, the presented view controller is trying to dismiss itself i.e. going down. How do I override the swipe gesture to be recognised by the subview instead of the super view.
When I implemented swipe on a static view controller, it works as expected.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var viewSwipe: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipeUp(_:)))
        swipeUp.direction = UISwipeGestureRecognizer.Direction.up
        self.viewSwipe.addGestureRecognizer(swipeUp)

        let swipedown = UISwipeGestureRecognizer(target: self, action: #selector(swipeDown(_:)))
        swipedown.direction = UISwipeGestureRecognizer.Direction.down
        self.viewSwipe.addGestureRecognizer(swipedown)
    }

    @objc func swipeUp(_ gesture: UISwipeGestureRecognizer) {
        print("swiped up")
    }

    @objc func swipeDown(_ gesture: UISwipeGestureRecognizer) {
        print("swiped down")
    }
}

The red area needs to get swipe

A: Add Gesture only in view and you can also add any direction on gesture. Here i put Small example, you can refer this code for your problem.
Get 1 for Right Direction and 2 For Left Direction
Example :
import UIKit

class ViewController: UIViewController,UIGestureRecognizerDelegate{

 @IBOutlet weak var viewGray: UIView!
 @IBOutlet weak var viewRed: UIView!

 override func viewDidLoad() {
     super.viewDidLoad()

   self.navigationController?.interactivePopGestureRecognizer?.delegate = self

   let directions: [UISwipeGestureRecognizer.Direction] = [.right, .left]
     for direction in directions {
        let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
        gesture.direction = direction
        gesture.delegate = self
        self.viewRed.addGestureRecognizer(gesture)
     }
  }

  @objc func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
  }

   func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
       return true
   }

  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      return true
  }
}

A: Your code should work. If not there, is probably conflict with different gesture recognizer. To solve this conflict, you can set delegate on your swipeUp and swipeDown recognizers:
class ViewController: UIViewController, UIGestureRecognizerDelegate

swipeUp.delegate = self
swipeDown.delegate = self

and try to investigate what is happening in this delegate funcs (with breakpoints or with print, it is up to you):
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return false
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

If none of this delegate funcs is called, when you are trying to swipe. Then there is probably different (ie invisible) view over you content.

A: you code will work. Just try to present your view controller as a full screen in case iOS 13. Refer following code.
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)


text:
Q: creating iso with installed linux where home data also should be part of iso I am looking out for a tool which will help to create an iso from installed linux virtual machine where it will also include home folder and can help to create bootable iso.
I have searched on web a lot and many tools do not support like customizer, systembackup, respin, clonezilla etc. I have installed pinguybuilder but with several options though it created iso but it after installation of iso it could not install bootloader.
Is there any tool available on Ubuntu 18.4/20.4/22.4 to create bootable iso of installed linux.


text:
Q: CSRF Guard - how to validate generated token at server side I'm very new to web security and I'm trying to implement CSRF Gaurd on my web application.
I have done all the required configuration on my web application and I can see that token (FWJY-N767-M4HG-DHXT-WCE4-5J08-MV4G-LNV4) is getting generated/injected when I do a ajax call or when a html page loads. I have notice that token is same on every request.
However, I'm not able to validate token at server side. According to my research it should go to CsrfGuardFilter.java class and validate the token but when I'm debugging I can see that it is not going to CsrfGuardFilter.java class and it not validating the request based on token. I'm getting the response for the requests which doesn't contain token also.
Can someone guide me to implement CSRF Guard properly on my web application. Thanks for your help.

A: In my web application I'm using GWT to generate front-end JavaScript after doing bit of research on various forum I have figured out that because of GWT generated JavaScript code token was not getting injected into any ajax call. So to implement CSRF guard over GWT code I need to inject the csrf guard script before the *.nocache.js script.
Helpful link

A: you have to declare CsrfGuardFilter, CsrfGuardServletContextListener and CsrfGuardHttpSessionListener in your web.xml in the correct location. In my application, I placed it after the session was created. Also, you have to define mapping for JavaScriptServlet.
NOTE : I used owasp csrfguard 3.1.0 in my application and I only had to define mappings for the above mentioned components. For older versions, you might have to define more properties/components.
I took help from the following example for my implementation :
https://github.com/aramrami/OWASP-CSRFGuard
I hope you got your issue resolved and my answer will help someone in future.


text:
Q: Import multiple csv in a DataFrame with different headers in Spark i have multiple Csv which everyone r a variable like this:
cloudiness.csv
    +---+---+----------+-------------------+
    |_c0| ID|cloudiness|           datetime|
    +---+---+----------+-------------------+
    |  0|  3|       1.0|2013-11-08 00:00:00|
    |  1|303|       2.0|2013-11-08 00:00:00|
    |  2|306|       3.0|2013-11-08 00:00:00|

temperature.csv
    +---+---+-----------+-------------------+
    |_c0| ID|temperature|           datetime|
    +---+---+-----------+-------------------+
    |  0|  3|        3.0|2013-11-08 00:00:00|
    |  1|303|        4.0|2013-11-08 00:00:00|
    |  2|306|        5.0|2013-11-08 00:00:00|

..and so on, (7 o 8 o this files).
I have to merge them in one only DataFrame using Spark (R, Python or Scala) like this:
    +---+---+-----------+----------+-------------------+
    |_c0| ID|temperature|cloudiness|           datetime|
    +---+---+-----------+----------+-------------------+
    |  0|  3|        3.0|       1.0|2013-11-08 00:00:00|
    |  1|303|        4.0|       2.0|2013-11-08 00:00:00|
    |  2|306|        5.0|       3.0|2013-11-08 00:00:00|

I tried spark.read but it takes too much time, files are 3 GB each one. What is the best method to do it?

A: The standard way is to join data frames.
when you read csv files using below snippet
val read_csv1 = sc.textFile("HDFS Path to read the file")
RDD will be created and you can join with other CSV's. If you mention performance issue means. let me give you another way.


text:
Q: Websocket with NestJs and Angular I'm trying to implement a websocket between my NestJs server and my angular app.
I red the official NestJs documentation here : https://docs.nestjs.com/websockets/gateways
I can open the communicaiton between the two entities but I'm not able to send event ..
Server Gateway
@WebSocketGateway()
export class SsgGateway implements OnGatewayInit, OnGatewayConnection {

    private logger: Logger = new Logger('SsgGateway');

    @WebSocketServer() wss: Server

    afterInit(server: any) {
        this.logger.log('Websocket gateway initialized')
    }

    handleConnection(client: any, ...args: any[]) {
        this.logger.log("Client connected")
    }

    @SubscribeMessage('msgToServer')
    handleMessage(client: Socket, payload: string): WsResponse<string> {
        this.wss.emit('msgToClient', payload)
    }
}

*

*I naturaly imported my SsgGateway into the app.module and enableCors

*afterInit is triggered during the server start (npm run:start)

*handleConnection is getting the client connexion when it starts ("Client connected")

Now, my client is not able to send any message through my socket. I tried with two different packages but unfortunately it is not working ..
The package installed are :

*

*socket.io-client

*ngx-socket-io

Here's the solution implemented client-side with socket.io-client :
Service
export class WebsocketService {

  constructor() {
    this.socket = io('ws://localhost:3000')
  }

  socket: any;

  listen(eventName: string) {
    return new Observable((subscriber) => {
      this.socket.on(eventName, (data) => {
        subscriber.next(data);
      })
    });
  }

  emit(eventName: string, data: any) {
    this.socket.emit(eventName, data);
  }

}

Component
export class AppComponent {
  title = 'websocket';

  constructor(private ws: WebsocketService) { }

  ngOnInit() {
    // Listen to websocket event
    this.ws.listen('msgToClient').subscribe((data) => {
      console.log(data);
    })
  }

  send() {
    this.ws.emit('msgToServer', "test");
  }

}

I bind an htlm button that trigger the "send" event but I never get any data from my websocket.
Now, this is the solution tried with the package ngx-socket-io :
Module
const config: SocketIoConfig = { url: 'http://localhost:3000', options: {  } };

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config)
  ],
  providers: [AppService, WebsocketService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Service
  constructor(private socket: Socket) { }

  sendMessage(msg: string) {
    this.socket.emit('msgToServer', msg);
  }

  getMessage() {
    return this.socket.fromEvent('msgToClient').pipe(map((data: {}) => data));
  }

Component
  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.getMessage().subscribe((data) => {
      console.log(data);
     })
  }

  send() {
    this.appService.sendMessage("test")
  }

I'm not even talking about the use of namespace which seems rather complicated to use.
A working example of Websocket with Angular and NestJs would be wonderful!
Thank you very much guys !


text:
Q: how to place Post and page content side by side Dear Stack Exchange Wordpress community,
I am interested in having two loops on the same page, having the larger one display the Page content and a sidebar display blog posts,and do not know how to go about it. I have searched the archives to still no avail.
Much Appreciation.
Bill

A: I am suggesting you to use two for loop using two post types.
 For blog post use below code
<?php query_posts( array(
 'post_type' => array( 'post')
 'showposts' => 5 )
 ); ?>
    <?php while ( have_posts() ) : the_post(); ?>

       <a href="<?php the_permalink(); ?> "><?php the_title(); ?>

    <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>

For page post use below code
<?php query_posts( array(
 'post_type' => array( 'page')
 'showposts' => 5 )
 ); ?>
    <?php while ( have_posts() ) : the_post(); ?>

       <a href="<?php the_permalink(); ?> "><?php the_title(); ?>

    <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>


text:
Q: Interchanging two integrals with different measures. If $\alpha:\mathbb{R} \rightarrow \mathbb{R}$ is a bounded, increasing, right continuous function, and we let $d\alpha$ denote the unique Lebesgue-Stieltjes measure induced by $\alpha$, then I'm trying to show that for any $c \in [0,\infty)$ that
$$\int_{\mathbb{R}}\alpha(x+c)-\alpha(x)dx = c \int_{\mathbb{R}}d\alpha$$
where $dx$ is the Lebesgue integral.
Now just playing around with things and not worrying too much about details, I discovered that
$$\int_{\mathbb{R}}\alpha(x+c)-\alpha(x)dx = \int_{\mathbb{R}}\left(\int_{x}^{x+c}d\alpha\right)dx \stackrel{?}{=} \int_{x}^{x+c}\left(\int_{\mathbb{R}}d\alpha \right)dx = c\int_{\mathbb{R}}d\alpha. $$
My question, is the interchanging of the two integrals (done at the step marked with $\stackrel{?}{=}$) justified? Does Fubini's theorem apply here?

A: Here is a direct approach using the monotone convergence theorem.
Note that $\alpha$ has limits at $\pm \infty$ (denote by $\alpha(\pm \infty)$ respectively) and we have $\int d \alpha = \alpha(\infty) - \alpha(-\infty)$.
Since $x \mapsto \alpha(x+c) -\alpha(x)$ is non negative it has an integral (possibly infinite).
Let $I_k = \int_{kc}^{(k+1)c} \alpha(x) dx$, then
$\int_{kc}^{(k+1)c} (\alpha(x+c)-\alpha(x)) dx = I_{k+1}-I_k \ge 0$ and
$\int (\alpha(x+c)-\alpha(x)) dx = \sum_k (I_{k+1}-I_k) $.
We see that $\lim_{k \to \infty}I_k = c \alpha(\infty)$,
$\lim_{k \to -\infty}I_k = c \alpha(-\infty)$ and so
$\sum_k (I_{k+1}-I_k) = \lim_{N \to \infty} (I_{N}-I_{-N}) = c (\alpha(\infty)- \alpha(-\infty)) = c \int \alpha$.

A: $\displaystyle\int_{\mathbb{R}}\alpha(x+c)-\alpha(x)dx=\int_{\mathbb{R}}\left(\int_{x}^{x+c}d\alpha\right)dx=\int_{\mathbb{R}}\left(\int_{\mathbb R}\chi_{[x,x+c]}(y) d\alpha(y)\right)dx$
and Tonelli's Theorem implies that
$\displaystyle \int_{\mathbb{R}}\left(\int_{\mathbb R}\chi_{[x,x+c]}(y) d\alpha(y)\right)dx=\int_{\mathbb{R}}\left(\int_{\mathbb R}\chi_{[x,x+c]}(y)dx \right)d\alpha(y)=\int_{\mathbb R}cd\alpha(y)=c\int_{\mathbb R}d\alpha(y)$


text:
Q: adjacency list from JSON data I try to programmaticly generate a new object as a adjacency list from the following provided sampleData to be used in jointJS, so it generates a organization chart in the end:
sampleData = [
    {"id":"1224286", "label":"someLabel1", "image":"male.png", "level":"1"},
    {"id":"1166041", "label":"someLabel2", "image":"male.png","refparent":"1224286", "level":"2"},
    {"id":"1224376", "label":"someLabel3", "image":"male.png","refparent":"1224286", "level":"2"},
    {"id":"1317500", "label":"someLabel4", "image":"male.png", "refparent":"1224286", "level":"2"},
    {"id":"1232930", "label":"someLabel5", "image":"male.png", "refparent":"1166041", "level":"3"},
    {"id":"1163148", "label":"someLabel6", "image":"male.png", "refparent":"1317500", "level":"3"},
    {"id":"1279087", "label":"someLabel7", "image":"male.png", "refparent":"1166041", "level":"3"},
    {"id":"1185740", "label":"someLabel8", "image":"male.png","refparent":"1224376", "level":"3"},
    {"id":"1234273", "label":"someLabel9", "image":"male.png", "refparent":"1232930", "level":"4"},
    {"id":"1210593", "label":"someLabel10", "image":"male.png", "refparent":"1185740", "level":"4"},
    {"id":"1279247", "label":"someLabel11", "image":"male.png", "refparent":"1185740", "level":"4"},
    {"id":"1316785", "label":"someLabel12", "image":"male.png", "refparent":"1232930", "level":"4"},
    {"id":"1266325", "label":"someLabel13", "image":"male.png", "refparent":"1210593", "level":"5"}
];

The sampleData should be converted as in the following structure to use it as an adjacency list :
var list = {
    '1224286': ['1166041', '1224376', '1317500'],
    '1166041': ['1232930', '1279087'],
    '1224376': ['1185740'],
    '1317500': ['1163148'],
    '1232930': ['1234273', '1316785'],
    '1163148': [],
    '1279087': [],
    '1185740': ['1210593', '1279247'],
    '1234273': [],
    '1210593': ['1266325'],
    '1279247': [],
    '1316785': [],
    '1266325': []
};

It is looking so simple but i just can't see it.

A: try this code (has n*n complexity)
var output = {};
sampleData.forEach(function(val){
  var id = val.id;
  var arr = [];
  sampleData.forEach(function(innerVal){
    if ( innerVal.refparent == id )
    {
       arr.push(innerVal.id);
    }
  });
  output[id] = arr;
});
console.log(output);

Or else you can transform the data-structure to get better performance
var transformed = {};
sampleData.forEach(function(val){
  var ref = val.refparent;
  transformed[ref] = transformed[ref] || [];
  transformed[ref].push(val.id);
});

//now iterate the original list to see what is missed out
var output = {};
sampleData.forEach(function(val){
  output[val.id] = transformed[val.id] || [];
});

This gives you 2n complexity.
DEMO

var sampleData = [
    {"id":"1224286", "label":"someLabel1", "image":"male.png", "level":"1"},
    {"id":"1166041", "label":"someLabel2", "image":"male.png","refparent":"1224286", "level":"2"},
    {"id":"1224376", "label":"someLabel3", "image":"male.png","refparent":"1224286", "level":"2"},
    {"id":"1317500", "label":"someLabel4", "image":"male.png", "refparent":"1224286", "level":"2"},
    {"id":"1232930", "label":"someLabel5", "image":"male.png", "refparent":"1166041", "level":"3"},
    {"id":"1163148", "label":"someLabel6", "image":"male.png", "refparent":"1317500", "level":"3"},
    {"id":"1279087", "label":"someLabel7", "image":"male.png", "refparent":"1166041", "level":"3"},
    {"id":"1185740", "label":"someLabel8", "image":"male.png","refparent":"1224376", "level":"3"},
    {"id":"1234273", "label":"someLabel9", "image":"male.png", "refparent":"1232930", "level":"4"},
    {"id":"1210593", "label":"someLabel10", "image":"male.png", "refparent":"1185740", "level":"4"},
    {"id":"1279247", "label":"someLabel11", "image":"male.png", "refparent":"1185740", "level":"4"},
    {"id":"1316785", "label":"someLabel12", "image":"male.png", "refparent":"1232930", "level":"4"},
    {"id":"1266325", "label":"someLabel13", "image":"male.png", "refparent":"1210593", "level":"5"}
];

var transformed = {};
sampleData.forEach(function(val){
  var ref = val.refparent;
  transformed[ref] = transformed[ref] || [];
  transformed[ref].push(val.id);
});

var output = {};
sampleData.forEach(function(val){
  output[val.id] = transformed[val.id] || [];
});

document.body.innerHTML += JSON.stringify(output,0,4);


text:
Q: When and how to use Html5DateRenderingMode I understand that Html5DateRenderingMode is used for displaying date/time related values and can be set as -
@{ Html.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339; }
@{ Html.Html5DateRenderingMode = Html5DateRenderingMode.CurrentCulture; }

Which I have tried declaring in View(.cshtml). When used with EditorFor as -
@Html.EditorFor(emp => emp.StartDate, new { htmlAttributes = new { @class = "form-control" } })

It displays date according to the declared RenderingMode.
Questions -
- Do we always set the date rendering mode in View(.cshtml) or can we declare it in ViewModel as well. If yes, how?
- What could be the practical usage of setting Html5DateRenderingMode?
(Thinking if same can be achieved using ApplyFormatInEditMode and DataFormatString annotations)
Thank you!

A: Documentation on this particular property is annoyingly sparse. Just about the best description of its purpose is found in the source:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Web.Mvc
{
    /// <summary>
    /// Controls the value-rendering method For HTML5 input elements of types such as date, time, datetime and datetime-local.
    /// </summary>
    public enum Html5DateRenderingMode
    {
        /// <summary>
        /// Render date and time values according to the current culture's ToString behavior.
        /// </summary>
        CurrentCulture = 0,

        /// <summary>
        /// Render date and time values as Rfc3339 compliant strings to support HTML5 date and time types of input elements.
        /// </summary>
        Rfc3339,
    }
}

When dealing with the date/time related HTML5 input types, the value of the input must be set to ISO, or "Rfc339" format, or the built-in browser controls won't be able to interpret the date/time properly. This only applies when using a modern browser that supports these types and presents a calendar/time control to allow you pick or otherwise enter the datetime info in a structured way.
Rather than two separate choices, this enum is really just an on/off switch, and most likely exists to permit a bit of flexibility depending on your target audience. If you actually want just a standard text input or you're focused only on desktop, where browser support is sadly still pitiful to this day, then you may want the input value to be more "friendly" to the user by being their current culture, i.e. 08/12/2015 vs 2015-08-12. However, if you want to rely on what browser controls exist, if any, using polyfills where necessary, or are focused on mobile, where support is universal, then you want the values output in proper ISO format.
Honestly, though, I've never fooled with this setting before and have never really had a need to.
As far as the DataFormatString attribute and its ApplyFormatInEditMode parameter goes, yes, you can pretty much achieve the same thing using that. It's a little more loose in that you can use any format, but if you apply ISO format in edit mode, then you're doing the same as this setting would when set to Html5DateRenderingMode.Rfc3339.


text:
Q: I can not save listview items to a database I have listview with four columns. I have created table in the database with four columns. But i can not save these items with this code. please help me.
foreach (ListViewItem l in listView1.Items)
        {
            cn = new SqlConnection(@"Data Source=DESKTOP-1F1TUP2\SQLEXPRESS;Initial Catalog=savedata;Integrated Security=True");
            cn.Open();
            cmd = new SqlCommand("Insert Into listview(item,quantity,unit_price,sub_total) VALUES (@item,@quantity,@unit_price,@sub_total)", cn);
            cmd.Connection = cn;

            cmd.Parameters.AddWithValue("item", l.SubItems[0]);
            cmd.Parameters.AddWithValue("quantity", l.SubItems[1]);
            cmd.Parameters.AddWithValue("unit_price", l.SubItems[2]);
            cmd.Parameters.AddWithValue("sub_total", l.SubItems[3]);
            cmd.ExecuteNonQuery();

        }

A: the parameter needs to be added as "@item"
cmd.Parameters.AddWithValue("@item", l.SubItems[0]);

you can try this also
cmd.Parameters.Add(new SqlParameter("@item", l.SubItems[0]));


text:
Q: How do I plot my country map with weather data stations? I've tried this code, but I can't plot the coordinates in my country map.
Weather = {"Ulaanbaatar", "Erdenet"}

stationtocoordinate = Map[# -> WeatherData[#, "Coordinates"] &, Weather]

allWeatherStations = WeatherData[];
fullformStations = FullForm /@ allWeatherStations;
Tally[StringLength /@ fullformStations[[All, 1, 2]]] . This code not working. Why?

A: WeatherData can be told to give you all the weather stations it knows about, but there's more than one type of weather station (and duplicates!):
allWeatherStations = WeatherData[];
fullformStations = FullForm /@ allWeatherStations;
Tally[StringLength /@ fullformStations[[All, 1, 2]]]
(*{{4, 6919}, {5, 10306}, {8, 4697}}*)

Looking at the documentation, I find the "WMO*" stations seem to be the interesting, and reliable ones. I extract these and find their corrdinates:
wmoWeatherStations = Cases[fullformStations[[All, 1, 2]], a_ /; StringLength[a] == 8];
wmoStationsPositions =
  GeoPosition[WeatherData[#, "Coordinates"]] & /@ wmoWeatherStations;

Using GeoWithinQ I find those stations within Mongolia and then use Pick to include these in GeoGraphics
wmoMongolia = GeoWithinQ[Entity["Country", "Mongolia"], wmoStationsPositions];
GeoGraphics[GeoMarker[Pick[wmoStationsPositions, wmoMongolia]],
 GeoRange -> Entity["Country", "Mongolia"]]

A: There is an example of what I think you are trying to do at the end of WeatherData help page, but its a little hard to read.  However - here's what I think you want.
(* Function to  Get a list consisting of {CityName, Temp, Co-ords}
given a Countries weather station, note we get the 1st
nearest weather station to the city *)

weatherdata[cityname_] := {cityname, WeatherData[#, "Temperature"],
 WeatherData[#, "Coordinates"]} & /@ WeatherData[{cityname, 1}];

(* Get Names for all Cities *)

cities = CityData[#, "Name"] & /@ CityData[{All, "Mongolia"}];

(*  Get the weather and weather station co-ordinates for the list of
cities  (the Drop is a kludge to remove the incorrect city "Moron")
from the weather data *)

wdata = Drop[weatherdata[#] & /@ cities, 9];

(*  Plot the list of city weather stations on a map using GeoPosition to
correctly plot the co-ordinates*)

GeoGraphics[{Point[GeoPosition[wdata[[All, 1, 3]]]],
Polygon[Entity["Country", "Mongolia"]], GeoRange -> "Country"}]

I'll leave it as an exercise to change the points to something that changes depending on the temperature.  i.e. a disc that changes colour/radius.  There are some good examples in the GeoGraphics help.


text:
Q: How to trigger a function on parent div when iframe content is clicked? I'm trying to create a reusable function that works by hiding a specific div (outside the iframe) whenever a click is made anywhere inside an iframe.
To be more specific, this div I want to hide is a search menu that can be opened on top (z-index) of an iframe. I'd like to close this menu whenever I click outside it, which happens to be inside the full screen iframe.
I couldn't make it work using the solutions from this and other similar pages (Whenever I change the URL, it doesn't work anymore): Detect click event inside iframe
I managed to do something like this that works but the code is repetitive. I'd like a more general function that works whenever I click inside any iframe.

const iframeListener1 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('chrono-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

const iframeListener2 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('plus-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

const iframeListener3 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('google-docs-1-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

const iframeListener4 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('google-sheets-2-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

const iframeListener5 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('google-docs-3-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

const iframeListener6 = addEventListener('blur', function() {
  if (document.activeElement === document.getElementById('google-docs-4-loader')) {
    $('#outer-layer-card').stop().fadeOut('fast');
  }
  removeEventListener('blur', iframeListener);
});

How can I trigger a function (to hide one specific div) whenever I click on any iframe?
Thanks in advance for any suggestions or help

A: Can save event listeners into a object and have a function to add them dynamically. That would mean to have some sort of html element which would have data-target attribute or similar. Additionaly can move the id_target to function parameter.

var iframe_listeners = [];

function add_iframe_event(){
  const id_target = $('data-target element').data('target');

  iframe_listeners[id_target] = addEventListener('blur', function() {
    if (document.activeElement === document.getElementById(id_target)) {
      $('#outer-layer-card').stop().fadeOut('fast');
    }
    removeEventListener('blur', iframe_listeners[id_target]);
  });
}

Edit:
loop method
var iframe_listeners = [];
const ids = [ '1', '2' ];

for(const id of ids){
  // skip if element doesnt exist
  if($(`#${id}`).length == 0) continue;

  add_iframe_event(id);
}

function add_iframe_event(id_target){
  iframe_listeners[id_target] = addEventListener('blur', function() {
    if (document.activeElement === document.getElementById(id_target)) {
      $('#outer-layer-card').stop().fadeOut('fast');
    }
    removeEventListener('blur', iframe_listeners[id_target]);
  });
}


text:
Q: How do I automatically sync a file from a local Mac to Mac OS X Server? I have a Mac running Mac OS X Server and there are three other Macs connected to the local network.
All our data is stored on the server and the server backs up every day to an external hard drive using Time Machine.
I want to synchronize certain files from our three local machines to the server once a day.
Is there a simple way to do automate this process?

A: I would recommend using Automator and rsync to accomplish this:
First, you'll want to make sure that the share you want the three client machines to sync to is mounted on each client computer, so the following command knows where to go to put the data.

*

*Open Automator from /Applications

*Create a new iCal Alarm workflow

*Find the "Run Shell Script" Automator action

*type in the text box: "rsync -ax /path to file you want to sync from  /path to file you want to sync to" In the case of syncing from a Mac to a server on the network, the path will look like this: /Volumes/Share/Path

*Click the Run button in Automator to test this action (you may want to test the command out in Terminal with some dummy files first).

*If the workflow is working properly, you can save it. When you save and name it, it should open iCal on your client computer and place the new iCal Alarm you just created in the calendar. You can then change the date and time that this should run, as well as set it to repeat on certain days of the week.

*From here, you can either duplicate these steps on the other client machines or share the event via email.
Good luck.

A: ChronoSync, File Replication Pro, and Dropbox would all accomplish this. You could create a Dropbox account for the server and each user could share a folder with the server's Dropbox account.
Other approaches are to use CrashPlan to backup from the clients to the server, or backup the clients to the server with Time Machine.


text:
Q: How I make rss feed like blogger guys I am doing some stuff which is related to rssfeed. I built a page for rss feed all the things are going well but when I try to test the feed or use the feed I can't, Here is my code. Actually I am building rss feed for my blogger so I want to be it like that, any ways just tell me where am I wrong
        <?php
require_once('simple_html_dom.php');
$html = new simple_html_dom();
$xml=simplexml_load_file("ad.xml");
header('Content-Type: application/atom+xml');
$b="<?xml version='1.0' encoding='UTF-8'?>
<feed>";
    echo $b;
foreach($xml->url as $s){
    $s=$s->loc;
$html = file_get_html($s);
 $element= $html->find('div[class=post-content clear-block]');
// Find all links
$vez=$html->find('div[class=post-date]');
$p = '|]*href="http://onlinegamesocean.com[^"]*"[^>]*>.*|iU';
$h = $html->find('h1[class=title]');

if(empty($vez)){
    foreach($h as $ha){
echo "<entry><title type='text'>".htmlentities($ha->plaintext)."</title>";
}
foreach($element as $a) {
    if ($a === end($element))
echo "<content type='html'>".htmlentities(preg_replace($p, '', $a))."</content></entry>";
}
}
}
echo "</feed>";
?>

Output:

<?xml version='1.0' encoding='UTF-8'?>
<feed><entry><title type='text'>Offworld Trading Company Free Download</title><content type='html'>

ABOUT THE GAME

Mars has been colonized and has invited you to lend a hand to make sure the new colony has a shot at success. But you’re not the only one that’s been invited, other business rivals are here as well and they have no qualms about playing dirty to gain the choicest territories on the Martian surface and driving their competitors out of business.

Title: Offworld Trading Company
 Genre: Indie, Simulation, Strategy
 Developer: Mohawk Games
 Publisher: Stardock Entertainment
 Release Date: 28 Apr, 2016

Offworld.Trading.Company.DLC-BAT { Download | Download | Download | Download | Download | Download | Download | Download | Download }

DLC’s:
 • Offworld Trading Company – Real Mars Map Pack DLC
 • Offworld Trading Company – Almanac DLC

Note:
 • Game prompts an early access notice on first run, but it is out of EA state as also evident on the version number v1.0.12745
 • Also the DLC’s only became available after EA state changed

Offworld Trading Company Free Download
 Size: 656 MB
 ——————————-

ONE FTP LINK

DIRECT LINK

Offworld.Trading.Company-HI2U.iso

OPENLOAD

Offworld.Trading.Company-HI2U.iso

UP07

Offworld.Trading.Company-HI2U.iso

1FICHIER

Offworld.Trading.Company-HI2U.iso

UPTOBOX

Offworld.Trading.Company-HI2U.iso

HUGEFILES

Offworld.Trading.Company-HI2U.iso

MEDIAFREE

Offworld.Trading.Company-HI2U.iso

USERSCLOUD

Offworld.Trading.Company-HI2U.iso

JHEBERG

Offworld.Trading.Company-HI2U.iso

GO4UP

Offworld.Trading.Company-HI2U.iso

MULTI LINKS

Offworld.Trading.Company-HI2U.iso

TORRENT

Enjoy

MINIMUM:

OS: Windows 10 / 8.1 / 7 64-bit

Processor: 1.8 GHz Intel Core 2 Duo / 2.0 GHz AMD Athlon X2 64

Memory: 2 GB RAM

Graphics: Nvidia GeForce 8800 GT / ATI Radeon HD 3870 / Intel HD Graphics 4600

DirectX: Version 11

Network: Broadband Internet connection

Storage: 2 GB available space

Sound Card:

RECOMMENDED:

Processor: 3 GHz Intel Quad-Core Processor / 3.2 GHz AMD Six-Core Processor

Memory: 4 GB RAM

Graphics: Nvidia GeForce GTX 460 / AMD Radeon HD 7850

DirectX: Version 11

Network: Broadband Internet connection

Storage: 2 GB available space

Sound Card:

Offworld Trading Company Free Download
 &#8211; Extract
 &#8211; Burn or mount the .iso
 &#8211; Run setup.exe and install
 &#8211; Copy Crack
 &#8211; Play

You May Also Like:

</content></entry><entry><title type='text'>Left Alone Free Download</title><content type='html'>

ABOUT THE GAME

Left alone is a psychological horror game set in multiple believable interior and exterior environments. The game has a unique, high octane atmosphere which means you’ll feel like you’re truly beginning an adventure you’ll never quite forget.

Title: Left Alone
 Genre: Action, Adventure, Indie
 Developer: Volumetric Games
 Publisher: Volumetric Games
 Release Date: 28 Apr, 2016

Left Alone Free Download
 Size: 680 MB
 ——————————-

ONE FTP LINK

DIRECT LINK

Left.Alone-PLAZA.iso

OPENLOAD

Left.Alone-PLAZA.iso

UP07

Left.Alone-PLAZA.iso

1FICHIER

Left.Alone-PLAZA.iso

UPTOBOX

Left.Alone-PLAZA.iso

DOWNACE

Left.Alone-PLAZA.iso

HUGEFILES

Left.Alone-PLAZA.iso

MEDIAFREE

Left.Alone-PLAZA.iso

USERSCLOUD

Left.Alone-PLAZA.iso

JHEBERG

Left.Alone-PLAZA.iso

GO4UP

Left.Alone-PLAZA.iso

MULTI LINKS

Left.Alone-PLAZA.iso

TORRENT

Enjoy

MINIMUM:

OS: Windows 7 64-bit

Processor: Quad-core CPU ~ 2.5Ghz

Memory: 2 GB RAM

Graphics: GTX 560m / HD6870 1GB or equivalent

DirectX: Version 10

Storage: 1 GB available space

Left Alone Free Download
 1. Extract release
 2. Mount ISO
 3. Install the game
 4. Copy crack from the PLAZA folder
 5. Play!

You May Also Like:

</content></entry></feed>

I get the error, When I use to get data from it using xmls function in php. I get correct result and when I try my blogger rss feed or some other website's feeds I get correct results,So my codes which use to get data from xml is correct but the above code may be wrong or I am doing some thing else.
Your approach will be highly appreciable for me. Please help me

A: instead of htmlentities() function you can use the format of rss 2.0, I call it second way. Any ways, You can use.
<![CDATA[".$VARIABLE."]]>

Hope it works for you.


text:
Q: Google Calendar API PHP Notification Expiration Value I am successfully registering for Google Calendar API Change Notifications using PHP:
$service = new Google_Service_Calendar($client);
$channel =  new Google_Service_Calendar_Channel($service);
$channel->setId(<some random ID>);
$channel->setType('web_hook');
$channel->setAddress('https://www.myserver.net/triggerCode.php');
$timetoExpire = time()+3600000;
$channel->setExpiration($timetoExpire);
$watchEvent = $service->events->watch('<some_calendar_name>', $channel);

EXCEPT this only works if the $channel->setExpiration line is commented out.
I get an error the ttl is invalid.  I have tried setting the expiration to a number of seconds (e.g.  6000), a number of milliseconds (e.g. 600000), and time() plus some milliseconds and I always get the same error:
Invalid ttl value for channel -1402834554'

How am I supposed to set this?

A: Finally got it working.  This PHP code works:
 $service = new Google_Service_Calendar($client);
 $channel =  new Google_Service_Calendar_Channel($service);
 $channel->setId($uniqueID);
 $channel->setType('web_hook');
 $channel->setAddress('https://mydomain.net/notificationCallBack.php');

 $timetoExpire = time()+3600000;
 $optParams = array('ttl' => $timetoExpire);
 $channel->setParams($optParams);

 $watchEvent = $service->events->watch($calendarID, $channel);

The above expiration is 42 days hence but the expiration winds up set to 30 days hence.  I am guessing that that is the upper limit.

A: From the API documentation it looks like watch event doesn't include the expiration parameter.
The request takes:
{
  "id": string,
  "token": string,
  "type": string,
  "address": string,
  "params": {
    "ttl": string
  }
}

The response contains expiration, but not the request itself:
{
  "kind": "api#channel",
  "id": string,
  "resourceId": string,
  "resourceUri": string,
  "token": string,
  "expiration": long
}

Maybe you mean ttl, which is part of the request params?

FYI: It also looks like expiration is defined as Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds.


text:
Q: Debian security release I have noticed that there is a "security" release listed in the Debian security tracer.

Some of the vulnerabilities are only fixed in the "security" release, which might be still present in a different version like plain "bullseye" for example.
What exactly is the difference between plain bullseye and "bullseye (security)"?
Is there an official Docker image, where all the security patches of "bullseye (security)" are automatically included? I would like to make sure to incorporate all the stable security patches as soon as possible.

A: The bullseye (security) release refers to the most recent bullseye release with the available security patches installed.
There is apt source configured for the security patches in the official release (see the /etc/apt/sources.list file). The currently available security patches can be installed using apt-get, which is usually a good idea, since there might be some new patches available since the time of the last official release:
apt-get --yes update && apt-get --yes upgrade

which can be done in a Dockerfile as well:
RUN apt-get --yes update && apt-get --yes upgrade

After running these commands, the security patches are installed.


text:
Q: SQL replace value of with always random xml code I have the following SQL XML in several rows of a table (table is tbldatafeed column in configuration_xml).  All of the UserName="" and Password="" is different each time for each row and does not repeat so I can not find/replace off of that.  I am trying to write a query that finds all of those and replaces them with Username/Passwords I choose.
<DataFeed xmlns="http://www.tech.com/datafeed/dfx/2010/04" xmlns:plugin="pluginExtensions" Type="TODO" Guid="TODO" UserAccount="DF_LEAN_PopulateCommentsSubForm" Locale="en-US" DateFormat="" ThousandSeparator="" NegativeSymbol="" DecimalSymbol="" SendingNotifications="false" SendJobStatusNotifications="false" RecipientUserIds="" RecipientGroupIds="" RecipientEmailAddresses="" Name="CI_C11.01_Lean-Lean_Reject Comments_A2A" >
  <Transporter>
    <transporters:ArcherWebServiceTransportActivity xmlns:transporters="clr-namespace:ArcherTech.DataFeed.Activities.Transporters;assembly=ArcherTech.DataFeed" xmlns:out="clr-namespace:ArcherTech.DataFeed;assembly=ArcherTech.DataFeed" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:compModel="clr-namespace:ArcherTech.DataFeed.ComponentModel;assembly=ArcherTech.DataFeed" xmlns:channel="clr-namespace:ArcherTech.DataFeed.Engine.Channel;assembly=ArcherTech.DataFeed" xmlns:engine="clr-namespace:ArcherTech.DataFeed.Engine;assembly=ArcherTech.DataFeed" xmlns:kernel="clr-namespace:ArcherTech.Kernel.Channel;assembly=ArcherTech.Kernel" xmlns="clr-namespace:ArcherTech.DataFeed;assembly=ArcherTech.DataFeed" xmlns:schema="clr-namespace:System.Xml.Schema;assembly=System.Xml" xmlns:xmlLinq="clr-namespace:System.Xml.Linq;assembly=System.Xml" xmlns:domain="clr-namespace:ArcherTech.Common.Domain;assembly=ArcherTech.Common" xmlns:s="clr-namespace:System;assembly=mscorlib" x:Key="transportActivity" SearchType="ReportId" Uri="https://arcs-d" RecordsPerFile="100" ReportID="EC514865-88D5-49CE-A200-7769EC1C2A88" UseWindowsAuth="false" IsWindowsAuthSpecific="false" WindowsAuthUserName="i9XzCczAQ7J2rHwkg6wG9QF8+O9NCYJZP6y5Kzw4be0+cdvUaGu/9+rHuLstU736pnQrRcwmnSIhd6oPKIvnLA==" WindowsAuthPassword="+y0tCAKysxEMSGv1unpHxfg6WjH5XWylgP45P5MLRdQ6+zAdOLSVy7s3KJa3+9j2i83qn8I8K7+1+QBlCJT1E7sLQHWRFOCEdJgXaIr1gWfUEO+7kjuJnZcIEKZJa2wHyqc2Z08J2SKfdCLh7HoLtg==" WindowsAuthDomain="" ProxyName="" ProxyPort="8080" ProxyUsername="" ProxyPassword="" ProxyDomain="" IsProxyActive="False" ProxyOption="None" InstanceName="ARCS-D" TempFileOnSuccessAction="DoNothing" TempFileOnSuccessRenameString="" TempFileOnErrorAction="DoNothing" TempFileOnErrorRenameString="" Transform="{engine:DataFeedBinding Path=Transform}" SessionContext="{engine:DataFeedBinding Path=Session}">
      <transporters:ArcherWebServiceTransportActivity.Credentials>
        <NetworkCredentialWrapper UserName="TeSZmI1SqO0eJ0G2nDVU+glFg/9eZfeMppYQnPfbeg8=" Password="Slt4VHqjkYscWyCwZK40QJ7KOQroG9OTKr+RGt9bQjE=" />
      </transporters:ArcherWebServiceTransportActivity.Credentials>
    </transporters:ArcherWebServiceTransportActivity>
  </Transporter>
</DataFeed>

I need to be able to set a value and replace it with a query
I have written the following
select @config_xml=configuration_xml from bldatafeed where datafeed_name = 'REMOVED'
update tbldatafeed set configuration_xml.modify(//*:NetworkCredentialWrapper/@UserName)[1] with "abc" ')
where datafeed_name = 'REMOVED'

This does the trick but it only works if I set the "abc" password each time in each area and in some cases I am running this against 50+ rows.
I also tried:
Declare @server nvarchar(max) = 'abc'
Declare @config_xml xml
select @config_xml=configuration_xml from bldatafeed where datafeed_name = 'REMOVED'
update tbldatafeed set configuration_xml.modify(//*:NetworkCredentialWrapper/@UserName)[1] with @server ')
where datafeed_name = 'REMOVED'

The error from this is that: XQuery [tbldatafeed.configuration_xml.modify()]: Top-level attribute nodes are not supported
What I would like to be able to do is set my variable and utilize that as I will be setting this up for multiple rows and unfortunately this error is making this a very difficult problem to solve.
Thanks for any help, this has kept me confused for a bit.

A: Use the function sql:variable() to use a variable in the XQuery expression.
declare @T table(X xml);
insert into @T values('<X UserName=""/>');

declare @UserName nvarchar(max) = 'abc'

update @T set
X.modify('replace value of (/X/@UserName)[1]
           with sql:variable("@UserName")');


text:
Q: CSS cascading term The cascading term in CSS is related to the fact
that having more style sources combine them together
or only to the fact to the conflict order resolution?
Thanks

A: Yes, the cascade defines the order conflicting styles will resolve.

A: This might be of help. http://www.w3.org/TR/CSS2/cascade.html#cascade.
It seems that you have the right assumption.


text:
Q: When would we extract verb phrases from a text? I have come across plenty of material on extracting noun phrases from text. Noun phrases were defined as adjacent NN/NNS/NNP/NNPS modified by an optional JJ. It is easy to note that noun phrases are extracted to get a sense of what the text is all about and to may be generate a tag/cloud of words, or to display the distribution of noun phrases for a text corpus.
On the otherhand, what are the scenarios when a verb phrase would need to be extracted? What business problems exists that necessitate for the extraction of verb phrases?
Thanks
Abhishek S

A: On case is to extract Predicates, in most SOV langauges it is sequence of NOUN VERB NOUN. Predicate is more descriptive then pure nouns and can be used for sentiments,


text:
Q: Mercurial Unstage Specific Files from Working Directory I have an uncommitted changeset. I want to commit some of the changes, but not commit some of the files (like unstaging a file in git). Can this be done in mercurial?

A: Use the -X option to hg commit to exclude certain files.  You can specify it more than once on the command line.  For example,
hg commit -X path/to/unwanted/file -X path/to/another/file

A: You can pass a list of files to commit to hg commit, e.g. hg commit -m msg file1 file2 ....

A: Yep! You have two options.

*

*Commit just some files.
If you provide file names as arguments to hg commit, only those files will be committed. So if I have the following hg status:
M foo.txt
M bar.txt

I can run hg commit foo.txt to commit just the changes to foo.txt and leave the changes in bar.txt for a later commit.

*Use the record extension.
The Record extension gives Mercurial behavior to git's index, letting you commit just some patches of your changes (like git add --patch). See the docs for more info.