text:
Q: How to remove element from 2d array I have a 2d array like this:
var rawData = [
    [1325347200000, 60], [1328025600000, 100], [1330531200000, 15], [1333209600000, 50]
];

//MEMORY
mem.push([
    iteration,
    memory.usage / (1024*1024)
]);

that keeps growing. I want to limit the size to 20, so I want to remove the oldest element in the array. I tried this but remove one element but keeps growing
//Remove first
if(iteration % 20 === 0) {
    rawData = rawData.splice(1);
}

A: I would implement an own push method that leftshifts the whole array:
class LimitedArray extends Array {
  constructor(max, ...args){
     super(max);
     this.push(...args);
  }

  push(...els){
    for(let i = els.length; i < this.length; i++)
          this[i - els.length] = this[i];
    for(let i = 0; i < els.length; i++)
       this[i + this.length - els.length] = els[i];
  }
}

So one can do:
 const cache = new LimitedArray(20);
 cache.push(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
cache.push(22);

If you really want to do that "inline", you can do:
 mem.push([1,2]);
 if(mem.length > 20) mem.shift();

Or if its not accurate and mem might be longer than 21:
mem.push([1,2],[3,4]);
if(mem.length > 20) mem.splice(0, mem.length - 20);

As suggested in the comments already, that can be simplified to:
mem.push([1,2], [3,4]);
mem = mem.slice(-20);

however that might be less performant and less memory efficient.


text:
Q: Kolmogorov distribution CDF to p-value I'm implementing the two sample K-S test using the great Wikipedia page.
As an example, I have two lists:
1 2 3 4 5 6 7 6 1 3 4
and
1 3 2 10 11 4 1 15 13 3 17
$D_n$, the largest absolute difference between the two cumulative distributions is 0.4545 (confirmed via this online K-S test).
The Wikipedia page says that I reject when $\sqrt{\frac{n_1 n_2}{n_1 + n_2}} D_n$ exceeds the critical value $K_\alpha$. Thus, I should be able to compute my p-value using the CDF for the $K$ statistic:
$x = \sqrt{\frac{n_1 n_2}{n_1 + n_2}} D_n$
$p-value = Pr(K \leq x)$
For the example lists, $x = 0.4545 \sqrt{\frac{11}{2}} = 1.0660025157744704$
Wikipedia lists two forms of the CDF:

Although I get the same answer for both forms of the CDF for this $x$, I get this:
$p-value = Pr(K \geq x) = 1-K_{CDF}(x) = 1-0.794163 = 0.205837$
Why does this $p-value$ not match the one given by the applet (also confirmed with SciPy), 0.147? What have I done wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: typescript param type dependency from value not working interface AddDataRequest{
    data:any
}
interface AddDataResponse{
    id:string
}
interface ITest{
    addData(json:AddDataRequest):Promise<AddDataResponse>
    removeData(json:AddDataResponse):Promise<boolean>
}
function testInterface<A extends keyof ITest>(action:A,req:Parameters<ITest[A]>[0],res:Awaited<ReturnType<ITest[A]>>){
    if(action === 'addData'){
        console.log(res.id); //TS2339: Property 'id' does not exist on type 'boolean | AddDateResponse'. Property 'id' does not exist on type 'false'.
    }
    else if(action==='removeData'){
        console.log(req.id); //TS2339: Property 'id' does not exist on type 'AddDateRequest | AddDateResponse'. Property 'id' does not exist on type 'AddDateRequest'.
    }
}
testInterface('removeData', {id:'test123'},true);//But works here

I am trying to make type dependency of function parameters from first one. It works when I'm trying to call the function but not works inside of it. Errors are in comments inside the code.

A: This is a common difficulty: maintaining the correlation between function parameters types, when type narrowing one of them.
The usual workaround is to gather these correlated parameters into a single object, and typing the latter as a discriminated union of the different possibilities (e.g. by using a mapped type and indexed access type).
That way, when we perform type narrowing on the discriminant property (here action), TypeScript is able to narrow the entire object:
// Build a discriminated union:
type TTestFullUnion = {
    //^? { action: "addData"; req: AddDataRequest; res: AddDataResponse } | { action: "removeData"; req: AddDataResponse; res: boolean }
    [kind in keyof ITest]: { // Mapped type to describe the correlation
        action: kind, // Discriminant property
        req: Parameters<ITest[kind]>[0],
        res: Awaited<ReturnType<ITest[kind]>>
    }
}[keyof ITest] // Indexed access type to produce a union out of the mapped type

function testInterface2<ActionFull extends TTestFullUnion>(actionFull: ActionFull) {
    const { action, req, res } = actionFull;
    if (action === 'addData') {
        console.log(res.id); // Okay
        //          ^? AddDataResponse
    }
    else if (action === 'removeData') {
        console.log(req.id); // Okay
        //          ^? AddDataResponse
    }
}
testInterface2({
    action: 'removeData',
    req: { id: 'test123' },
    res: true
}); // Okay

Unfortunately, that means slightly changing your API.
Playground Link


text:
Q: Google Cloud Identity Aware Proxy over Corporate Proxy Configured Google Cloud Identity Aware Proxy for the application. So far, I can ssh to it no problem, as long as I am not using corporate proxy. Tried over proxy (with IAP endpoint being in 'allow' list in corporate proxy), but it failed with SSL CERTIFICATE error.
Errors:
...
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 853, in _create
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 1117, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)
INFO: Error during WebSocket processing:
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

INFO: Client closed connection from [stdin].
DEBUG: (gcloud.compute.start-iap-tunnel) Error while connecting [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)].
Traceback (most recent call last):
  File "/usr/local/Caskroom/google-cloud-sdk/latest

...

Has anyone succeeded in configuring corporate proxy for IAP? If yes, what configuration would you think is needed to get it working?
Thanks so much in advance!!

A: Answering my own question:
Yes, a proxy can be configured to access IAP endpoint nodes.
Steps:

*

*Ask your friendly proxy admins to add the following to allow list:
wss://tunnel.cloudproxy.app

*Configure your current GCLOUD_SDK environment
$ gcloud config set proxy/type http
Updated property [proxy/type].
 $ gcloud config set proxy/address proxy.testcorp.com
 Updated property [proxy/address].

 $ gcloud config set proxy/port 8080
 Updated property [proxy/port].

 $ gcloud config set proxy/username user001
 Updated property [proxy/username].

 $ gcloud config set proxy/password XXXXXXXXXXXX
 Updated property [proxy/password].

*Make sure you have correct SSL Certs installed on your workstation. You can configure GCLOUD_SDK to use your certs using the following command:
gcloud config set custom_ca_certs_file  /Users/user01/gce/certs/corpcerts.pem
Next you can go ahead and issue 'gcloud ssh' command with --tunnel-through-iap  to connect to your node.


text:
Q: displaying data properly with a PHP function public function Read($Table, $Fields, $Condition, $Orderby, $Limit) {
    $Query = "SELECT $Fields FROM $Table";
    if ($Condition != null) {
        $Query .= " WHERE " . $Condition;
    }
    if ($Orderby != null) {
        $Query .= " ORDER BY " . $Orderby;
    }
    if ($Limit != null) {
        $Query .= " LIMIT " . $Limit;
    }
    $Result = mysql_query($Query);
    while ($Row = mysql_fetch_assoc($Result)) {
        echo "
";
        foreach ($Row as $Key => $Value) {
            echo "" . $Value . "	";
        }
        echo "
";
    }
}

Hello Friends, My goal was to create a generic function as to fetch records from database and display in a table so that i can use it in every application. I've so far managed to show the records in table with the above code. But i want to have a update and delete link on every row in a .. On the update and delete link i want to pass the get value of id for that currect record.
I am also needing some feedback if this is the correct method i am following to make a Read(); function with the aim of making it generic. PS. I just started OOP.
Thanks in advance.

A: Add cells the the table with update and delete links.
    while ($Row = mysql_fetch_assoc($Result)) {
        echo "
";
        foreach ($Row as $Key => $Value) {
            echo "" . $Value . "	";
        }
        echo "Update";
        echo "Delete";
        echo "
";
    }

update.php should display a form to update the record, while delete.php would just delete the specified record and redirect back to the display page.


text:
Q: Dropdown Option Structure I need to create a tree structure for my category options list in form.
My form type code for options list:
->add('discipline', 'entity', array('label' => 'Parent Discipline',
    'empty_value'   => 'Parent Discipline...',
    'required'      => true,
    'empty_data'    => null,
    'class'         => 'RFQ\IronilBundle\Entity\ProductionType',
    'query_builder' => function(ProductionTypeRFQRepository $er) {return  $er->createQueryBuilder('w')->where('w.parent IS NULL')->addOrderBy('w.name', 'ASC');},
    'attr'          => array('class'=>'form-control login-input')))

As you can see I have connected Repository which will get options list from database in tree structure, but I don't know how exactly to do that. Now my Repository looks like this:
    <?php

namespace RFQ\IronilBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ProductionTypeRFQRepository extends EntityRepository
{
    public function findAllParents()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT p FROM RFQIronilBundle:ProductionType p WHERE p.parent IS NULL ORDER BY p.name ASC')
            ->getResult();
    }

    public function findAll()
    {
        return $this->findBy(array(), array('name' => 'ASC'));
    }
}

This repository only gets parents, but not the children from database.
Please, give some information where to find a solution for this.
EDIT:
For request, this is my Entity for categories:
    <?php

namespace RFQ\IronilBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ProductionType
 *
 * @ORM\Table(name="production_type")
 * @ORM\Entity(repositoryClass="RFQ\IronilBundle\Entity\ProductionTypeRepository")
 * @ORM\Entity(repositoryClass="RFQ\IronilBundle\Entity\ProductionTypeRFQRepository")
 */
class ProductionType
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     * @ORM\OneToMany(targetEntity="RFQ", mappedBy="discipline")
     */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="ProductionType", mappedBy="parent")
     * @ORM\OrderBy({"name" = "ASC"})
     **/
    protected $children;

    /**
     * @ORM\ManyToOne(targetEntity="ProductionType", inversedBy="children")
     **/
    protected $parent;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set name
     *
     * @param string $name
     * @return ProductionType
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add children
     *
     * @param \RFQ\IronilBundle\Entity\ProductionType $children
     * @return ProductionType
     */
    public function addChild(\RFQ\IronilBundle\Entity\ProductionType $children)
    {
        $this->children[] = $children;

        return $this;
    }

    /**
     * Remove children
     *
     * @param \RFQ\IronilBundle\Entity\ProductionType $children
     */
    public function removeChild(\RFQ\IronilBundle\Entity\ProductionType $children)
    {
        $this->children->removeElement($children);
    }

    /**
     * Get children
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Set parent
     *
     * @param \RFQ\IronilBundle\Entity\ProductionType $parent
     * @return ProductionType
     */
    public function setParent(\RFQ\IronilBundle\Entity\ProductionType $parent = null)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return \RFQ\IronilBundle\Entity\ProductionType
     */
    public function getParent()
    {
        return $this->parent;
    }

    public function __toString()
    {
        return $this->name;
    }
}

And Entity for my RFQ in which I need this Tree structure with categories (I have removed all items which doens't need for problem):
    <?php

namespace RFQ\IronilBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * RFQ
 *
 * @ORM\Table(name="rfq")
 * @ORM\Entity
 */
class RFQ
{
    //RFQ overall
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="ProductionType",inversedBy="name")
     * @ORM\JoinColumn(referencedColumnName="id")
     **/
    protected $discipline;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set discipline
     *
     * @param \RFQ\IronilBundle\Entity\ProductionType $discipline
     * @return RFQ
     */
    public function setDiscipline(\RFQ\IronilBundle\Entity\ProductionType $discipline = null)
    {
        $this->discipline = $discipline;

        return $this;
    }

    /**
     * Get discipline
     *
     * @return \RFQ\IronilBundle\Entity\ProductionType
     */
    public function getDiscipline()
    {
        return $this->discipline;
    }
}

A: With some liters of coffee and energy drinks I managed how to resolve my problem. I will write something like a tutorial here to help everyone who got this problem too, because it was very hard to find a nice tutorial how to do it.

*

*Add these bundles to your composen.json and run composer update.
"yavin/symfony-form-tree": "dev-master",
"gedmo/doctrine-extensions": "dev-master",
"stof/doctrine-extensions-bundle": "1.1.*@dev"

links to bundles: symfony-form-tree; DoctrineExtensions; StofDoctrineExtensionsBundle

*After adding bundles you need to register StofDoctrineExtensionBundle in AppKernel.php
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle()

*Now you need to add right Gedmo annotations to category entity (my category calls ProductionType.php)
<?php

namespace RFQ\IronilBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="production_type")
 * @Gedmo\Tree(type="nested")
 * @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
 */
class ProductionType
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     * @ORM\OneToMany(targetEntity="RFQ", mappedBy="discipline")
     */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="ProductionType", mappedBy="parent")
     * @ORM\OrderBy({"name" = "ASC"})
     **/
    protected $children;

    /**
     * @ORM\ManyToOne(targetEntity="ProductionType", inversedBy="children")
     * @Gedmo\TreeParent
     **/
    protected $parent;

    /**
     * @var integer
     *
     * @Gedmo\TreeLeft
     * @ORM\Column(type="integer")
     */
    private $treeLeft;

    /**
     * @var integer
     *
     * @Gedmo\TreeLevel
     * @ORM\Column(type="integer")
     */
    private $treeLevel;
    /**
     * @var integer
     *
     * @Gedmo\TreeRight
     * @ORM\Column(type="integer")
     */
    private $treeRight;
    /**
     * @var integer
     *
     * @Gedmo\TreeRoot
     * @ORM\Column(type="integer", nullable=true)
     */
    private $treeRoot;

    // Generated setters and getters

*Add extensions to your mapping and activate extension you need (in my case Tree)
stof_doctrine_extensions:
    orm:
        default:
            tree: true

*Now you need work with symfony-form-tree. first add services to Resources/config/services.xml
<service id="symfony.form.type.tree" class="Yavin\Symfony\Form\Type\TreeType">
   <argument type="service" id="property_accessor"/>
   <tag name="form.type" alias="y_tree"/>
</service>

<service id="symfony.form.type_guesser.tree" class="Yavin\Symfony\Form\Type\TreeTypeGuesser">
   <argument type="service" id="doctrine"/>
   <tag name="form.type_guesser"/>
</service>

*At last you need to create form builder for symfony-form-tree to create hierarchical dropdown options list:
->add('discipline', 'y_tree', array(
    'class' => 'RFQ\IronilBundle\Entity\ProductionType', // tree class
    'levelPrefix' => '--',
    'orderFields' => array('treeRoot', 'treeLeft'),
    'prefixAttributeName' => 'data-level-prefix',
    'treeLevelField' => 'treeLevel',
))

That's all! I am not saying that this is the right way to make hierarchical dropdown options list and maybe I have made some mistakes, but this is working for me perfect.


text:
Q: jbuilder access to nested models class Parent
belongs_to :condition
has_many   :conditionregions, through: :condition

class Condition
translates :description, :fallbacks_for_empty_translations => true
globalize_accessors

class Conditionregion
belongs_to :region

With jbuilder the associations can be chained on parent defined relatives, including translations,
json.conditionregions @event.condition.conditionregions, :region_id
json.translations @event.condition.translations, :locale, :description

However, extracting the related data of a relation returns a NoMethodError undefined methodregion`
json.regions @event.condition.conditionregions.region, :name

How can this latter information be accessed?  Must the model also chain down (and how to do so?) or is there a syntaxic hoop to jump through?

A: Try this,
json.regions @event.condition.conditionregions.joins(:region).pluck('region.name')

A: RTFM, as per gem instructions
json.regions @event.condition.conditionregions do |conditionregion|
  json.name conditionregion.region.name
end


text:
Q: Swift: getting error while decoding using CodingKey I have created a model and I need to try to add value to one of the CodingKey's case
struct Model {
  let name: String
  let location: String
  let descriptions: String

}

enum CodingKeys: String, CodingKey {

  case name = "NAME"
  case location = "LOCATION"
  case descriptions = "INFO-\(NSLocalizedString("Language", comment: ""))"

}

init(from decoder: Decoder) throws {

  let container = try decoder.container(keyedBy: CodingKeys.self)
  .
  .
  descriptions = try container.decode(String.self, forKey: .descriptions)

}

Now compiler gives me this error

 Raw value for enum case must be a literal

How can I fix this error?

A: You don't have to use an enum for CodingKeys. You can also use a struct with static lets. It's just a bit more boilerplate:
struct Model: Decodable {
    let name: String
    let location: String
    let descriptions: String

    struct CodingKeys: CodingKey {
        let intValue: Int? = nil
        let stringValue: String

        init(stringValue: String) {
            self.stringValue = stringValue
        }

        init?(intValue: Int) {
            return nil
        }

        static let name = CodingKeys(stringValue: "name")
        static let location = CodingKeys(stringValue: "location")
        static let description = CodingKeys(stringValue: "INFO-\(NSLocalizedString("Language", comment: ""))")
    }

    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        location = try container.decode(String.self, forKey: .location)
        descriptions = try container.decode(String.self, forKey: .description)

    }
}


text:
Q: Unable to find the requested Data Provider So i made a new asp .net mvc application and just  I still get this error ,
when I run it then show error "Unable to find the requested .Net Framework Data Provider" and if entered id in url like "localhost/MVC_Demo/employee/Details/2"
then it show error in ...Please tell me how to solve?
EmployeeContext.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MVC_Demo.Models
{
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }
}

EmployeeController.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Demo.Models;

namespace MVC_Demo.Controllers
{
    public class EmployeeController : Controller
    {

        public ActionResult Details(int id)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            Employee employee = employeeContext.Employee.Single(emp => emp.ID == id);

            return View(employee);
        }
    }
}

Web.config
<connectionStrings>
    <add name="EmployeeContext" connectionString="Server=.; database=dbEmployees; Integrated Security=SSPI" providerName="System.Data.Client" />
  </connectionStrings>

Employee.cs File
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVC_Demo.Models
{
    [Table("Emp")]
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public int Salary { get; set; }
    }
}

A: this works fine,
<system.data>
    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>


text:
Q: How can I implement a command line option in Bazel to switch between which dependency version is used for building? For some background, the C++ program I am working on has the possibility to interoperate with some other applications that use various Protobuf versions. In the source code for my program, I have the compiled .pb.cc files from these other applications for the Protobuf interface. These .pb.cc files were compiled with a particular version of Protobuf, and I don't have any control over this. I am using Bazel to build, and I want to be able to specify a Bazel build configuration for my program, which will use a particular version of Protobuf which matches that of one of the possible other applications.
Originally, I wanted to put something in the .bazelrc file so that I can specify a particular version of Protobuf depending on the config, for example:
# in .bazelrc:
build:my_config --protobuf_version=3_20_1
build:my_other_config --protobuf_version=3_21_6

Then from the terminal, I could build with the command
bazel build --config=my_config //path/to/target:target

which would build as if I had typed
bazel build --protobuf_version=3_20_1 //path/to/target:target

At this point, I wanted to use the select() function, as detailed in the Bazel docs for Configurable Build Attributes, to use a particular Protobuf version during building. But, the Protobuf dependencies are all specified in the WORKSPACE file, which is more limited than a BUILD file, and this select() function cannot be used there. So then my idea was to pull in every version of the Protobuf library that I would possibly need, and give them different names in the WORKSPACE file, and then in the BUILD files, use a select() function to  choose the correct version. But, the Bazel rule for compiling the proto_library is used as such:
proto_library(
    name = "foo",
    srcs = ["foo.proto"],
    strip_import_prefix = "/foo/bar/baz",
)

I don't see of any opportunity to use a select() function here to specify which Protobuf version's proto_library rule should be used. The proto_library rule is also defined in from the WORKSPACE file with:
load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
rules_proto_dependencies()
rules_proto_toolchains()

Now, I would say that I am stuck. I don't see a way to specify on the command line which version of Protobuf should be used with the proto_library rule.
In the end, I would like a way to do the equivalent in the WORKSPACE file of
# in WORKSPACE
if my_config:
    # specific protobuf version:
    http_archive(
      name = "com_google_protobuf",
      sha256 = "8b28fdd45bab62d15db232ec404248901842e5340299a57765e48abe8a80d930",
      strip_prefix = "protobuf-3.20.1",
      urls = ["https://github.com/protocolbuffers/protobuf/archive/v3.20.1.tar.gz"],
    )
elif my_other_config:
    # same as above, but with different version
else:
    # same as above, but with default version

According to some google groups discussion, this doesn't seem to be possible in the WORKSPACE file, so I would need to do it in a BUILD file, but the dependencies are specified in the WORKSPACE.

A: I figured out a way that works that seems to go against Bazel's philosophy, but most importantly does what I want.
The repository dependencies are loaded in the first of two steps, the first involving the WORKSPACE file, and the second involving the BUILD file. Command line flags for the build cannot be normally be directly passed to the WORKSPACE, but it is possible to get some information to the WORKSPACE by setting an environment variable and creating a repository_rule. In the WORKSPACE, this  environment variable can be used, for example, to change the url argument to http_archive which specifies the dependency version.
This repository rule is created in a separate file .bzl file, which is then loaded in the WORKSPACE.  As a generalized example of how get environment variable values into the WORKSPACE, the following file my_repository_rule.bzl could be created:
# in file my_repository_rule.bzl
def _my_repository_rule_impl(repository_ctx):
    # read the particular environment variable we are interested in
    config = repository_ctx.os.environ.get("MY_CONFIG_ENV_VAR", "")

    # necessary to create empty BUILD file for this rule
    # which will be located somewhere in the Bazel build files
    repository_ctx.file("BUILD")

    # some logic to do something based on the value of the environment variable passed in:
    if config.lower() == "example_config_1":
        ADDITIONAL_INFO = "foo"
    elif config.lower() == "example_config_2":
        ADDITIONAL_INFO = "bar"
    else:
        ADDITIONAL_INFO = "baz"

    # create a temporary file called config.bzl to be loaded into WORKSPACE
    # passing in any desired information from this rule implementation
    repository_ctx.file("config.bzl", content = """
MY_CONFIG = {}
ADDITIONAL_INFO = {}
""".format(repr(config), repr(ADDITIONAL_INFO ))
    )

my_repository_rule = repository_rule(
    implementation=_my_repository_rule_impl,
    environ = ["MY_CONFIG_ENV_VAR"]
)

This can be used in the WORKSPACE as such:
# in file WORKSPACE
load("//:my_repository_rule.bzl", "my_repository_rule ")
my_repository_rule(name = "local_my_repository_rule ")
load("@local_my_repository_rule //:config.bzl", "MY_CONFIG", "ADDITIONAL_INFO")

print("MY_CONFIG = {}".format(MY_CONFIG))
print("ADDITIONAL_INFO = {}".format(ADDITIONAL_INFO))

When a target is built with bazel build, the WORKSPACE will receive the value of the MY_CONFIG_ENV_VAR from the terminal and store it in the Starlark variable MY_CONFIG, and any other additional information determined in the implementation.
The environment variable can be passed by normal means, such as typing in a bash shell, for example:
MY_CONFIG_ENV_VAR=example_config_1 bazel build //path/to/target:target

It can also be passed as a flag with the --repo_env flag. This flag sends an extra environment variable to be available to the repository rules, meaning the following is equivalent:
bazel build --repo_env=MY_CONFIG_ENV_VAR=example_config_1 //path/to/target:target

This can be made easier to switch between by including the following in the .bazelrc file:
# in file .bazelrc
build:my_config_1 --repo_env=MY_CONFIG_ENV_VAR=example_config_1
build:my_config_2 --repo_env=MY_CONFIG_ENV_VAR=example_config_2

So running bazel build --config=my_config_1 //path/to/target:target will show the debug output from the print statements in WORKSPACE as the following:
MY_CONFIG = example_config_1
ADDITIONAL_INFO = foo

If ADDITIONAL_INFO in the rule implementation (in the file my_repository_rule.bzl) were set to a version number such as "3.20.1", then the WORKSPACE could, for example, use this in an http_archive call to pull the desired version of the dependency.
# in file WORKSPACE
if ADDITIONAL_INFO == "3.20.1":
    sha256 = "8b28fdd45bab62d15db232ec404248901842e5340299a57765e48abe8a80d930"

http_archive(
  name = "com_google_protobuf",
  sha256 = sha256,
  strip_prefix = "protobuf-{}".format(ADDITIONAL_INFO),
  urls = ["https://github.com/protocolbuffers/protobuf/archive/v{}.tar.gz".format(ADDITIONAL_INFO)],
)

Of course, the value of the sha256 kwarg could also be passed in from the repository rule as a separate string variable, or as part of a dictionary, for example.


text:
Q: In Xamarin, how can I change the background color of a button for just 1 second and return it again to its original color? I'm developing a little app in Xamarin and I want to change the background color of a button just for 1 second when the user presses it. The code I'm trying to use is the following:
var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
btnCancel.BackgroundColor = Color.Red;       // changing the color to red
Task.Delay(1000).Wait();                     // waiting 1 second
btnCancel.BackgroundColor = auxColor;        // restoring the original color

But what I get is the following sequence:
1- Saving the original color
2- WAITING 1 SECOND
3 Changing the color to red
4 Immediately restoring the color
Does anybody know how to solve this problem?

A: You can use the Device.StartTimer in the following manner.
In your button click event:
private void OnButtonClicked(object sender, EventArgs e)
{
    var auxColor = btnCancel.BackgroundColor;    // saving the original color
    btnCancel.BackgroundColor = Color.Red;

    Device.StartTimer(TimeSpan.FromSeconds(1), () =>
    {
        btnCancel.BackgroundColor = auxColor;
        return false;
    });
}

To interact with UI elements you can use BeginInvokeOnMainThread like:
Device.StartTimer (new TimeSpan (0, 0, 1), () =>
{
    // do something every 1 second
    Device.BeginInvokeOnMainThread (() =>
    {
      // interact with UI elements
    });
    return true; // runs again, or false to stop
});

See Device.StartTimer docs.

A: Looks like you are calling the steatements in a method executed by the main thread, which is also responsible for rendering. This means your statement
Task.Delay(1000).Wait();                     // waiting 1 second

blocks rendering, so your change will not be visible.
There are different possible approaches to solve your problem, simplest approach would be using an async method, to allow the UI thread to continue in background:
private async void blink()
{
    var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
    btnCancel.BackgroundColor = Color.Red;       // changing the color to red
    await Task.Delay(1000)                       // waiting 1 second
    btnCancel.BackgroundColor = auxColor;        // restoring the original color
}

Another possible solution would be to setting the original color after the delay was finished using the original (UI) thread context again:
var auxColor = btnCancel.BackgroundColor;        // saving the original color (btnCancel is the button name)
btnCancel.BackgroundColor = Color.Red;           // changing the color to red
Task.Delay(1000).ContinueWith((T) =>             // waiting 1 second
    {
        btnCancel.BackgroundColor = auxColor;    // restoring the original color
    }, TaskScheduler.FromCurrentSynchronizationContext());


text:
Q: Claims and SAML2 confusion My understanding is that claims are an STS thing based on WS-trust standard and nothing to do with SAML2 standard. WS-trust STS token can use SAML to send claims in that format. Am I correct?

A: Claims is a general concept - a claim is a piece of information about a user.
In SAML2 the same concept is present, but it is named attribute instead. There is also a special treatment in SAML2 of the SubjectNameId field - usually the username. When translated to a .NET ClaimsIdentity it is simply just another claim.

A: Claims are essentially a Microsoft concept. In that world, claims are the signed statements made about an identity by ADFS and interpreted by WIF e.g. Mobile = 12345678.
The mechanism used to pass this information is a SAML token (not to be confused with the SAML protocol).
This contains SAML assertions as above - WIF takes this base information and returns a claims object to the application.
Claims are not restricted to WS-Trust - that's essentially active (web services). They are also used by WS-Federation which is passive (browser).

A: Claims are a general concept - completely independent of the token type or protocol that is used.


text:
Q: WebStorm warning when using viewBox property on an inline svg tag I use an SVG tag with viewBox attribute, inlined in an HTML file.
<!doctype html>
<html><!-- ... ---><body>
  <!-- ... -->
  <svg viewBox="0 0 17 17">
    <!-- ... -->
  </svg>
  <!-- ... -->
</body></html>

Despite the fact it is working (and required here), WebStorm gives me a warinig:

Attribute viewBox is not allowed here

Am I doing something wrong or is it just a bug in WebStorm?

A: Please try adding namespace attribute to svg tag, like <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 17 17"> - this should solve the problem. According to specification, "in all cases, for compliance with the Namespaces in XML Recommendation [XML-NS], an SVG namespace declaration must be provided so that all SVG elements are identified as belonging to the SVG namespace."


text:
Q: VSCode does not recognize jest custom matcher I'm currently struggling with making a Jest custom matcher work in VSCode with typescript.
I wrote a custom matchers file like the following (I've simplified the test for brevity reasons):
export {}

declare global {
  namespace jest {
    interface Matchers<R, T = {}> {
      toSucceed(): R
    }
  }
}

function toSucceed(this: jest.MatcherContext, received: Result<any>): any {
  return {
    pass: true,
    message: () => 'Custom matcher message',
  }
}

expect.extend({
  toSucceed,
})

I included this file path in my jest.config.ts under the tag setupFilesAfterEnv.
Then I wrote tests like:
it('should pass', () => {
  expect(foo()).toSucced()
})

All this configuration works fine, but I still get a VSCode inline error:
Property 'toSucceed' does not exist on type 'JestMatchers<any>'
JestMatchers is a type definition inside the @types/jest root, since it is a type I cannot augment it directly.
Have anyone experienced any similar problem?

A: I encountered a similar error message when the namespace declaration of "interface Matchers" was incorrect. After fixing that, a custom matcher appeared in jestMatchers, too. Matchers and jestMatchers are connected.
Your code works fine for me—except for the undefined Result<any>—so you can try to directly import in test and see if Visual Studio Code can understand the declaration:
import "./toSucceed";

If direct import works for you, I would guess that there's a problem with the jest extension which helps Visual Studio Code understand jest.config.

A: Did you remember to add the type definitions to your tsconfig?
For me it works fine when I put the type definition in a d.ts file at the root level, and add that path to the "include" option in my tsconfig:
{
  // Some other config
  "include": [
    "custom-matchers.d.ts"
  ]
}

Haven't tested with your custom matcher specifically, but I had a similar issue that I resolved like this.
So your custom-matchers.d.ts would be:
export {}

declare global {
  namespace jest {
    interface Matchers<R, T = {}> {
      toSucceed(): R
    }
  }
}


text:
Q: In a JPA query, how do I pass in a list for use as a single-column table? I have a list of IDs, and I need a query to return only those that do not exist in the specified table. I know that, in SQL, you can do it like this:
select *
from (
   values (4),(5),(6)
) as v(id)
where not exists (select *
   from images i
   where i.id = v.id);

(From this answer: Link)
But I'm attempting to use a JPA @Query, and pass in the list as a parameter, which it doesn't seem to like.
SELECT t.id
FROM :ids AS t(id)
WHERE NOT EXISTS
    ([Nested select clause])

With
List<Long> findIdsMissingFromTable(@Param("ids") List<Long> ids, [...]

I have also tried (VALUES :ids), which it also doesn't like, and removing the AS with the same result. In all cases, I get QuerySyntaxException: unexpected token: ( near line 1, column 18 [...] which seems to be the colon in the first case, or the open parenthesis in the second.
What should I be doing instead?

A: JPA queries do not allow subqueries outside of WHERE or HAVING clauses. The subquery in this case is (VALUES :ids), because it makes a table the rest of the query can use. If it could be reorganised to have the subquery in the WHERE clause, the problem could be solved that way. However, setting nativeQuery = true was the simplest solution for my case, because I did not need any JPA-specific features like FETCH.

A: I tried passing using the native query and values(:ids). It is picking only one id instead of all the passed id's in the list. Did you do any additional steps to create the query


text:
Q: How to assert a value in an xml using karate I have below xml response and I need to assert for 'result' value using karate
<Values version="2.0">
  <value name="num1">4</value>
  <value name="num2">3</value>
  <value name="n1">4</value>
  <value name="result">7</value>
  <value name="n2">3</value>
  <value name="value">7</value>
</Values>

I am able to get data for 'Values' object but not for 'result' element.

A: * def response =
"""
<Values version="2.0">
  <value name="num1">4</value>
  <value name="num2">3</value>
  <value name="n1">4</value>
  <value name="result">7</value>
  <value name="n2">3</value>
  <value name="value">7</value>
</Values>
"""
* match /Values//value[@name='result'] == '7'


text:
Q: Is my proof of equivalence valid? Let $A \succeq B$ be defined as $A$ is at least as probable as $B$. $A \succ B$ is defined as $A\succeq B$ and $B \nsucceq A$, i.e. $A$ is strictly more probable than $B$. $A \approx B$ is defined as $A\succeq B$ and $B \succeq A$, i.e. $A$ is equiprobable as $B$. An axiom that $\succeq$ obeys is
Additivity: If $A \cap C=B \cap C=\emptyset$, then $A \succeq B$ if and only if $A \cup C \succeq B \cup C$.
I would like to prove that the following two constraints on $\succeq$ are equivalent.
Regularity:$\forall A(A \neq \emptyset \rightarrow A \succ \emptyset)$
Regularity 2: $\forall A(A \neq \Omega \rightarrow \Omega \succ A)$
Here's my proof. Assume that Regularity is true first. Assume that Regularity 2 is false for reductio. This means that $\exists A (A\neq \Omega \land \Omega \nsucc A)$. Let $a$ be this $A$. So $a \neq \Omega \land \Omega \approx a$. Since $a \neq \Omega$, the complement of $a^c \neq \emptyset$. By Regularity, $a^c \succ \emptyset$. This means $\emptyset \nsucceq a^c$. By Additivity, $a= \emptyset \cup a \nsucceq a^c \cup a = \Omega$. Since $\Omega \approx a$, $a \succeq \Omega$. Contradiction. So Regularity 2 must be true. The same steps can be used to prove Regularity while assuming Regularity 2. Therefore, Regularity is equivalent to Regularity 2.
Is my proof valid? My worry is that I used Additivity. Is this okay?
Edit: typo in Additivity


text:
Q: Flask OpenApi web service in uWSGI and NGinx I am having great problems getting this to work.
We have a web service which is configured in Flask with OpenApi.
During dev, it was setup within the
if __name__ == '__main__'  phase.
However, this is never called by uWSGI and so I have had to remove that condition.
Afterwards, the service was launched with an app.run(...) binding to a given ip and port.
If I keep the app.run() call (with no parameters), the uWSGI log spits out the standard flask warning that it is only a dev server and should not be used for production.
Here is how the service is initialised :
import connexion
from flask_cors import CORS

from src.middlewares import Log as midLog
from src.middlewares import DB as midDb

import utils
from web.doc import bp_doc

# Instance a Flask server with Connexion library that validate openAPI
app = connexion.FlaskApp(__name__, specification_dir='specification/')

# DB init
app.app.wsgi_app = midDb.DB(app.app)

# Load OPEN API doc
utils.load_openapi()

# OpenAPI doc verif + CORS + Doc
app.add_api(sfile.File.path("tmp","config.adhoc","openapi.yaml"), options = {"swagger_ui": False},validate_responses=True,base_path="/")
CORS(app.app) # Build CORS Header
app.app.register_blueprint(bp_doc,url_prefix='/doc') # Register Blueprint

# Active Log
app.app.wsgi_app = midLog.Log(app.app,DEBUG)

#app.run()

The uWSGI ini file is configured thus :
[uwsgi]
module=wbsvc:application
wsgi-file=wbsvc.py

master = true
processes = 10

buffer-size=65535

socket = wbsvc.sock
chmod-socket = 660
vacuum = true
die-on-term = true

With the nginx config being like this :
server {
        listen 80;
        server_name localhost;

        client_max_body_size 10M;
        keepalive_timeout 60s;
        client_body_timeout 60s;

        sendfile on;
        client_body_buffer_size 20m;

        location /wbsvc {
                include uwsgi_params;
                uwsgi_pass unix:/home/webservice/svc/wbsvc.sock;
        }
}

The uWSGI server is setup as a service using the following definition :
    [Unit]
    Description=uWSGI configuration file for the web service
    After=network.target

    [Service]
    User=web_services
    Group=www-data

    WorkingDirectory=/home/webservice/svc/
    Environment="PATH=/home/webservice/svc/ws_env/bin"
    ExecStart=/home/webservice/svc/ws_env/bin/uwsgi --ini ws.ini

    [Install]
    WantedBy=multi-user.target

Everything runs up ok, but when I call the web service from a client system, there is a log created :
ERROR HANDLING
[pid: 17399|app: 0|req: 1/1] 81.250.236.200 () {40 vars in 734 bytes} [Fri Jul  8 11:52:24 2022]
POST <url requested> => generated 106 bytes in 17 msecs (HTTP/1.1 500) 4 headers in 135 bytes (2 switches on core 0)

From my other logs, it would appear that the web service never gets called.
I am sure that other people have successfully setup a web service using python, flask, OpenApi, uWSGI and NGinx.
Can anyone help me out with this, I've been at it for over a week now with no real progress.
Extra details :
System : Ubuntu 18.04 LTS
Python 3.8
Nginx : 1.14.0
uWSGI : 2.0.20
Flask : 2.1.2

Edit :
Note that the requests are POST calls.


text:
Q: AngularJS: How to change url in $http.get on select event I have customers.php file which produce json data. List of json data are changing when we change variable in the url like this
customers.php?var=5
In AngularJS I have made html file with two separate part. 1st part is a select options with specific values. 2nd part is part who shows json data. It is clear that 2nd part use $http.get(url) where url is customers.php?var=selected_number in controller.
How can I change url in controller which use $http.get when user select specific options in < select > ... < / select > html file.
Footnote: Here is example of controller file
var Pajsije = angular.module('CodeOverflow', ['ngRoute']);

    Pajsije.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/viewa', {
            templateUrl : 'viewa.html',
            controller  : 'ViewAController'
        })

        // route for the about page
        .when('/viewb', {
            templateUrl : 'viewb.html',
            controller  : 'ViewBController'
        })

        // route for the contact page
        .when('/viewc', {
            templateUrl : 'viewc.html',
            controller  : 'ViewCController'
        })
        .otherwise({
                redirectTo: '/viewa'
        });
});

// create the controller and inject Angular's $scope
Pajsije.controller('ViewAController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Good look!';
});

Pajsije.controller('ViewBController', function($scope) {
    $scope.message = 'Look about page.';
});

Pajsije.controller('ViewCController', ['$scope','$http', '$templateCache', function($scope, $http, $templateCache) {

    $scope.myChange = function() {

    $http({method: 'GET', url: '../json-data/customers.php?idstudm=12', cache: $templateCache}).success(function (response) {$scope.names = response.records;});

};

}]);

A: Try $rootScope to set the variable part of the URL in the controller whenever the selection in the UI (HTML Page) is made (querypart).
$rootScope.variableURL = "customers.php?var=" + $scope.selected_number; Append this to the URL while sending $http request. Please inform me if I didn't understand the requirement properly.
 We already know that $rootScope is accessible across all controllers and can be used for smaller data carrying across controllers and services.

A: Use should bind selectbox to a scope model using ngModel directive and use this model in controller. Something like this:
<select ng-model="number" ng-change="myChange()">
    <option value="3">3</option>
    <option value="3">10</option>
</select>

Controller:
Pajsije.controller('ViewCController', ['$scope', '$http', '$templateCache', function ($scope, $http, $templateCache) {

    $scope.myChange = function () {
        $http({
            method: 'GET',
            url: '../json-data/customers.php?idstudm=' + $scope.number,
            cache: $templateCache
        }).success(function (response) {
            $scope.names = response.records;
        });
    };

}]);

A: I read your question. I think you have problem with separated files. I guess, because you are using AngularJS, you are using angular-route for automatic routing. So, for that reason you are probably using file like main.html which is include customers.html with routing management.
If in that file you have mechanism which will present data when routing happens, the data will not be presented in main file with ng-controller when user click on particular data to select. (not all data, only data which are in myChange function)
Best regards.


text:
Q: Volume of Solid of Revolution Find the volume of the solid of revolution of the area enclosed by:
$x=2y$ and $x= y^2 - 3$
around the line $y=4$.
I understand that this is a function in terms of y, and graphing it out I realize that the rectangular strips need to be horizontal. Therefore, because they are parallel to the axis of revolution, the shell method would need to be used. However, I am getting stuck on how to set up the integral. I attempted this by saying:
$$2\pi\int_{-1}^3 (y+1)(y^2-3-2y) \,dy$$
I got the bounds by setting the two functions equal to one another and solving, and added 1 to the radius in the integral because the line $y=4$ is one above the top limit. I know I'm wrong but not totally sure what to do.
Thanks in advance.

A: As David points out the radius should be $4-y$ because this is the distance between 4 and y. For example if y=0 then the radius would be 4-0 = 4.
There's another slight problem with the second part of your integral in that $y^2-3 -2y$ is negative. I know this because if you draw a picture, you get that the quadratic part lies to the left of the linear part, meaning that the $x=2y$ is greater than the $x=y^2-3$ so you should put $2y-(y^2-3)$ instead. Otherwise your setup is correct!

A: The $y+1$ is the radius of the cylindrical shell.  It should be $4-y$ because this is the (positive) distance from $4$ to $y$.


text:
Q: "Smart" where clause for filtering values (Oracle 10g) Imagine table t1 have 2 cols:
col1      col2
--------------
test 900     1
test 901     2
test 902     3
user 901     4
test 909     5

I want to find just one row by 2 params (name, code) where name its (test, user ..etc) and code - (901, 902, null, .. etc).
There could not be more than one row of the same (Code,name) - I Mean there Are no 2 rows that have "test 901" in Col1.
Code:
declare
 name varchar2(30);
 code varchar(10);
 col_val varchar2(30);
 col2_val numeric;
begin
 name:= 'test';
 code := '900';

  select col1, col2 into col_val, col2_val
  from t1
  where

   ( REGEXP_LIKE(col1, name||'\s+'||code) -- (3)
   or (
        not   REGEXP_LIKE(col1, name||'\s+'||code) -- (1)
        and REGEXP_LIKE(col1, name) -- (2)
      )
    )
  order by col1;
  DBMS_OUTPUT.PUT_LINE('val:'||col_val||' id:'||col2_val);
end;

1) for test values name:= 'test' code := '900' the result should be "val:test 900 id:1" - It's OK.
2) BUT for name:= 'test' code := '909' the result should be "val:test 909 id:5", but I got "val:test 900 id:1" ( the first row with Name='Test' ) - It's NOT want I want.
3) and in case name:= 'test' code := '999' the result should be "val:test 900 id:1" (there are NO 999 code, so I need just any row that have Name='test' inside).
The main question is WHY oracle Ignores (1) clause for 2) example?
Perhaps I'm doing something wrong - so it would be great if You could show my mistake!

A: You cannot combine ROWNUM and ORDER BY like this, because the ROWNUM is the row number before it gets sorted.
You need to get more verbose and write something like
 select a.* from (
     select * from table order by col1 ) a
  where rownum = 1;

Check the documentation for ROWNUM and paging.

A: This condition:
(REGEXP_LIKE(col1, :name || '\s+' || :code)
OR (NOT REGEXP_LIKE(col1, :name || '\s+' || :code) AND REGEXP_LIKE(col1, :name))

will match all rows in your example.
When searching for test 909, you are matching 'test 909' OR (NOT 'test 909' AND 'test'). This will match every row starting from 'test' (either per first condition or per second).
Since you are using rownum = 1, the first column matched in returned, in your case 'test 900'
If you want a fallback match (return 'test 909' if it exists, any 'test' otherwise), use this:
SELECT  *
FROM    (
        SELECT  *
        FROM    t1
        WHERE   REGEXP_LIKE(col1, name || '\s+' || code)
        UNION ALL
        SELECT  *
        FROM    t1
        WHERE   REGEXP_LIKE(col1, name)
        )
WHERE   rownum = 1

, or, if you don't like UNIONs:
SELECT  *
FROM    (
        SELECT  *
        FROM    t1
        WHERE   REGEXP_LIKE(col1, name)
        ORDER BY
                CASE WHEN REGEXP_LIKE(col1, name || '\s+' || code) THEN 0 ELSE 1 END
        )
WHERE   rownum = 1

The latter one, though, is less efficient, since it has to sort.

A: You would be much better off storing the parts of col1 in separate columns. In any case, here's one more thing besides what Thilo said.
Ignoring the rownum part, four rows of your table match the WHERE clause in your example. Your WHERE clause in English is "name and code both match or else they don't both match, but name matches."
This is a complicated way of saying "name matches," and there's no need for such a complicated WHERE clause if that's really what you mean.
(If \s means space, which I'm not sure, it's "name matches and there is a space after the name.") If you want to see a "both" match ahead of a name-only match, choose the first row in this "scoring" order:
ORDER BY
  CASE WHEN REGEXP_LIKE(col1, name||'\s+'||code) THEN 2
       WHEN REGEXP_LIKE(col1, name||'\s+) THEN 1
  ELSE 0 END DESC

Response to comment:
Your WHERE clause fails to express the BUT if not, ... aspect of your requirement. Your WHERE clause simply expresses If there is row with both CODE and NAME OR a row with just NAME in it, show it, and that isn't your requirement.
To express WHERE A, BUT if not A, then B, it won't work to write
WHERE <condition A> OR <condition B>

You have to write
WHERE <condition A> OR (NOT <condition A> AND <condition B>)

or do something like I did with my CASE expression.
Does that help?


text:
Q: How to verify a given string is a real URL, in PHP? I need to find the best way (in terms of performance) to find if a given string is a URL.
REGEXP won't help, as www.eeeeeeeeeeeeeee.bbbbbbbbbbbbbbbb.com is a valid url name but not in any network known to man.
I am thinking using CURL and see if I get status 200 back or just file_get_contents and analyze the result.
Is there a better way?

A: Don't fetch the whole contents - that could be enormous. Issue a HEAD request instead.
You could do some validation first, of course - remove things which are invalid as URLs, rather than just URLs which aren't currently served by anything. After that, issuing a HEAD request is about as good as it gets. Having said that, it becomes a grey area... what about a URL which returns "authorization required"? It could be a password protected directory, but if you knew the password you'd then get back a 404 because the file itself doesn't exist...

A: This article outlines how to perform a DNS request from php.  That might be the fastest option, although it would not tell you anything like if the server is online, file is found, etc.  But it would tell you that the url is registered to an IP.  It's up to you whether that would fit your definition of "valid"

A: You don't mean a URL, you mean a Domain Name

A: $host != gethostbyname($host)

for checking the host.

A: I would strongly suggest using CURL but just the headers without fetching any contents.
Here is the function, I use to verify if the given URL is valid and found.
function __checkUrl($url)
{
    //First checking with pattern whether it is proper or not
    $pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
    if (preg_match($pattern, $url))
    {
        $ch = curl_init();

        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);

        // grab URL
        $output = curl_exec($ch);
        // Get response code
        $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

        // Not found?
        if ($response_code == '404') {
            return false;
        } else {
            return $newurl;
        }
    }
    else
    {
        return false;
    }
}

With this function, I first check the URL is actually valid with Regex. After that curl that. By setting CURLOPT_FOLLOWLOCATION to true, we are taking care of 301 and similar redirects, but limit the no. of redirections to 3.
And we finally we return Effective URL after all the redirections.
Hope this helps.


text:
Q: Unity trees appear really big in built game when I play preview the trees appear like painted with the landscape brush.
When built, the trees appear big and like 2d from far. When coming closer they get the real size.
Someone knows why?
Should I tell you which kind of tree?
Other trees don't behave like this in my game.


text:
Q: Get height WebViewBridge after loading finish I used https://github.com/alinz/react-native-webview-bridge to show my html file.
I want add admod below Webview bride so I add webview bride and ads in ScrollView, when webview loaded I will get height of webview and set marginTop to ads = height of webview. But I don't know how to get height of WebviewBridge.
If you have solution or idea please help me.
Thank so much

A: you can give webView some height(say height/2) as per your interest and render the ads in remaining using scrollView.
Hope this helps


text:
Q: getting javax.mail.AuthenticationFailedException on heroku I am Using Heroku to deploy my java spring boot backend which utilizes the javamailsender. When testing locally before deployment, I was able to send emails and receive emails thru the application. But, ever since I deployed it on heroku, I have been receiving error whenever I try to send email.
Error Sending Email: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at
2020-07-17T01:00:29.110458+00:00 app[web.1]: 534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor r188sm8440648qkf.128 - gsmtp
2020-07-17T01:00:29.110462+00:00 app[web.1]:

I have seen plenty of articles/discussion forum where users encounter such problem and I tried to resolve using the solution that was given but was unsuccessful. I have the  2-Step-Verification on and turned on the less secure app but no luck. I also saw that doing App Password helped solved the issue but didn't really understand how to go about that in terms of my app on heroku. I have react frontend hosted on firebase and spring boot backend hosted on heroku. Any help would be appreciated. Thank you!

A: Nvm, I figured out what was causing this error. I guess I had to create an App Password and use that password that was created inside my application.properties.


text:
Q: Delete remote Non Empty folders with Java & SFTP I have a requirement to delete multiple non empty folders on multiple UNIX servers.
I am looking to use something like Apache FileUtils, which allows non empty LOCAL folders to be deleted.
Its just that my folders in this case are REMOTE.
Do i have to first list all the files contained in each remote folder, deleting each file found in turn?
Or...
Is there a java SFTP/SSH client that exposes the functionality of FileUtils.deleteDirectory() for remote folder removal?

A: I'm not entirely sure if it has a native recursive delete() (this is trivial to implement yourself though) but jsch (http://www.jcraft.com/jsch/) is an awesome implementation that allows for sftp access. We use it all the time.
Example code for connection:
JSch jsch = new JSch();
Properties properties = new Properties();
properties.setProperty("StrictHostKeyChecking", "no");

if (privKeyFile != null)
    jsch.addIdentity(privKeyFile, password);

Session session = jsch.getSession(username, host, port);
session.setTimeout(timeout);
session.setConfig(properties);

if (proxy != null)
    session.setProxy(proxy);

if (privKeyFile == null && password != null)
    session.setPassword(password);

session.connect();

ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();

The channel has rm() and rmdir().

A: Unfortunately, the sftp protocol does not allow to delete the non-empty directory,
and jsch has not implemented the recursive deletion of such directories.  If you don't want to implement recursive deletion by yourself, how about executing "rm -rf" on jsch's exec channel?

A: You can delete folder using JSCH java API. Below is the sample code for deleting non empty folder with java and SFTP.
@SuppressWarnings("unchecked")
private static void recursiveFolderDelete(ChannelSftp channelSftp, String path) throws SftpException {

    // List source directory structure.
    Collection<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(path);

    // Iterate objects in the list to get file/folder names.
    for (ChannelSftp.LsEntry item : fileAndFolderList) {
        if (!item.getAttrs().isDir()) {
            channelSftp.rm(path + "/" + item.getFilename()); // Remove file.
        } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { // If it is a subdir.
            try {
                // removing sub directory.
                channelSftp.rmdir(path + "/" + item.getFilename());
            } catch (Exception e) { // If subdir is not empty and error occurs.
                // Do lsFolderRemove on this subdir to enter it and clear its contents.
                recursiveFolderDelete(channelSftp, path + "/" + item.getFilename());
            }
        }
    }
    channelSftp.rmdir(path); // delete the parent directory after empty
}

For more details. Please refer the link here


text:
Q: Wrong Output Dollar Amount To Coins I have some code here that takes a double amount that serves as a dollar amount and outputs the amount of coins it contains. I have been trying to get it to execute "1.69" correctly for a long time, putting in a ridiculous amount of parenthesis to make sure it works; however, the output is never correct. Currently, as it stands below, the output is 6 Quarters, 1 dimes, 1 nickle, and 3 pennies, which is "1.68," and I cannot for the life of me figure out why. Any ideas? Thanks.
ChangeJar2(final double _amount_){

    quarters = (int) (_amount_/.25);// Computes # of quarters
    dimes = (int) ((_amount_-(quarters*(.25)))/.1);// Computes # of dimes
    nickles = (int) ((_amount_-(quarters*(.25))-(dimes*.1))/.05);// Computes # of nickles
    pennies = (int) ((_amount_-(quarters*(.25))-(dimes*(.1))-(nickles*(.05)))/.01);// Computes # of pennies

    System.out.println(quarters + " " + dimes + " " + nickles + " " + pennies);

}// End of ChangeJar(final double _amount_) Constructor


text:
Q: jQuery device orientation range converting to percentage between 0 and 100 I'm trying to control an HTML element by using the gyroscope in my smartphone. I managed to extract the gyroscope's values (Alpha, Beta and Gamma) but can't manage to translate it in such a way it's able to manipulate objects the way I'd like to.
The starting position of the device is in landscape mode, right in front of the user; just like a flatscreen television. The device will be inserted in a Google Cardboard viewer.
The attached image explains what I am trying to achieve.

*

*An objects "Left" percentage in CSS.

*Device orientation while rotating head from left to right

I can't seem to find a way to "convert" the range of the rotaion movement to a percentage value between 0 and 100%.
For example:

*

*If I look slightly left, the Alpha value is around 22/23 and the left percentage should be around 25.

*If I look slightly right, the Alpha value is around 338/337 and the left percentage should be around 75.

Could you guys help me out?
Best regards,
Peter

A: You got this a bit wrong, check for more details here: https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation

*

*The DeviceOrientationEvent.alpha value represents the motion of the device around the z axis, represented in degrees with values
  ranging from 0 to 360.

*The DeviceOrientationEvent.beta value represents the motion of the device around the x axis, represented in degrees with values
  ranging from -180 to 180. This represents a front to back motion of
  the device.

*The DeviceOrientationEvent.gamma value represents the motion of the device around the y axis, represented in degrees with values
  ranging from -90 to 90. This represents a left to right motion of the
  device.

est-west and north-south position, notice z is not represented in x y axis

*

*x - beta: Represents the axis from West to East

*y - gamma: Represents the axis from South to North

*z - alpha: Represents the axis perpendicular to the ground

Going forward with CSS props:

*

*x - beta: Represents top property

*y - gamma: Represents left property

*z - alpha: not necessary usable in a 2d css but you can use it for zoom or angle to a 2d shape, div or image.

For left property, you should use gamma device orientation, here is a nice example (masonry level gama) where left css prop in percent is used to position the level point.
try form here on mobile: https://jsfiddle.net/f7tdrb87/
percentage computation:
function precentageIn180(value)
{
    var percent =  ((value * 100) / 180).toFixed(0);
  return percent;
}

and the interval [-90, 90] transposed into [0, 180] where 0 == 0% and 180 == 100%, so then event.gamma + 90 is used all the time;

var point   = document.querySelector('.point');
var masonryLevel = document.querySelector('.masonry-level-gama');
var log = document.querySelector('.log');

var maxY = masonryLevel.clientWidth - point.clientWidth;

function precentageIn180(value)
{
 var percent =  ((value * 100) / 180).toFixed(0);
  return percent;
}

function handleOrientation(event) {
  var y = event.gamma; // In degree in the range [-90,90]
  log.innerHTML = "gamma: " + y + "\n";
  //value on gama is [-90, 90] => but we want to have between [0, 180], to be possiblle to compute 100% of 180
  y += 90;
  var percent = precentageIn180(y);
  log.innerHTML += "gamma percent: " + percent + "\n";
  point.style.left = (percent + "%");
}

window.addEventListener('deviceorientation', handleOrientation);
.masonry-level-gama {
  position: relative;
  width : 190px;
  height: 40px;
  border: 1px solid #CCC;
  border-radius: 10px;
}

.point {
  position: absolute;
  top   : 10px;
  left  : 50%;
  margin-left: -10px;
  width : 20px;
  height: 20px;
  background: blue;
  border-radius: 100%;
}


text:
Q: dylib image not found in OpenCV I have a C++ project that I configure the CMake like:
set(CMAKE_CXX_STANDARD 17)
find_package( OpenCV REQUIRED )
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(ubimet main.cpp data.cpp)
target_link_libraries(ubimet ${OpenCV_LIBS})
set_property(TARGET ubimet PROPERTY CXX_STANDARD 17)

When I include the header #include <opencv2/core/core.hpp> I get:
dyld: Library not loaded: /usr/local/opt/protobuf/lib/libprotobuf.22.dylib
      Referenced from: /usr/local/opt/opencv/lib/libopencv_dnn.4.3.dylib
      Reason: image not found
    Abort trap: 6

In that folder I have:
MacBook-Pro-de-Hector-2:lib hectoresteban$ ls
libprotobuf-lite.23.dylib   libprotobuf.23.dylib        libprotoc.23.dylib      pkgconfig
libprotobuf-lite.a      libprotobuf.a           libprotoc.a         python3.8
libprotobuf-lite.dylib      libprotobuf.dylib       libprotoc.dylib


text:
Q: Connecting points - plugin problem QGIS I have a question related to connecting points in QGIS. I am doing a project relating to transport. I have a layer of points (bus stops) and I have to connect them according to a timetable (as runs a bus line). Lines must proceed on the road (I have layer of roads combined with OpenStreetMap). I found the plugin Online Routing Mapper, but in this plugin are only two points (start and stop) and making line where each has 15 or more points is time-consuming. Can someone please me to prompt another method of how to do it? The plugin of which I mentioned would meet my needs if I could add more points.

A: There is an experimental QGIS plugin (you need to mark "Show also experimental plugins" in Plugins|Settings) named PointsToPaths that converts points to lines with verticies grouped by a text or integer field and ordered by an integer or date string field. You can try out it.

A: You can also try Points2One plugin. It converts points to lines.

A: Thanks for your advice. However, the lines must run along existing roads (marking the buses lines) and this is my main problem. Using these plug-ins I combine points with stright lines.


text:
Q: Add a second bridge to a virtual machine We have a ubuntu-12.04 host running another ubuntu-12.04 virtual machine with kvm virtualization and bridged network interface on eth4. This network allows the virtual machine access to the outside world. I want to add another bridge (br0) to the virtual machine so it can access the local network. But every time I try this, the first bridge "collapses" in some way, as in I cannot access the virtual machine via ssh or even ping it.
The following is the /etc/network/interfaces file on the host that I am trying to get to work
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

auto eth4
iface eth4 inet manual

auto br4
iface br4 inet static
     address 10.52.4.247
     netmask 255.255.255.0
     gateway 10.52.4.1
     dns-nameservers 10.27.3.2 10.25.3.2
     broadcast 10.52.4.255
     bridge_ports eth4
     bridge_stp off
     bridge_maxwait 5
     metric 0

# Local network
auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
    address 192.168.0.21
    netmask 255.255.255.0
    broadcast 192.168.0.255
    bridge_ports eth0
    bridge_stp off
    bridge_maxwait 5
    metric 0

What am I missing here? Any help greatly appreciated!


text:
Q: Why can't I add variables with 1x1 tibbles to a tibble with tibble::add_row? This is a simple example of what I am trying to do. Why can't I add a row with each variable a 1x1 tibble?
d <- tibble(x = 2, y = 3)
x1 <- tibble(1)
y1 <- tibble(7)

d2 <- d %>%
  tibble::add_row(
    x = x1,
    y = y1
  )

I know the following works but it is not tidy and it just seems like there should be a better way.
d <- tibble(x = 2, y = 3)
x1 <- tibble(1)
y1 <- tibble(7)

d2 <- d %>%
  tibble::add_row(
    x = as.numeric(x1),
    y = as.numeric(y1)
  )

Thanks in advance awesome R people (:

A: Upgrading comment to an answer:
You're trying to insert a whole dataset ('tibble' in this instance) into a single cell in your first attempt. You need to select the single column out of the dataset to add as rows.
add_row(d, x = x1[[1]], y = y1[[1]])

Running as.numeric(x1) also converts x1 to a vector in a round-about way, which as you've found, will also work.
You could also go full dplyr and do:
add_row(d, x = pull(x1,1), y = pull(y1,1))

...if you wanted to avoid using the [[ brackets.


text:
Q: What should 'git lfs lock' on a file not tracked by LFS do? What should be the behavior of 'git lfs lock' if its called on a file not tracked by LFS? I did not see this addressed in the documentation
In my experiments with the command line, it allows me to lock a file that isn't tracked by LFS. It subsequently shows that lock when I do a 'git lfs locks'. However, if I do a 'git lfs ls-files' it does not show that file as being tracked.
Is that right?
git-lfs/2.13.3 (GitHub; windows amd64; go 1.16.2; git a5e6585)

A: It is permissible to lock or unlock a file that is not actually tracked.  This can be useful because the file may exist in a different branch, or may have existed in a branch, but been deleted.  Therefore, lock operations should generally succeed so that locks can work across different branches with different files.
git lfs ls-files shows files that are tracked by Git LFS.  If the files are not tracked in the current branch, they won't be shown by Git LFS, even if they may be locked on the server.


text:
Q: a 3D modeling software runs slowly but my pc is fast: should I format or is it a hardware incompatibility? I have Windows 10 pro x64 on a high-performance assembled portable workingstation with the features below->

Processor : Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz
Memory : 8088MB(1600)
Mother Board : P170EM
Windows Version : Microsoft Windows 10 Pro
Installation Date : 2016-11-14
Monitor : Default Monitor
Video Adapter : NVIDIA GeForce GTX 675M
Mouse : PS/2 Compatible Mouse
Keyboard : Standard PS/2 Keyboard
Disk Drive : INTEL SSDSC2CW060A(55GB,IDE)
DVD/CD-ROM Drive : Slimtype DVD A  DS8A8SH
a second internal drive (har disk) installed, no raid

I have Windows installed on the 60 GB SSD.
I usually install programs in the second internal drive (hard disk).

Now I'm running 3d modelling softwares but I have troubles with Solidworks 2016 x64. I run 3DsMAX 2017 x64 in the same pc and it works fine, whereas Solidworks is very very slow; I tried installing Solidworks both in the SSD and in the hard disk without seeing any difference.
It runs faster on other portable computers with weaker video cards, see the following features->

ON ALIENWARE ------>

model -> Alienware 13 R2
Video cards ->  NVIDIA GEFORCE gtx 960 m  and Intel hd graphics 520
intel core i7 6500U CPU 2.5 GHz@ 2.60 ghz
8 G ram
bios 1.2.0
Win 8.1 x64

The graphic card installed on Alienware is weaker than mine, according to the report below ->

ON ASUS ZEN ------>

model -> asus zenbook ux301
video card -> intel iris graphics 5100 (it seems it only has this
graphics processor, I checked both in the device manager panel and with
dxdiag tool, see also the screen below)
CPU -> intel quad i7
win 10
two SSD , RAID

As you can see below, the videocard is really weaker than mine ->

Moreover SOLIDWORKS runs faster in a Mac laptop with a less powerful CPU and even on others which don't have certified video cards (according to what my teacher said).
I set my NVIDIA control panel and told it to use the high performance NVIDIA processor while running Solidworks->

More specifically the settings for the program are the following ->

I disabled the applications which might create compatibility issues according to my experience (antivirus, antiramsomware, antimalwares, sandboxie).
I tried installing (and uninstalled) the software both in the SSD and in the hard disk (they are both internal) but I didn't solve the problem.
In other terms, there are no apparent reasons why my pc is so slow when I run Solidworks because it's a powerful workingstation; I tested the software on other -less powerful- laptops and it run faster. Solidworks is supposed to be fully compatible with Windows 10 AFAIK. I wonder if I should format my ssd and do a clean installation of Windows; but it's also true that my operating system is fast except than while running Solidworks.
I also use other heavy programs (e.g. Photoshop CS6 x64, 3DS Max...) and they are ok.
In the screens below you can see how the software acts in my system ->

and these are the running tasks ->

My VGA benchmark below (see also http://www.videocardbenchmark.net/gpu.php?gpu=GeForce+GTX+675M )  ->

I tested it with a benchmark tool (GPU burner) and I got the following ->

Graphic card driver are up-to-date (I checked with devID, downloaded from here-> http://devid.info/ : no mention of NVIDIA drivers in the report).
Anyhow I updatet all the drivers which DevID detected as out-of-date, restarted and loaded Solidworks again but nothing changed.
Might it be possible that a software runs slowly because the operative system needs to be reinstalled, even when it seems to be completely ok while running all the other programs? Or might it depend on hardware incompatibility?
p.s. I recently asked my teacher if the VGA might be the problem and he said that Solidworks runs on the graphic processor, so the video card doesn't matter: it sounds quite odd, may it be possible?

A: I solved the problem by reinstalling Windows but I didn't choose the "format" option.
I reinstalled Windows 10 x64 from the same ISO on usb stick on the same partition (C:) and by using the same license.
In the installation menu I just selected which partition to use to install Windows, I didn't chose the "format" option, so I didn't format the partition properly but just let Windows installing itself and doing the job.
Once I had Windows again I installed Solidowrks and Bitdefender and launched Solidworks: it works fast now, so I may exclude any incompatibility with the Antivirus software installed.
Then I re-installed all the other programs and no one created incompatibility issues with Solidowrks so far, the program is keeping working very well.
I also checked and learnt that this 3Ds modelling software runs faster on weaker PCs, no need for a very powerful graphic card with x GB dedicated (except than when doing rendering, which may require higher hardware performances and in that case using a high performance Nvidia Quadro makes the difference).
So it runs very good even on a old-generation graphic card for gaming and slowness only depended on the operative system.


text:
Q: Fraunhofer Diffraction -- possibly shifting of fft2 issue I am trying to re-purpose a Matlab code re-written in python for the diffraction on a circular aperture shifted with respect to the center of the image. I have looked at earlier posts and did not find a similar one. I am also looking at Computational Fourier Optics as a reference. I expect to get a maximum dislocated from the center in the same direction as the displacement of the initial mask. However, I get the diffraction image that is in the center no matter what the location of the circular aperture is. Is it me needing to go and read undergrad Phys or something is wrong with the code? Thanks in advance! The code is below.
from numba import jit
import scipy
import numpy as np
import time
import matplotlib
import matplotlib.pyplot as plt

import matplotlib.colors as colors
import math
from math import sqrt

padding = 0

complex_type = np.complex128
float_type = np.float64

lambda_0 = 0.5e-6
f = 10e-2
(4*lambda_0*f**3/np.pi)**(1/4)

def propFF(u1,L1,lambda_0,z):
    # Fraunhofer Propagation kernel

    u1 = u1.astype(complex_type)
    (M,N)=np.shape(u1)
    L1 = float_type(L1)
    lambda_0 = float_type(lambda_0)
    z = float_type(z)
    M = float_type(M)
    N = float_type(N)
    dx1 = float_type(L1/M)
    k = float_type(2*np.pi/lambda_0)
    L2 = float_type(lambda_0*z/dx1)

    dx2 = float_type(lambda_0*z/L1)
    x2 = np.linspace(-L1/float_type(2),L1/float_type(2),int(M+2 * padding))
    (X2,Y2) = np.meshgrid(x2,x2)
    X2 = X2.astype(float_type)
    Y2 = Y2.astype(float_type)

    c = float_type(1)/(complex_type(1j)*lambda_0*z)\
        *np.exp(complex_type(1j)*k/(float_type(2)*z)*(X2**2+Y2**2))
    u2=c*np.fft.ifftshift(np.fft.fft2(np.fft.fftshift(u1),s=[int(M)+2*padding, int(M)+2*padding]))*(dx1**2)
    return u2

def rect(x, y, x_0, x_1, y_0, y_1):
    X = np.zeros(np.shape(x)).astype(float)
    X[np.abs(x-x_0) < 0.5] = 1.0
    X[np.abs(x-x_1) == 0.5] = 0.5

    Y = np.zeros(np.shape(y)).astype(float)
    Y[np.abs(y-y_0) < 0.5] = 1.0
    Y[np.abs(y-y_1) == 0.5] = 0.5
    return(X * Y)

def circle(x, y, x_0, x_1, y_0, y_1):
    R = np.zeros(np.shape(x)).astype(float)
    R[(np.abs(x-x_0)**2+np.abs(y-y_0)**2)**.5 < 0.5] = 1.0
    R[(np.abs(x-x_1)**2+np.abs(y-y_1)**2)**.5 == 0.5] = 0.5

    return(R)

L1 = float(0.5)
M=float(160)
lambda_0=0.5e-6
k=2*np.pi/lambda_0
w=0.051
z=2000

dx1=L1/M
x1=np.linspace(-L1/2,L1/2,np.int(L1/dx1))
y1=x1

(X1,Y1)=np.meshgrid(x1,y1)

u1 = circle(X1/(2*w), Y1/(2*w), 1., 0, 0, 0)

plt.figure(figsize=(4.5,4))
plt.pcolormesh(x1,y1,np.abs(u1**2))

u2_tf = propFF(u1,L1,lambda_0,z)

I2_tf = np.real(u2_tf*np.conj(u2_tf))

x1 = np.linspace(-L1/2, L1/2,np.int(M + padding * 2))
y1 = x1

plt.figure(figsize=(8,7))
plt.pcolormesh(x1,y1,I2_tf**(1.0/3.0))
plt.colorbar()
plt.title('Fresnel Transfer Function')
plt.show()


text:
Q: Android build failed when using react-native-googlesignin I am using react native googlesignin module.
When I run n android it throws error like this:

Here is my build.gradle file:
    dependencies {
compile project(':react-native-fbsdk')
compile project(':react-native-android-permissions')
    compile project(':react-native-device-info')
    compile project(':react-native-push-notification')

    compile project(':react-native-barcodescanner')
    compile project(':@remobile/react-native-splashscreen')
    compile project(':react-native-camera')
    compile project(':react-native-image-picker')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(":react-native-google-signin")

    compile 'com.google.android.gms:play-services-auth:9.2.1' // should be at least 9.0.0
      compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}

I have tried the following also:
compile(project(":react-native-google-signin")){
        exclude group: "com.google.android.gms" // very important
    }
    compile 'com.google.android.gms:play-services-auth:9.2.1' // should be at least 9.0.0

Can anyone tell me how to resolve this issue.

A: npm link will search with regex, the current line is
compile(project(":react-native-google-signin")){ so we need to change it to
compile project(":react-native-google-signin")
{
        exclude group: "com.google.android.gms" // very important
}

and in this way, when npm link will detect the dependency and won't be duplicated


text:
Q: Using Instruments to Know What Activity Occurs at a Given Time As the Instruments trace below shows, I have some regular plunges in my Physical Free Memory. At the same time the percent user load rises. Allocations remains steady, but the tabular listings show some operations have a high peak to average ratio.

I don't understand enough about Instruments to identify what activity is happening at the time the free memory plunges. I can look at Time Profiler in the detail pane, but this appears to be cumulative, from the beginning. I would like to see what's happening over a the narrow window of time where memory use goes up.
Also, I don't understand why the tack for the Time Profiler shows no activity during these times when memory use goes up, but the Activity Monitor shows high activity.
Would someone provide some guidance on how to interpret this and how to get more out of it so I can understand the memory using problem? Thanks.

A: *

*Click the button below the tracks ("Statistics"?) and choose "Objects List".

*Order the table by Timestamp.

*Zoom in on the track for the region you want to analyze.

*Click in the track/graph -- Instruments will jump to that time.

You may also benefit by using Heapshot Analysis.


text:
Q: C2DM inapp registration: unable to start service Intent OK, I really don't know what I'm lacking here. I try to get C2DM working for our application and especially handling the Broadcasts make me struggle.
We have an appwide BroadcastReceiver:
public final class AppBroadcastReceiver extends BroadcastReceiver {

    //get an instance if not already present
    public static AppBroadcastReceiver getInstance(final IntentFilter filter) {
        if (instance == null) {
            instance = new GlobalBroadcastReceiver();
        }
        if (filter != null) {
            filter.addAction("com.google.android.c2dm.intent.REGISTRATION";
            filter.addAction("com.google.android.c2dm.intent.RECEIVE");
            filter.addCategory("my.package.name");
        }
        return instance;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        final String broadcastAction = intent.getAction();
        Log.d(logTag, String.format("GlobalBroadcastReceiver::onReceive for action = %s", broadcastAction));

        if ("com.google.android.c2dm.intent.REGISTRATION".equals(broadcastAction)) {
            for (final AppBroadcastListener l : listeners) {
                l.c2dmRegistration(intent);
            }
        } else if ("com.google.android.c2dm.intent.RECEIVE".equals(broadcastAction)) {
            for (final ApplBroadcastListener l : listeners) {
                l.c2dmReceive(intent);
            }
        }//else
    }//onReceive
}

AppBroadcastListener is an interface all our activities are implementing to assure the appropriate method are at least present. In their onResume(), onStop() methods the activities registering and unregistered themselves at the Receiver, respectively.
For testing purposes I have a Debug Activity proving me the following two methods:
public void sendC2DM(View v){
    Intent intent= new Intent();
    intent.setAction(com.google.android.c2dm.intent.RECEIVE);
    intent.putExtra("message","Bender: \"kiss my shiny metal ass!\"");
    intent.addCategory(getPackageName() );

    sendBroadcast(intent);
}

public void registerC2DM(View v){
    Intent registrationIntent = new Intent(com.google.android.c2dm.intent.REGISTRATION);
    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
    registrationIntent.putExtra("sender", ourSenderIdregistered@googlemail.com);
    startService(registrationIntent);
}

And in the android.manifest I've added the follwoing lines in the <application>-tag:
    <receiver
        android:name=".AppBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >

        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="my.package.name" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="my.package.name" />
        </intent-filter>
    </receiver>

So every activity we want to receive broadcast is registering itself at the BroadcastReceiver on it's onResume() and when something is happening the BroadcastReceiver will catch and call the implemented methods. E.g. ,logging the message or displaying a Toast.
However when I send a "C2DM message" I see this structure is working for self crafted broadcast. (Bender's message is popping up in a Toast) but registerC2DM().startService(registrationIntent); just logs:

Unable to start service Intent {
  act=com.google.android.c2dm.intent.REGISTRATION (has extras) }: not
  found

I've no clue what I'm missing here. General advice seems to be: check your android.manifest (done) or: log in with the registered gmail account.
Not sure bout this. I'm logged in with my gmail account yeah but not with ourSenderIdregistered@googlemail.com which we put in the intent when registering. I also strongly believe this can not be the solution. (Telling all our customers to log in with this account... ehm no?!).
So I guess it's something else but I just can't find it :C

A: OK, this is really mean to spot:
If you want to register for c2dm you use
com.google.android.c2dm.intent.REGISTER

but to catch the answer to this message you have to set up you're broadcast receiver to listen to
com.google.android.c2dm.intent.REGISTRATION

Subtle? Yes, here once again the error and the corrected version:
//false
public void registerC2DM(View v){
    Intent registrationIntent = new Intent(com.google.android.c2dm.intent.REGISTRATION);
    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
    registrationIntent.putExtra("sender", ourSenderIdregistered@googlemail.com);
    startService(registrationIntent);
}

//true
public void registerC2DM(View v){
    Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
registrationIntent.putExtra("sender", ourSenderIdregistered@googlemail.com);
    startService(registrationIntent);
}

Smashed 3 keyboards before realising this... :)


text:
Q: Extract object from image in Matlab I'm currently learning image processing with Matlab. What I'm trying to do is to find in the following image all the letter a's and remove all the rest.

First of all I convert the image to a binary one. Then I try to get rid of the noise by using a median filter. There are some gaps in some of tha a's borders, which I fill by opening the image.
But then I get stuck, I found some things on the internet (which I do not completely understand) with which I am able to select the gaps from all the a's.
What should I do next?
My code is as follows:
text = imread('http://i.stack.imgur.com/N4nCm.png');
text = mat2gray(text);

% find threshold and chance to binary image
border = graythresh(text);
textbw = im2bw(text, border);
imshow(textbw);

% remove noise with median filter
textfilt = medfilt2(textbw);

% remove small holes in the border of the a
se = strel('disk', 4);
texter = imopen(textfilt, se);

% find holes
s = regionprops(texter, 'BoundingBox');
bb = round(reshape([s.BoundingBox], 4, []).');

% show original image with holes
imshow(textbw);

for idx = 1 : numel(s)
    rectangle('Position', bb(idx,:), 'edgecolor', 'red');
end

A: That is a nice problem to tackle. Here is an approach you could use, but I admit that it is by no means perfect and might not be that robust. Hopefully it will give you ideas...
What I did is basically filter the image with a median filter (as you did) and removed small elements using bwareaopen. Then I called regionprops to get a bunch of properties, among which the most important are the area and eccentricity. The idea was that all letters "a" should have a somewhat similar eccentricity, therefore once we know the eccentricity of one letter we can find the other letters that have about the same. You could probably make the code more robust using additional properties that make the letters stand out from the rest; maybe the ratio MajorAxisLength/MinorAxisLength for instance. I'll leave that part up to you :)
So the easiest way to pick a letter in this case was to select the object with the largest area, which is the big a at the center of your image. Once we have its eccentricity, we can apply some threshold and select only those objects found using regionprops that have an eccentricity about similar. The median filter and call to bwareaopen applied earlier are important here because the kind of noise in the 4 boxes on the right can complicate things if they are not removed, as a few of the random spots are likely to have an eccentricity similar to our dear letter "a".
That being said, here is the commented code. Note that I changed the name of your text variable to textIm since text is a Matlab function.
clc
clear
close all

textIm = imread('http://i.stack.imgur.com/N4nCm.png');

%// find threshold and change to binary image
border = graythresh(textIm);

%// =========== NEW \\ ===========
%// NOTICE the use of ~im2bw(...)
textbw = ~im2bw(textIm, border);

%// remove noise with median filter

%// =========== NEW \\ ===========
textfilt = medfilt2(textbw,[7 7]);
textfilt = bwareaopen(textfilt,8);

%// =========== NEW \\ ===========
%// Use an absurdely large line structuring element oriented at 25 degrees
%// to make the a's stand out

se = strel('line', 20 ,25);
textfilt = imclose(textfilt, se);

%// Get a couple properties. Note the "Eccentricity"
S = regionprops(textfilt, 'Area','Eccentricity','Centroid','BoundingBox');

All_areas = vertcat(S.Area);

%// Find the largest element (i.e. the big a). We will use it to get its
%// eccentricity and fetch other a's.

[MaxArea, MaxAreaIdx] = (max(All_areas(:)));

%// Get eccentricity of largest letter.
RefEcc = S(MaxAreaIdx).Eccentricity

Here the eccentricity of the large "a" is 0.6654. An eccentricity of 0 means a circle and an eccentricity of 1 means a line.
%// Just concatenate everything. Easier to work with.
All_Ecc = vertcat(S.Eccentricity);
All_Centroids = vertcat(S.Centroid);
All_BB = vertcat(S.BoundingBox)

%// Find elements that have the approximate eccentricity of the large a
%// found earlier. You can be more/less stringent and add more conditions here.

PotA = find(All_Ecc > RefEcc*.8 & All_Ecc < RefEcc*1.2)

%// Display output with centroids and bounding boxes.
imshow(textIm)
hold on

scatter(All_Centroids(PotA,1),All_Centroids(PotA,2),60,'r','filled');

for k = 1:numel(PotA)

rectangle('Position',All_BB(PotA(k),:),'EdgeColor','y','LineWidth',2)
end

And output, with centroids as red dots and bounding boxes as yellow rectangles:

That was fun! Hope I could help somehow. You might need to adapt the code for other letters or if you have other circle-ish objects in your image, but I guess that's a start.


text:
Q: Diagnosing IIS Shutdowns Symptoms:

*

*I attach a debugger, I wait a little while, it automatically detaches

*I watch the event log during normal operation - after a single request comes in, it waits a little bit, the shuts down

Disagnosing. I've followed the following steps for logging shutdowns in IIS:

*

*http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx

*http://blogs.msdn.com/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx
I know these are working because...
What I see in the Event Logs when I change the web.config:
The description for Event ID 0 from source ASP.NET 2.0.50727.0 cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event:

_shutdownMessage=IIS configuration change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
HostingEnvironment caused shutdown

_shutdownStack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdown()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

the message resource is present but the message is not found in the string/message table
But it doesn't help because the mysetery error doesn't tell me anything.  I see the same thing as from before I added this extra logging:
The description for Event ID 0 from source ASP.NET 2.0.50727.0 cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event:

_shutdownMessage=HostingEnvironment initiated shutdown
HostingEnvironment caused shutdown

_shutdownStack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdown()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

the message resource is present but the message is not found in the string/message table
Anyone have any ideas for more debugging?

A: Well, it turns out that IIS somehow got set to recycle the pool every minute - certainly not the usual configuration.  (I think it was a prank.)  I'm leaving this up so anyone who googles that error message might find something that helps them.

A: Here's a good reference:
http://blogs.iis.net/mailant/archive/2008/03/07/iis7-diagnostics-for-developers-talk-at-mix08.aspx
You can also use DebugDiag:
http://www.microsoft.com/downloads/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&DisplayLang=en
DebugDiag is the tool MS Support would have you use to generate a report for them to inspect.


text:
Q: EXCEL - SUM all tiles that do not contain a specific character My cell network operator has sent me an excel spreadsheet with all my data usage and phone calls for the month.
I would like to calculate the data usage, but the problem is that the phone call durations are in the same column and i would like to exclude them.
The call durations are seperated by ":" (HH:MM:SS) and the data usage has no seperators. I would like to do a "=SUMIF" that excludes any column that contains ":"
12159
6
5
5
1
9
5
00:00:45
00:00:06
00:00:25
00:00:03
4783
00:00:38
00:00:03
66678
1
8
3
00:00:29
00:00:01
00:00:00
00:00:01
00:00:57
147716
5
93
1

I have tried the following with no success

A: Use this as time is a decimal value of less than 1:
=SUMIF(F:F,">=1")

This method does assume that your calls are not longer than 24 hours.

A: You could use
=SUMIF(F1:F10;">1";F1:F11)
If you haven't made a call with a duration of more than 24 hours, it will work :)