text:
Q: JSON schema : "allof" with "additionalProperties" Suppose we have schema following schema (from tutorial here):
{
  "$schema": "http://json-schema.org/draft-04/schema#",

  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": {
      "allOf": [
        { "$ref": "#/definitions/address" },
        { "properties":
          { "type": { "enum": [ "residential", "business" ] } },
          "required": ["type"]
        }
      ]
    }

  }
}

And here is valid instance:
{
      "shipping_address": {
        "street_address": "1600 Pennsylvania Avenue NW",
        "city": "Washington",
        "state": "DC",
        "type": "business"
      }
}

I need to ensure that any additional fields for shipping_address will be invalid. I know for this purpose exists additionalProperties which should be set to "false". But when I'm setting "additionalProprties":false as in the following:
"shipping_address": {
          "allOf": [
            { "$ref": "#/definitions/address" },
            { "properties":
              { "type": { "enum": [ "residential", "business" ] } },
              "required": ["type"]
            }
          ],
          "additionalProperties":false
        }

I get a validation error (checked here):
[ {
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/shipping_address"
  },
  "instance" : {
    "pointer" : "/shipping_address"
  },
  "domain" : "validation",
  "keyword" : "additionalProperties",
  "message" : "additional properties are not allowed",
  "unwanted" : [ "city", "state", "street_address", "type" ]
} ]

The question is: how should I to limit fields for the shipping_address part only?  Thanks in advance.

A: Here's a slightly simplified version of Yves-M's Solution:
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        }
      },
      "required": [
        "street_address",
        "city",
        "state"
      ]
    }
  },
  "type": "object",
  "properties": {
    "billing_address": {
      "$ref": "#/definitions/address"
    },
    "shipping_address": {
      "allOf": [
        {
          "$ref": "#/definitions/address"
        }
      ],
      "properties": {
        "type": {
          "enum": [
            "residential",
            "business"
          ]
        },
        "street_address": {},
        "city": {},
        "state": {}
      },
      "required": [
        "type"
      ],
      "additionalProperties": false
    }
  }
}

This preserves the validation of required properties in the base address schema, and just adds the required type property in the shipping_address.
It's unfortunate that additionalProperties only takes the immediate, sibling-level properties into account. Maybe there is a reason for this. But this is why we need to repeat the inherited properties.
Here, we're repeating the inherited properties in simplified form, using empty object syntax. This means that properties with these names would be valid no matter what kind of value they contained. But we can rely on the allOf keyword to enforce the type constraints (and any other constraints) declared in the base address schema.

A: Don't set additionalProperties=false at definition level
And everything will be fine:
{
    "definitions": {
        "address": {
            "type": "object",
            "properties": {
                "street_address": { "type": "string" },
                "city":           { "type": "string" },
                "state":          { "type": "string" }
            }
        }
    },

    "type": "object",
    "properties": {

        "billing_address": {
            "allOf": [
                { "$ref": "#/definitions/address" }
            ],
            "properties": {
                "street_address": {},
                "city": {},
                "state": {}
            },
            "additionalProperties": false
            "required": ["street_address", "city", "state"]
        },

        "shipping_address": {
            "allOf": [
                { "$ref": "#/definitions/address" },
                {
                    "properties": {
                        "type": {
                            "enum": ["residential","business"]
                        }
                    }
                }
            ],
            "properties": {
                "street_address": {},
                "city": {},
                "state": {},
                "type": {}
            },
            "additionalProperties": false
            "required": ["street_address","city","state","type"]
        }

    }
}

Each of your billing_address and shipping_address should specify their own required properties.
Your definition should not have "additionalProperties": false if you want to combine his properties with other ones.

A: additionalProperties applies to all properties that are not accounted-for by properties or patternProperties in the immediate schema.
This means that when you have:
    {
      "allOf": [
        { "$ref": "#/definitions/address" },
        { "properties":
          { "type": { "enum": [ "residential", "business" ] } },
          "required": ["type"]
        }
      ],
      "additionalProperties":false
    }

additionalProperties here applies to all properties, because there is no sibling-level properties entry - the one inside allOf does not count.
One thing you could do is to move the properties definition one level up, and provide stub entries for properties you are importing:
    {
      "allOf": [{"$ref": "#/definitions/address"}],
      "properties": {
        "type": {"enum": ["residential", "business"]},
        "addressProp1": {},
        "addressProp2": {},
        ...
      },
      "required": ["type"],
      "additionalProperties":false
    }

This means that additionalProperties will not apply to the properties you want.

A: [author of the draft v4 validation spec here]
You have stumbled upon the most common problem in JSON Schema, that is, its fundamental inability to do inheritance as users expect; but at the same time it is one of its core features.
When you do:
"allOf": [ { "schema1": "here" }, { "schema2": "here" } ]

schema1 and schema2 have no knowledge of one another; they are evaluated in their own context.
In your scenario, which many, many people encounter, you expect that properties defined in schema1 will be known to schema2; but this is not the case and will never be.
This problem is why I have made these two proposals for draft v5:

*

*strictProperties,

*merge.

Your schema for shipping_address would then be:
{
    "merge": {
        "source": { "$ref": "#/definitions/address" },
        "with": {
            "properties": {
                "type": { "enum": [ "residential", "business" ] }
            }
        }
    }
}

along with defining strictProperties to true in address.

Incidentally, I am also the author of the website you are referring to.
Now, let me backtrack to draft v3. Draft v3 did define extends, and its value was either of a schema or an array of schemas. By the definition of this keyword, it meant that the instance had to be valid against the current schema and all schemas specified in extends; basically, draft v4's allOf is draft v3's extends.
Consider this (draft v3):
{
    "extends": { "type": "null" },
    "type": "string"
}

And now, that:
{
    "allOf": [ { "type": "string" }, { "type": "null" } ]
}

They are the same. Or maybe that?
{
    "anyOf": [ { "type": "string" }, { "type": "null" } ]
}

Or that?
{
    "oneOf": [ { "type": "string" }, { "type": "null" } ]
}

All in all, this means that extends in draft v3 never really did what people expected it to do. With draft v4, *Of keywords are clearly defined.
But the problem you have is the most commonly encountered problem, by far. Hence my proposals which would quench this source of misunderstanding once and for all!

A: Since no one has posted a valid answer for spec 2019-09 and upwards and I almost missed Andreas H.'s comment;
{
  "$schema": "http://json-schema.org/2019-09/schema#",

  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
      // additionalProperties: false    // <-- Remove completely if present
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": {
      "unevaluatedProperties": false,   // <-- Add to same level as allOf as false
      "allOf": [
        { "$ref": "#/definitions/address" },
        { "properties":
          { "type": { "enum": [ "residential", "business" ] } },
          "required": ["type"]
        }
      ]
    }
  }
}

A pretty clear and succinct explanation can be found by the author here;


text:
Q: java.io.FileNotFoundException: data.properties (The device is not ready) getting the below error while exporting to PDF file:-

 java.io.FileNotFoundException: D:\Workspace\PricingTool\data.properties (The device is not ready)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at export.ExportToPdf$PageNumbersWatermark.onOpenDocument(ExportToPdf.java:1451)
        at com.lowagie.text.pdf.PdfDocument.initPage(Unknown Source)
        at com.lowagie.text.pdf.PdfDocument.open(Unknown Source)
        at com.lowagie.text.Document.open(Unknown Source)
        at export.ExportToPdf.CreatePDF(ExportToPdf.java:189)
        at export.ExportToPdf.doGet(ExportToPdf.java:130)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Here is my code:
public void CreatePDF(Document document, PdfWriter writer,
            HttpServletRequest request) throws DocumentException {
        otherexpids = new ArrayList();
        int proj_id = Integer.parseInt(request.getParameter("proj_id"));
        int ver_id = Integer.parseInt(request.getParameter("ver_id"));
        document.addAuthor("Infogain Corporation");
        document.addTitle("Online Pricing");
        writer.setPageEvent(new PageNumbersWatermark());
        writer.setEncryption(null, "pc123!".getBytes(),
                PdfWriter.AllowPrinting, PdfWriter.STANDARD_ENCRYPTION_128);
        document.open();
        Paragraph ph = new Paragraph("", header);
        ph.setAlignment("center");
        document.add(ph);

I want to export some records to a pdf file but while debugging i am getting error at document.open()
please help me on this. Thanks in advance

A: If you configured the path in your configuration file then check the location. In my case, I changed my drive from E to D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Samba share Windows 10 CentOS 8 I am a new linux user and i am trying to set up my centOS computer to be able to share files with my windows computer and i just cannot get it to work.
The idea would be that i download something from the internet using the windows pc and the download location would be somwhere on the centOS pc.
The problem i encounter is that i just cannot connect to the centOS pc i try writting the ip address and windows just says"Windows cannot access \\192.168.0.110 "This is the error windows gives
This is my smb.conf.
# See smb.conf.example for a more detailed config file or
# read the smb.conf manpage.
# Run 'testparm' to verify the config is correct after
# you modified it.

[global]
        workgroup = WORKGROUP
        server string = Samba Server %v
        netbios name = RHEL
        security = user
        dns proxy = no
        passdb backend = tdbsam
        hosts allow = 192.168.0.0/24
        printing = cups
        printcap name = cups
        load printers = yes
        cups options = raw
        wins support = yes
        local master = yes
        preferred master = yes
        map to guest = bad user
        client min protocol = SMB 3
[homes]
        comment = Home Directories
        valid users = %S, %D%w%S
        browseable = No
        read only = No
        inherit acls = Yes

[printers]
        comment = All Printers
        path = /var/tmp
        printable = Yes
        create mask = 0600
        browseable = No

[print$]
        comment = Printer Drivers
        path = /var/lib/samba/drivers
        write list = @printadmin root
        force group = @printadmin
        create mask = 0664
        directory mask = 0775
[Anonymus]
        comment = Anonymus File Share Server
        path = /disk1/samba/plex/
        browsable = yes
        writable = yes
        guest ok = yes
        read only = no
        force user = nobody

`
[root@192-168-0-110 ~]#  /usr/sbin/sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   enforcing
Mode from config file:          enforcing
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Memory protection checking:     actual (secure)
Max kernel policy version:      31

`
[root@192-168-0-110 ~]# systemctl status firewalld.service
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2020-03-24 09:54:50 EET; 3 days ago
     Docs: man:firewalld(1)
 Main PID: 1013 (firewalld)
    Tasks: 3 (limit: 17928)
   Memory: 29.3M
   CGroup: /system.slice/firewalld.service
           └─1013 /usr/libexec/platform-python -s /usr/sbin/firewalld --nofork --nopid

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

My windows computer is on WORKGROUP.
I turned on the feature smb 1.0.
I activated the smb service in the CentOS firewall.
The computers are on the same network .
I have turned on network discovery and file and printer sharing also public folder sharing is on using 128 encryption and password protected sharing is off.

A: What about your centos8 side firewall ?
systemctl status firewalld.service

What about your centos8 side SElinux ?
/usr/sbin/sestatus


text:
Q: Describing automorphisms of a punctured unit disc Here is my attempt :

Let $f \in \text {Aut}(D(0,1) \setminus \{0\})$.
Since $f$ is bounded on a deleted neighborhood of $0$, function $f$
  has a removable singularity at $0$. Since $f$ is bijective, we must
  have $f(0)=0.$
By Schwarz's lemma we get $|f(z)| \le |z|.$
But $f^{-1} \in \text {Aut}(D(0,1) \setminus \{0\}) \; \text {and}
 f^{-1}(0)=0 \Rightarrow |z|=|f^{-1}(f(z))| \le |f(z)|.$
Thus $|f(z)|=|z| \Rightarrow f(z)=\lambda z \;$ for some $\lambda \in
 \Bbb C$ and $|\lambda|=1$.
We infer that all the elements of $\text {Aut}(D(0,1) \setminus \{0\})$ are
  rotations.

Are my arguments correct?

A: The important missing detail is where you say "since $f$ is bijective, $f(0)=0$".
To explain what the problem is we need to  be a little more careful with the notation (in fact you made the error because you're actually using the notation "$f$" for two different things. Not to say your notation was bad, it's fairly standard, but that's where the error came from).
Say $D$ is the disk and $D'$ is the punctured disk. You're given $f:D'\to D'$. Now $f$ has a removable singularity at the origin, great. So $f$ extends to a function $F:D\to\Bbb C$.
Now when you say "since $f$ is a bijection..." you're actually referring to the new function $F$. You're given that $f:D'\to D'$ is a bijection - how do you know that $F$ is a bijection?
For that matter, how do you even know that $F(0)\in D$?
Hints: A certain very basic result that you use all the time shows that $|F(0)|<1$. So you have $F:D\to D$. Now you can use the Open Mapping Theorem to show that since $f$ is a bijection we must have $F(0)=0$.

A: In my opinion one argument is missing: we have $|f(z)|=|z|$ for all $z \in D(0,1)$. Why we get $f(z)=\lambda z \;$ for some $ \lambda$ with $|\lambda|=1$ ?
Define $g : D(0,1) \to \mathbb C$ by $g(z)=f(z)/z$ if $z \ne 0$ and $g(0)=f'(0)$. Then $g$ is holomorphic and $|g(z)|=1$ for all $z \in D(0,1)$.
Hence $g(D(0,1))$ is not open, thus $g$ is constant.
Can you proceed ?


text:
Q: Android: Two Dependencies, Each One Depends on Same Component, Triggers DexArchiveMergerException I have a situation in which my project consists of two different libraries that apparently has a dependency on the same component:
gradle.build of the client app:
android {
...
}

dependencies {
...
implementation <dependency # 1>
implementation <dependency # 2>
...
}

The error that I am seeing:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

The Android issue in question:
Program type already present: <package name>.<Component>

We've recently made gradle changes to one of these dependencies in hopes of eliminating this error:
build.gradle - dependency # 1
android {
...
}

dependencies {
...
api <dependency # 1>
api <dependency # 2>
...
}

But this change apparently has no affect on the outcome.
We have multidex enabled. This property also has no affect on the outcome.
I even went as far as adding this block of code to the gradle file of my client app:
configurations {
    runtime.exclude group: "<package name>", module: "<problem module>"
}

per examples provided here: https://docs.gradle.org/current/userguide/dependency_types.html
I'm beginning to run low on options.
Is it possible to make a gradle configuration change to one, multiple, or all of the gradle files in order to put a stop to this? If so, what options do I have?

A: If a dependency exists in two different dependencies of a single module such that the same package name exists, you can forget about building the client app. For example:
Dependency # 1 -> classes.jar -> <some package name> -> Component
Dependency # 2 -> classes.jar -> <THE SAME package name> -> Component

If you have access to modify the two libraries, you will be forced to change the package name of one of them. There's no way around it, no way out of it.


text:
Q: How to represent a *[]string in a graphql SDL language when creating types in schema.graphqls? I am creating a graphql api but I am having trouble when using gqlgen for Golang,I need to represent this :
type Pets struct  {
    multiEan  *[]string
}

Into this more or less:
type Pets  {
    multiEan: [String!]
}

The think is when I run the command:
go run github.com/99designs/gqlgen generate

I get the golang struct representation given by the framework but not with the *[]string pointer I need, i get only a raw slice of []string, any ideas on how to solve it ?

A: Gqlgen generates the Go structs for you so you have to use what it gives you.  It does not make sense to say that I want it to generate something else given the GraphQL schema. You can adjust your schema to get different types but really you design the schema then work with the types that gqlgen has generated from it.
That said if your multiEan resolver should be nullable then you need and extra exclamation mark (!):
type Pets  {
    multiEan: [String!]!
}

However, since Go slices are reference types (can be assigned nil) this still won't generate a pointer to the slice.  If you need to use a pointer to the slice elsewhere then you can just take the address of it.  Maybe you could share a bit more code so we can see what you are trying to do.


text:
Q: Vagrant multiple VM config with CoreOS what I'm trying to do, it's to integrate the standard CoreOS Vagrantfile found here and my own Vagrantfile which boots an Ubuntu box.
This is my Vagrantfile:
# Vagrantfile API/syntax version.
VAGRANTFILE_API_VERSION = "2"

### Check if required plugins are installed
unless Vagrant.has_plugin?("vagrant-bindfs")
  raise 'vagrant-bindfs plugin is missing!'
end

unless Vagrant.has_plugin?("vagrant-hostsupdater")
  raise 'vagrant-hostsupdater plugin is missing!'
end

# Setup CoreOS config files
CLOUD_CONFIG_PATH = File.join(File.dirname(__FILE__), "user-data")
CONFIG = File.join(File.dirname(__FILE__), "config.rb")

# Defaults for config options defined in CONFIG
$num_instances = 1
$instance_name_prefix = "core"
$update_channel = "stable"

# Attempt to apply the deprecated environment variable NUM_INSTANCES to
# $num_instances while allowing config.rb to override it
if ENV["NUM_INSTANCES"].to_i > 0 && ENV["NUM_INSTANCES"]
  $num_instances = ENV["NUM_INSTANCES"].to_i
end

# Include Config file
if File.exist?(CONFIG)
  require CONFIG
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

# COREOS
  config.vm.define :coreos do |node|
    node.ssh.insert_key = false
    node.vm.box = "coreos-%s" % $update_channel
    node.vm.box_version = ">= 308.0.1"
    node.vm.box_url = "http://%s.release.core-os.net/amd64-usr/current/coreos_production_vagrant.json" % $update_channel

    node.vm.provider :virtualbox do |v|
      v.check_guest_additions = false
      v.functional_vboxsf     = false
    end

    if Vagrant.has_plugin?("vagrant-vbguest") then
      node.vbguest.auto_update = false
    end

    (1..$num_instances).each do |i|
      node.vm.define vm_name = "%s-%02d" % [$instance_name_prefix, i] do |node|
        node.vm.hostname = vm_name
        ip = "172.17.8.#{i+100}"
        node.vm.network :private_network, ip: ip

        if File.exist?(CLOUD_CONFIG_PATH)
          node.vm.provision :file, :source => "#{CLOUD_CONFIG_PATH}", :destination => "/tmp/vagrantfile-user-data"
          node.vm.provision :shell, :inline => "mv /tmp/vagrantfile-user-data /var/lib/coreos-vagrant/", :privileged => true
        end
      end
    end
  end

# UBUNTU

  config.vm.define :ubuntu do |node|
    node.vm.box = "ubuntu1404-64"
    node.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
    node.vm.network "private_network", ip: "192.168.100.100"
    node.vm.hostname = "wpthor"
    node.bindfs.debug = true

  ### Set a right amount of memory
    node.vm.provider :virtualbox do |vb|
      vb.customize ["modifyvm", :id, "--memory", "1024"]
    end

  ### Fix for Ansible bug resulting in an encoding error
    ENV['PYTHONIOENCODING'] = "utf-8"

  ### Run Ansible provision
    node.vm.provision "ansible" do |ansible|
      ansible.limit = 'all'
      ansible.verbose = "" ### If you notice errors, add "vvv" here to activate verbose mode
      ansible.playbook = "ansible/development.yml"
      ansible.inventory_path = "ansible/hosts"
    end
  end
end

It works without errors, but it boots only one CoreOS node (instead of 3). Probably it's a stupid syntax error, but I can't come up with a solution. Can you help me?

A: Just update the number of machines you want booted up.

$num_instances = 3


text:
Q: Push Notification to particular device in Android I am creating an Android app where in I will require the push notifications.
I can send notifications to multiple Devices very perfectly..There is no issue at all..
Here the query is How can I  send Notification to particular device (or user).
Like for example, If any 1 user's balance is low, then I want to generate Notification to particular that user.
What should be done to send the push notification to the particular individual user in Android?
Please Help and Suggest.
Thanks

A: This blog post suggests that when your app registers for cloud-to-device messages, it will receive a registration ID. You should have the app report this registration ID to your servers, where you can then supply it to the C2DM servers as required.


text:
Q: Array: Swift and IOS All,
Can you give me a source code of my below problem?
I have 100 user array and load that array value(username) in tableview.
Scenario:
When I click any tableviewcell, i store that value in new array( userArray) and also i have displayed right side discloser (checkmark).
But my problem is when i click again to deselect that user from tablecell  my app has been crashed due to index out of bound.
I know problem is out of index, but how can i resolve that issue so if i click again on that tablecell it will remove user from userArray and i get new fresh userArray?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let tagValue = 100 + indexPath.row
let cell: UITableViewCell = tableView.viewWithTag(tagValue) as UITableViewCell

if cell.accessoryType == UITableViewCellAccessoryType.None
{
    cell.accessoryType = UITableViewCellAccessoryType.Checkmark
    userToSendPost.append(self.users2[indexPath.row])
} else {
    cell.accessoryType = UITableViewCellAccessoryType.None
    let tempString = userToSendPost[indexPath.row] //tagvalue
    let objcArray = userToSendPost as NSArray
    let indexOfObject = objcArray.indexOfObject(tempString)
    userToSendPost.removeAtIndex(indexPath.row)
  }
}

sorry for my bad english.

A: You are approaching this incorrectly.
On the tableview set the property tableView.allowsMultipleSelection = true.
Then when you want to get the selected users...
let selectedIndexPaths = tableView.indexPathsForSelectedRows()

Then you can use the row property from those index paths to find the users.
var selectedUsers: [User] = []

for indexPath in selectedIndexPaths {
    let user = theUsers[indexPath.row]

    selectedUsers.append(user)
}

The multiple selection and the check mark is handled automatically by the tableview.

A: To follow your approach, I think this could help you ;)
But the approach of @Fogmeister is better !
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let tagValue = 100 + indexPath.row
        let cell: UITableViewCell = tableView.viewWithTag(tagValue) as UITableViewCell

        if cell.accessoryType == UITableViewCellAccessoryType.None
        {
            cell.accessoryType = UITableViewCellAccessoryType.Checkmark
            userToSendPost.append(self.users2[indexPath.row])
        } else {
            let tempUserString = self.users2[indexPath.row] // get your user string
            if contains(userToSendPost, tempString) { // check if exist on your array
                userToSendPost.removeObject(tempString) // remove it
            }
            cell.accessoryType = UITableViewCellAccessoryType.None
        }
}

// If you want to use Array, add this method
extension Array {
        mutating func removeObject<U: Equatable>(object: U) {
            var index: Int?
            for (idx, objectToCompare) in enumerate(self) {
                if let to = objectToCompare as? U {
                    if object == to {
                        index = idx
                    }
                }
            }

            if(index != nil) {
                self.removeAtIndex(index!)
            }
        }
}


text:
Q: how can i sort an array of structures in c I need to sort an array of structures, each one having a string that is a name.
I want to do a simple sorting using bubble sort and strcmp, but my code doesn't work, it outputs the last name I've entered for the entire loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 16
#define N 5

struct Prova {
  char nome[SIZE];
};

void sort(struct Prova *ptr) {
  char temp[SIZE];

  for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
      if (strcmp((ptr + i)->nome, (ptr + j)->nome) < 0) {
        strcpy(temp, (ptr + i)->nome);
        strcpy((ptr + i)->nome, (ptr + j)->nome);
        strcpy(temp, (ptr + j)->nome);
      }
    }
  }
}

int main() {
  struct Prova * ptr;
  ptr = (struct Prova*) malloc(N * sizeof(struct Prova));

  for (int i = 0; i < N; i++) {
    scanf(" %s", (ptr + i)->nome);
  }

  sort(ptr);

  for (int i = 0; i < N; i++) {
    printf("%s\n", (ptr + i)->nome);
  }
}

Basically it needs to sort all the names in the structures and print them in ascending order, using the first letter of the name.
UPDATED: Later i noticed that mistake in my code, thank you all for the replies/suggestions. Now is this:
  for(int i = 0; i < N - 1; i++)
{
  for(int j = i+1; j < N; j++)
  {
    // < 0 = Z-A  invece > 0 = A-Z
    if(strcmp((ptr+i)->nome,(ptr+j)->nome) > 0)
      {
        strcpy(temp, (ptr+i)->nome);
        strcpy((ptr+i)->nome,(ptr+j)->nome);
        strcpy((ptr+j)->nome, temp);
      }
  }

}

A: OP mis-coded
    strcpy(temp, (ptr + i)->nome);
    strcpy((ptr + i)->nome, (ptr + j)->nome);
    // strcpy(temp, (ptr + j)->nome);
    strcpy((ptr + j)->nome, temp);

Many other improvements possible

*

*Use qsort() @Karsten Koop

*Validate inputs.  Better to use fgets().

*Simplify, check and free --> struct Prova *ptr = malloc(sizeof *ptr * N); if (ptr == NULL) Handle_OutOfMemory(); ... // use ptr ... free(ptr);

A: The problem is the last strcpy statement. You need to reverse the parameters like this:
for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
      if (strcmp((ptr + i)->nome, (ptr + j)->nome) < 0) {
        strcpy(temp, (ptr + i)->nome);
        strcpy((ptr + i)->nome, (ptr + j)->nome);
        strcpy((ptr + j)->nome, temp);
      }
    }
  }
}


text:
Q: Java: NoSuchMethodException even though the method exists So I have a class with 2 public methods defined. When I call getDeclaredMethods, then loop over the results, printing the names, both correctly show up. So not only does the method exist, but the reflection call finds it.
But when I try calling the method, like in the code below, I get a NoSuchMethodException. So why can't it find it when invoking?
public class Foo
{
  public byte[] read_status(Object arg)
  {
    byte[] test = new byte[10];
    for(int i = 0; i < 10; i++)
    {
      test[i] = (byte)i;
    }
    return test;
  }

  public int test(String s) throws Exception
  {
    Object r = this.getClass().getDeclaredMethod("read_status").invoke(this, (Object)s);
    byte[] bytes = (bytes[])r;
    for(int i = 0; i < bytes.length; i++)
    {
      System.out.println(""+bytes[i]);
    }
    return 0;
  }
}

A: You should put the parameters' types of the method, your code should look like this:
public int test(String s) throws Exception {
    Object r = this.getClass().getDeclaredMethod("read_status", Object.class).invoke(this, (Object)s);
    byte[] bytes = (byte[])r;
    for(int i = 0; i < bytes.length; i++) {
      System.out.println(""+bytes[i]);
    }
    return 0;
}


text:
Q: Number of red and blue marbles when probability of drawing two marbles of the same color is 0.5 There are $n$ marbles in a container. The marble is either red or blue. The probability of you drawing two marbles of the same color on the first two draws is 0.5. What is the number of red and blue marbles?
Let $x, y$ denote the number of red and blue marbles, respectively. Then $x+y=n$ and
\begin{align}
    \frac{x}{n}\frac{x - 1}{n - 1} + \frac{y}{n}\frac{y - 1}{n - 1} = 0.5 \\
\end{align}
After some manipulation we end up with
$$
x^2 + y^2 - x - y - 2xy = 0
$$
1 equation. 2 unknowns, so there should be an infinite number of solutions. The issue is $x,y$ are constrained to be integers, so it's not as easy to find a solution. But after some plug and chug, I found that $x = 3$ leads to integer solutions for $y$, specifically $y \in \{1, 6\}$.
Is there a more procedural way to obtain $x$ and $y$? I don't want to resort to checking values for values of $x$ since that could take a long time.


text:
Q: Cannot open tar file I have a file called data. Although the file doesn't have an extension, I used the file bash command to see what type of file it is:
$ file data
data: POSIX tar archive (GNU)

Seeing as it is a tar file, I try to open it but I get an error:
$tar xvf data
tar: data: Not found in archive

A: You need to add a hyphen before the xvf.
tar -xvf data

Else, if you are in another location.
tar -xvf /<path to data>/data


text:
Q: How can I say this in jQuery? I am tryng to say onClick of the link with class "myLink" show the div with the class "myDiv". And on focusOut hide the "myDiv" div. But my problem is with the focusOut part. Right now my code looks like this:

Click Me

$('.myDiv').hide();
$('.myLink').click(function(event) {
    $('.myDiv').show();
    event.preventDefault();
});
$('.myLink').focusout(function(event) {
    $('.myDiv').hide();
    event.preventDefault();
});

problem is, if the user clicks anywhere other than the "myLink" link it is considered focusOut. I don't want the div to hide if the user clicks within the div, I want it only to hide if the user clicks anywhere other than the link AND the div. How to do this?

A: Have you tried binding to the div's focusout instead of the link's focusout?


text:
Q: iPhone Apps pause update when screen is locked It seems that when updating multiple Apps and locking the screen, updates are not completed until reopening the phone.
Once I used the 'Update All', which started updating, before going to sleep, only to find hours later that most of the Apps are waiting in some 'installing' stage. Once I unlocked the phone, it took 5 minutes for them to finish.
Can't tell if this is intended and what are the reasons.
It use to be that when I used the 'Update All', close the phone (locked screen) and come back 10 minutes later and everything is updated.


text:
Q: How to connect Django to Cassandra Data base? I have a project which I have to develop with Django using Cassandra data base. I looked in there documentation but there is only information about mysql, sklite and postgre databases, nothing about Cassandra. I am looking for a sample way to connect Django to Cassandra:
I know i have to set the database configuration in the file setting.py:
    # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
    "ENGINE": "django.db.backends.cassandra",
    # DB name or path to database file if using sqlite3.
    "NAME": "test",
    # Not used with sqlite3.
    "USER": "",
    enter code here# Not used with sqlite3.
    "PASSWORD": "",
    # Set to empty string for localhost. Not used with sqlite3.
    "HOST": "127.0.0.1",

but it throws an error:
Error was: No module named django_cassandra.base

Can anyone help me ?

A: You can use this pattern for your settings.py at Django Project folder:
    DATABASES = {
    'default': {
        'ENGINE': 'django_cassandra_engine', # Install this engine from https://pypi.org/project/django-cassandra-engine/
        'NAME': 'yourkeyspace', # the keyspace was created at cassandra
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',  # You can add your hosts here (use ,)
        'OPTIONS': {
            'replication': {
                'strategy_class': 'SimpleStrategy', # or any strategy you need
                'replication_factor': 1 # Depend on your decision
            },
            'connection': {
                'consistency': ConsistencyLevel.ONE,
                'lazy_connect': True,
                'retry_connect': True,
                'port': 9042, # default port
                #  You can add any connection options for cassandra.Cluster() here!
                          }
                     }
              }
        }

A: Django does not currently support nosql as backends.  There is a nice django-like ORM called cqlengine, https://github.com/cqlengine/cqlengine, which is actively being developed and the datastax team says they are working with the cqlengine people.  Although you can't use the database defs in settings.py, you can use django-like commands, for example, thingy.objects.all() to access your cassandra.
The native datastax python driver found on the datastax site, is more cqlsh oriented, may remind you of the oracle connector but is a bit faster.
The answer recommended in the link is very old.
Hope this helps.


text:
Q: Poisson or Normal distribution? In this problem:

The respiratory disturbance index (RDI), a measure of sleep disturbance, for a specific population has a mean of 15 (sleep events per hour) and a standard deviation of 10. They are not normally distributed. Give your best estimate of the probability that a sample mean RDI of 100 people is between 14 and 16 events per hour?

I solved the problem by using the central limit theorem, i.e. that the sample mean approaches the population mean, even if the population is not normally distributed.
> pnorm((16-15)/(10/sqrt(100)))-pnorm((14-15)/(10/sqrt(100)))
[1] 0.6826895

Can I model the problem with a Poisson distribution or would I require explicit information that the RDI follows a Poisson distribution in order to meaningfully do so?

A:
Poisson or Normal distribution?

Possibly neither.

I solved the problem by using the central limit theorem, i.e. that the sample mean approaches the population mean, even if the population is not normally distributed.

That's not what the CLT says. What you have there -- "that the sample mean approaches the population mean" sounds like the law of large numbers, but it's not sufficient to solve this problem.
What you need to use the normal distribution is the assumption that the sample mean is near enough to normally distributed to apply normal calculations. The central limit theorem doesn't tell you that either.
There's not really enough information in the question to make much of an assessment (not even to apply Berry-Esseen which does give one specific sense of how far off the normal might be).
I presume the intent here was to apply the normal approximation. You're left simply to assume (with no good reason to do so) that the sample size is large enough in this instance to apply a normal approximation.
However, because you have a fairly short interval about the mean (only going out a standard deviation), this may work fairly well for a wide variety of cases. You might also consider whether to apply a continuity correction.
[Edit: After playing around with a variety of more-or-less plausible possibilities for the original distribution consistent with the information given (including the obvious condition that disturbances per hour must be non-negative), I think the normal approximation should generally work quite well for this specific instance. However, it's possible to construct distributions consistent with the information where that probability is much smaller.]
[There are some results for bounds on the tails of distributions of sums (e.g. Chernoff bounds), but I don't think that's of substantive help here.]

Can I model the problem with a Poisson distribution

Counts may well not be Poisson. Consider, for example, a situation where individuals have Poisson distributions, but each individual's Poisson parameter is drawn from a Gamma distribution. Then the population distribution is negative binomial.
Now if the population distribution were Poisson, one thing you should see is that the population mean and variance should be the same. However, $15 \neq 100$.

or would I require explicit information that the RDI follows a Poisson distribution in order to meaningfully do so?

You have explicit information that the population distribution of counts is not Poisson. It's not a plausible approximation.
Further note that disturbances per hour is not necessarily an integer, since presumably disturbances are counted across a period other than exactly an hour (I presume across the duration of sleep for each individual) and then scaled to 'disturbance per hour' so as to be more comparable. As such you have (differently) scaled counts for each individual and would not expect a count data model to necessarily fit well. You're effectively dealing with rates rather than counts, and so a Poisson would not be expected to fit.


text:
Q: ¿Comó puedo hacer para que en un foreach (laravel) me pueda imprimir los resultados de dos variables, en vez de usar doblemente el foreach? En el código siguiente muestro como obtengo las variables que es "empresa" y con las funciones de laravel complemento el "código", pero, ¿cómo puedo poner dos variables como si fuese una:  "empresa && establecimientos"?

            @foreach ($empresas as $empresa)

id }})">

 foto_perfil }}" />

                                {{ $empresa->nom_empresa }}

            @endforeach

A: puedes hacer esto:
{{ $empresa->nom_empresa." ".$empresa->establecimientos }}

o esto:
{{ $empresa->nom_empresa }} {{ $empresa->establecimientos }}


text:
Q: reactjs bundle script by browserify not working on the client side (Uncaught ReferenceError: Component is not defined) I'm trying out using node.js and reactjs as a template rendering service for my php backend. Here's the guideline.
I wonder if there's a problem with my bundle.js built by browserify. I'm getting Uncaught ReferenceError: ItemPage is not defined on the client side because the component ItemPage is not global in the bundle.js, but I have no idea how to access it since it is wrapped in some functions that I really don't understand.
Here's my es6 component script:
import React from 'react';
import Tabs from 'grommet/components/Tabs';
import Tab from 'grommet/components/Tab';
class ItemPage extends React.Component {
    render(){
        return <Tabs onClick={this._onClick.bind(this)}>
            <Tab title="First Title">

First Tab

Contents of the first tab !

Something@@@@@@

            </Tab>
            <Tab title="Second Title">

Second Tab

Contents of the second tab

            </Tab>
            <Tab title="Third Title">

Third Tab

Contents of the third tab

            </Tab>
        </Tabs>
    }
    _onClick(){
        alert("raging")
    }
}

The command I use to bundle the script:
browserify src/ItemPage.js -o /js/build/ItemPage.js -t [ babelify --presets [ es2015 react ] ]

Output:
    echo '
';

     // reactjs markup content sent back from node.js
    echo $content;

    echo '
';

    echo '';
    echo '';

    echo '';

    echo '';

Error:
Uncaught ReferenceError: ItemPage is not defined

Here is my bundle file (2mb):
https://drive.google.com/file/d/0B1XYujDUsAgtb3NrSlBFQ19qckU/view?pref=2&pli=1
You can see that ItemPage isn't global in the script.
Update:
I have added default export to the file:
import React from 'react';
import Tabs from 'grommet/components/Tabs';
import Tab from 'grommet/components/Tab';
class ItemPage extends React.Component {
    render(){
        return <Tabs onClick={this._onClick.bind(this)}>
            <Tab title="First Title">

First Tab

Contents of the first tab !

Something@@@@@@

            </Tab>
            <Tab title="Second Title">

Second Tab

Contents of the second tab

            </Tab>
            <Tab title="Third Title">

Third Tab

Contents of the third tab

            </Tab>
        </Tabs>
    }
    _onClick(){
        alert("raging")
    }
}
export default ItemPage;

However ItemPage is still local and inaccessible on the client side.
Here is my latest build:
https://drive.google.com/file/d/0B1XYujDUsAgtZjNvaFdBUVlzU2s/view?usp=sharing

A: Aside from adding export you need to say browserify to generate UMD output by adding --standalone flag.

--standalone -s  Generate a UMD bundle for the supplied export name.
                     This bundle works with other module systems and sets the name
                     given as a window global if no module system is found.

browserify src/ItemPage.js
        -o /js/build/ItemPage.js
        --standalone ItemPage
        -t [ babelify --presets [ es2015 react ] ]

multiline for the sake of readability

A: You need to export ItemPage in your script
export default ItemPage


text:
Q: BottomNavigationView Is hiding my webview I have a  BottomNavigationView activity . in that, i have a webview fragment, whenever the web-view loads a website. The BottomNavigationView is hiding the bottom part of my web-view, is there anyone who can help me regarding this ?
this is my activity_main.xml which contain the BottomNavigationView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hackerinside.jaisonjoseph.polysocial.MainActivity">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    android:layout_alignParentBottom="true"
    app:menu="@menu/navigation" />

</RelativeLayout>

This is my first fragment code which contain the webview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.hackerinside.jaisonjoseph.polysocial.tab2">

<FrameLayout
    android:id="@+id/frame1"
    android:layout_width="match_parent"
    android:layout_height="3dp"
    android:background="@android:color/transparent">

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="3dp"
        android:background="@android:color/transparent"
        android:foregroundGravity="top"
        android:progressDrawable="@drawable/custom_progress"
        android:progress="20"/>

</FrameLayout>

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.hackerinside.jaisonjoseph.polysocial.EulaWebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview"
        android:focusable="true"
        android:focusableInTouchMode="true" />

</android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

A: You just neet to add a FrameLayout (It will be you container so keep its id as  android:id="@+id/container")

and replace your code of activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container"
        android:layout_above="@+id/navigation"
        >

    </FrameLayout>
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        android:layout_alignParentBottom="true"
        app:menu="@menu/navigation" />

</RelativeLayout>

A: Actully you are adding your your fragment on all your layout which is below the navigation below. you should use layout like below and place your fragment within inner layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        android:layout_alignParentBottom="true"
        />
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_above="@id/navigation"
    android:layout_height="match_parent">
    <!--Your code for the fragment here.-->
</RelativeLayout>

</RelativeLayout>

A: use
android_layout_height="50dp" (in bottom navigation)
and use
android_layoutmarginBottom="50dp"  (in web view)
hope it helps.


text:
Q: Convert VarChar to Float with different culture format From different external sources I get data where some numbers are in a NVarChar field. Until now I used a REPLACE with a CAST to ensure that numbers with a "," where cast the right way. Like this:
select cast(replace('12,5',',','.') as float)
select cast(replace('12.5',',','.') as float)

This has worked just fine, but now I get data where there is also a thousand separator in. Like this:
select cast(replace('2.012,5',',','.') as float)
select cast(replace('2,012.5',',','.') as float)

It' broken.
Is there a way to detect which data format is used in a NVarChar with a number?
I have tried to use TRY_PARSE with a culture parameter, it works well if there is a thousand separator but not without:
SELECT @Fuelunits =
CASE
    WHEN ISNUMERIC(TRY_PARSE(@Hoeveelheid AS decimal(9,2) USING 'nl-NL')) = 1
THEN CAST(TRY_PARSE(@Hoeveelheid AS decimal(9,2) USING 'nl-NL') AS FLOAT)
ELSE CAST(TRY_PARSE(@Hoeveelheid AS decimal(9,2) USING 'en-US') AS FLOAT)
END

The problem is that I have to use this in an UPDATE and that that the data format can differ in the same table.
Any suggestions?

A: You can use CHARINDEX() to work out what separators are present and where they are in the string along with a CASE expression to handle different cases before you REPLACE and CAST to FLOAT:
CREATE TABLE #vals (val NVARCHAR(10));

INSERT INTO #vals
(
    val
)
VALUES
(N'2.012,5'),
(N'2,012.5');

SELECT CAST(CASE
                -- is there a '.' in a position before a ','?
                WHEN CHARINDEX('.', val) < CHARINDEX(',', val) THEN
                    -- yes - remove the '.' and replace the ',' with '.'
                    REPLACE(REPLACE(val, '.', ''), ',', '.')
                ELSE
                    -- no - just remove the ','
                    REPLACE(v.val, ',', '')
            END AS FLOAT)
FROM #vals AS v;

DROP TABLE #vals;

References:
CHARINDEX (Transact-SQL)

Searches an expression for another expression and returns its starting position if found.


text:
Q: Android HttpClient with XML issue I have problem at Android HTTPClient.
I am converting iOS app into Android.
here is the iOS code.
NSURL *uri = [NSURL URLWithString:url];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:uri];
[request appendPostData:[strData dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];

it returns XML data correctly.
and here is the android code.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);

httppost.addHeader("Accept", "text/xml");
httppost.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity(strData, "UTF-8");
entity.setContentType("text/xml");
httppost.setEntity(entity);

HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String responseBody = EntityUtils.toString(resEntity, HTTP.UTF_8);

but web server returns html data which is same when I call url without xml.
I have double checked the url and strdata is exactly same at iOS and Android;
Can you help me what I made mistake.
Many thanks.


text:
Q: How to rebuild the dynamic Huffman tree from DEFLATE This question is in regards to section 3.2.7 of RFC-1951, rebuilding the dynamic Huffman tree.
Each code is defined by a sequence of code lengths, such that all codes of a given bit length have lexicographically consecutive values.
For example, here is a rgb(255,0,0) 50x50 png, where the IDAT is a dynamic Huffman tree from DEFLATE.
0000024: xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx  CIDATx
000002a: xxxxxxxx 11101101 11001111 00110001 00010001 00000000  ...1..
0000030: 00000000 00001000 00000000 10100001 11101111 01011111  ....._
0000036: 01011010 00110011 10111000 01111010 00001100 00000100  Z3.z..
000003c: 10100000 10101001 11111001 00100000 00010001 00010001  ... ..
0000042: 00010001 00010001 00010001 00010001 00010001 00010001  ......
0000048: 00010001 00010001 00010001 00010001 00010001 00010001  ......
000004e: 00010001 00010001 00010001 00010001 00010001 00010001  ......
0000054: 00010001 00010001 00010001 00010001 00010001 00010001  ......
000005a: 00010001 00010001 00010001 00010001 00010001 00010001  ......
0000060: 00010001 00010001 00010001 00010001 00010001 10010001  ......
0000066: 10001011 00000101 10110000 00110011 01110101 10010110  ...3u.
000006c: 01111001 11000101 00011100 10110001 00000000 00000000  y.....
0000072: 00000000 00000000 01001001 01000101 01001110 01000100  ..

infgen produces this header:
last
dynamic
litlen 0 2
litlen 255 4
litlen 256 4
litlen 274 4
litlen 283 4
litlen 285 1
dist 3 1
dist 15 1

...the goal is to understand the bits and processes to rebuild the dynamic tree...

The first three bits describe the DEFLATE header.
101 <- last block bit, tree type is dynamic.

The next fourteen bits describe the HLIT, HDIST, and HCLEN.
11101 <- HLIT,  29 + 257 = 286
01111 <- HDIST, 15 + 1 = 16
1110 <- HCLEAN, 14 + 4 = 18

What do these values describe about the dynamic Huffman tree?

Next, reading three bits at a time and following the permutation table...the lengths are found to be...
Lengths: [4, 2, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2] (line 697 of puff.c)
Are these lengths used to define the literals?

A: More information...the next 14 bits are...
5 Bits of HLIT, the Literal/Length codes - 257 (257 - 286)
5 Bits of HDIST, the Distance codes - 1        (1 - 32)
4 Bits of HCLEN, the Code Length codes - 4     (4 - 19)

From the example:
  HLIT => 29 + 257 = 286, HDIST => 15 + 1 = 16, HCLEN => 14 + 4 = 18

Now gather 3-bit values HCLEN times. Following the order of the permutationt table (page 13 from RFC-1951.)
permuted ordering: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]

From the example:
   HCLEN is 18 => 18*3 = 54-bits.
   lengths: [ 4 2 4 0 2 0 0 0 0 0 0 0 0 0 0 0 0 3 2 ]

Next unpack those triple-bit values. This unpacking provides instructions on how to construct the dynamic Huffman tree… "For even greater compactness, the code length sequences themselves are compressed using a Huffman code."
To unpack the triple-bit values: (examples below)
  1. Count the number occurrences of the values.
  2. Determine the offset, the count plus the previous offset.
  3. Determine the symbols.
     A symbol is placed at the offset value, which is found at a length value.
     After placing a symbol, increment the offset.

From the example:
    LENGTHS: [ 4 2 4 0 2 0 0 0 0 0 0 0 0 0 0 0 0 3 2 ] //the three-bits from HCLEN
    COUNT: [ 13 0 3 1 2 0 0 0 0 0 0 0 0 0 0 0 ] //the occurrences of lengths.
      i.e, 0 occurs 13 times, 1 occurs 0 times, 2 occurs 3 times...
    OFFSET: [ x 0 0 3 4 6 6 6 6 6 6 6 6 6 6 6 ] //the count plus the previous offset.
      i.e, o[2] = 0 + 3, o[3] = 3 + 1, o[4] = 4 + 0...
    SYMBOL: [ 1 4 18 17 0 2 ] //use length to index offset to place symbol
      i.e, if i=1, s[off[len[i]]] = s[off[len[2]]] => s[off[0]] => s[0] = 1, increment off[0]...

...The symbols are now defined. Next decode bits to build the dynamic Huffman tree…

A:
What do these values describe about the dynamic Huffman tree?

They don't really tell you much about the tree, but rather how many symbols for each type of code are described in the subsequent bits of the dynamic header.
There are eighteen code length code lengths provided next (three bits each), followed by 286 literal/length codes and then sixteen distance codes, all encoded using the code length code.

Are these lengths used to define the literals?

No. The three-bit lengths are for the code length codes. You need to build that code just to read the following literal/length and distance code lengths, which are themselves compressed using that code.
This is described in section 3.2.7 of RFC 1951:
"For even greater compactness, the code length sequences themselves are compressed using a Huffman code."

A: The header contains bit lengths of the Deflate Literal (0-255), Length (256-285), and Distance codes (0-29). If you know their bit lengths you can rebuild the tree following the algorithm in Section 3.2.2 of RFC1951.  Look for the steps that start with "Count the number of codes for each code length..."
However, the bit length values are also encoded with Huffman using 0 to 7 bits.  You need first crack open the HCLEN table at the beginning using the same algorithm as above.  Section 3.2.7 explains it.
Why encode the header twice as such?  To make the dynamic Huffman header small.


text:
Q: How to get all the keys from a specific doc of a collection in firestore? I have already learned firestore CRUD. It is easy to get value from a document if fields are known of the doc. My question is how to grab the list of keys that the specific doc has. I need it because I want to show the fields and values in a table. If I add more fields in future in the same doc then the table will automatically be updated with the new fields and values.

Thanks.

A: As mentioned in the docs you can get a document snapshot using get() method of a document reference and then use data() method of snapshot to get all the data in the document as an object.
https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document
var docRef = db.collection("users").doc("alovelace");

docRef.get().then(function(doc) {
    if (doc.exists) {
        // Here you can get your data
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
});

Then you have an object of key values representing your document data.


text:
Q: Monotonicity of this series Given the function $f:\mathbb{R}\to \mathbb{R}$ with $f(x)=e^{x-1}$ we have the series $(x_n)_{n\ge1}$ where:
$x_1=2$ and $x_{n+1}=f(x_n), n\ge1$
Find the monotonicity of the series and compute $\lim _{n\to \infty }\left(x_n\right)$
I think the function is strictly increasing, but I'm not sure if I worked correctly...

A: Hint: to establish that the sequence is increasing, it suffices to show that $f(x) > x$ for all $x \geq 2$.
One way to do so is to check that $f(2) > 2$, then notice that the function $f(x) - x$ has a positive derivative.

A: You just need to show that $f(x_n)>x_n$, or
$$
e^{x-1} > x
$$
for $x\ge 2$. Let $x=1+y$; then
$$
e^y > 1 + y,
$$
which is well-known inequality for $y > 0$.
And now about limit. Let $\lim_{n\to\infty} x_n$ exists and equals to $a$. By condition,
$$
x_{n+1}=e^{x_n-1} \Longrightarrow \lim_{n\to\infty} x_{n+1}=\lim_{n\to\infty}e^{x_n-1} \Longrightarrow a = e^{a-1}
$$
(we used continuity of exp). However, this equation have single root $a=1$, which is not a limit obviously. So, $x_n$ stricly increasing and unbound (if it's bounded, then limit exists); hence it tends to infinity.


text:
Q: Is it safe to reboot linux just after an lvextend? I'm wondering how safe it is to reboot a Linux install just after I did an lvextend on a mirrored partition.
I can see that the partition is being mirrored properly as the HDD light is light solid. So it's working hard on that one... and I've seen before that it can take hours to update a complete mirror (I just added over 800Gb to that volume).
The lvextend command has returned with no errors and I can run the lvs command and see that the mirror is 47% done.
Is it safe to reboot while the mirror is being updated in this way?
Note: the mirror was 100% up to date before the lvextend command was run.

A: Please check the mirror segment type with lvs -o name,segtype: if it's raid1, it should be safe to reboot if you must, although you might lose some progress.
If the segment type is the legacy mirror, the same will apply to you only if there is a separate on-disk mirror log segment in use. This mirror type includes a --mirrorlog setting with several options: disk is a persistent mirror log that is not itself mirrored, core keeps the mirror log in RAM only, which will always require resyncing from 0% at every reboot. There used to be also a mirrorlog option mirrored, but apparently it had some design issues as the current lvconvert man page specially recommends that it should be avoided (and creating new mirror segments with that mirrorlog type may already be prevented).
The LVM mirroring code includes a checkpointing mechanism: every once in a while the synchronization process updates a persistent record of how far it got, and if the synchronization is interrupted for any reason, it will automatically resume from the last checkpoint.
Nevertheless, I would not reboot a system when a software RAID of any type is in the middle of syncing unless I absolutely had to. Just in case.


text:
Q: What's the difference between Sequential and Synchronous Execution? If I understand it correctly:
Asynchronous Execution - One task doesn't have to wait for another to finish
Concurrent Execution - Two tasks are being worked during a common time period (usually through context switching)
But the opposites of both of those seem the same.
Synchronous Execution - One task has to wait for another to finish before executing
Sequential Execution - Two tasks can't be worked on during a common time period. They have to be executed in order.
It seems Synchronous and Sequential execution are the same thing. What am I missing?

A: Sequential and synchronous are different things. Lets take for example next pseudocode:
pseudocode
{
do A
do B
do C
}
both sequential and synchronous will do task in order A->B->C. The difference is in the way they can do it.
Only way synchronous can do it is to start executing task A, block everything and wait till the task is finished. After that it proceeds to task B. You can imagine this as execution of all tasks on one single thread.
On the other hand with sequential execution we can start execution of task A on thread 1 in background. After is finishes we can start executing task B on our main thread (lets say thread 2).
We have same end result, but as you can see the process is different


text:
Q: Update field key in cloud firestore Updating a field can be done like
firestore.collection("Users").document(user).update("key", "value");

but i want to do the opposite. updating "key" itself. not it's value. for example key: value ---> key2: value
Is it possible?

Thanks

A: What you are asking is not possible. But you can achieve this by getting the value first by the key, then store the value in a variable. After that you can add a new record. So the value will be same, but key will be updated.
I hope you understood what I'm trying to say.


text:
Q: Creating dynamic and expandable dictionaries in Python I want to create a Python dictionary which holds values in a multidimensional array that can expand.
This is the structure that the values should be stored:
userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','country':'USA'}]}

Let's say I want to add another user:
def user_list():
     users = []
     for i in xrange(5, 0, -1):
       lonlatuser.append(('username','%s %s' % firstn, lastn))
       lonlatuser.append(('age',age))
       lonlatuser.append(('country',country))
     return dict(user)

This will only return a dictionary with a single value in it (since the key names are same values will overwritten). So how do I append a set of values to this dictionary?
Note: assume age, firstn, lastn, and country are dynamically generated.

A: userdata = { "data":[]}

def fil_userdata():
  for i in xrange(0,5):
    user = {}
    user["name"]=...
    user["age"]=...
    user["country"]=...
    add_user(user)

def add_user(user):
  userdata["data"].append(user)

or shorter:
def gen_user():
  return {"name":"foo", "age":22}

userdata = {"data": [gen_user() for i in xrange(0,5)]}

# or fill separated from declaration so you can fill later
userdata ={"data":None} # None: not initialized
userdata["data"]=[gen_user() for i in xrange(0,5)]

A: What's the purpose of the outer data dict?
One possibility is not to use username as a key, but rather the username itself.
It seems like you are trying to use dicts as a database, but I'm not sure it's a good fit.

A: I think it's too late for the answer but nevertheless, hoping that it may help somebody in near future I'm gonna give the answer. Let's say I have a list and I wanna make them as a dictionary. The first element of each of the sublists is the key and the second element is the value. I want to store the key value dynamically. Here is an example:
dict= {} # create an empty dictionary
list= [['a', 1], ['b', 2], ['a', 3], ['c', 4]]
#list is our input where 'a','b','c', are keys and 1,2,3,4 are values
for i in range(len(list)):
     if list[i][0] in dic.keys():# if key is present in the list, just append the value
         dic[list[i][0]].append(list[i][1])
     else:
         dic[list[i][0]]= [] # else create a empty list as value for the key
         dic[list[i][0]].append(list[i][1]) # now append the value for that key

Output:
{'a': [1, 3], 'b': [2], 'c': [4]}

A: You can create a list of keys first and by iterating keys, you can store values in the dictionary
l=['name','age']

d = {}

for i in l:
    k = input("Enter Name of key")
    d[i]=k

print("Dictionary is : ",d)

output :
Enter Name of key kanan
Enter Name of key34
Dictionary is :  {'name': 'kanan', 'age': '34'}

A: You could try this
Python 3+
key_ref = 'More Nested Things'
my_dict = {'Nested Things':
                [{'name', 'thing one'}, {'name', 'thing two'}]}

my_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}]

try:
    # Try and add to the dictionary by key ref
    my_dict[key_ref].append(my_list_of_things)

except KeyError:
    # Append new index to currently existing items
    my_dict = {**my_dict, **{key_ref: my_list_of_things}}

print(my_dict)

output:
{
    'More Nested Things': [{'name', 'thing three'}, {'name', 'thing four'}],
    'Nested Things': [{'thing one', 'name'}, {'name', 'thing two'}]
}

You could rap this in your on definition and make it more user friendly, typing try catch it fairly tedious


text:
Q: If else statement with mysql table? - PHP I need to make an if else statement that will prevent a user from bidding on an item if they are the highest bidder. I think it would go a little something like this.
if ($accountid = the accountid in the bidhistory table)
{
    echo "You are the highest bidder!";

}
else
{
$sql="INSERT INTO bidhistory (accountid, biditemid)
VALUES ($accountid, $itemid)";

mysql_query("
UPDATE bidhistory
SET bidprice = bidprice + 1
WHERE biditemid = " .
@mysql_escape_string($itemid));

$result=mysql_query($sql) or die("Error in adding bid for item: ".mysql_error());
}
?>

I'm not sure how to reference the accountid from the bidhistory table. Also, if there is a better way to do this, please point me in the wright direction. Thanks!

A: Note:

*

*You can fetch the row of the highest bid with the specific item first.
Then check if the highest bidder (accountid) is the same with the current user.

*You can check the notes I had for some lines quoted in /* ... */
Your query for checking:
$result = mysql_query("SELECT accountid FROM bidhistory WHERE biditem = '$itemid' ORDER BY bidhistoryid DESC LIMIT 1"); /* GET THE LAST ROW FOR WHO BIDS LAST; AND REPLACE NECESSARY COLUMN NAME (unique/primary) - bidhistoryid */
while($row = mysql_fetch_array($result)){
  $checkaccountid = $row['accountid']; /* STORE THE USER THAT BIDS LAST FOR THIS ITEM */
}

if($checkaccountid == $accountid){ /* THEN COMPARE IT WITH THE CURRENT USER */
  /* CODE YOU WANT TO DO IF HE/SHE IS THE LAST BIDDER ALREADY */
}
else {
  /* IF NOT, HE/SHE CAN STILL BID */
}

But I recommend that you use mysqli_* rather than the deprecated mysql_* API.
$con = new mysqli("YourHost", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if($stmt = $con->prepare("SELECT accountid FROM bidhistory WHERE biditem = ? ORDER BY bidhistoryid DESC LIMIT 1")){
  $stmt->bind_param("i",$itemid); /* BIND THIS VARIABLE TO YOUR QUERY ABOVE */
  $stmt->execute(); /* EXECUTE THE QUERY */
  $stmt->bind_result($checkaccountid); /* STORE THE RESULT TO THIS VARIABLE */
  $stmt->fetch(); /* FETCH THE RESULT */

  if($checkaccountid == $accountid){
    /* CODE YOU WANT TO DO IF HE/SHE IS THE LAST BIDDER ALREADY */
  }
  else {
    /* IF NOT, HE/SHE CAN STILL BID */
  }
  $stmt->close();

} /* END OF PREPARED STATEMENT */


text:
Q: Unable to use elasticsearch sink connector (kafka-connect) I'm currently trying to start an elasticsearch sink connector on a kafka-connect cluster (distributed mode)
This cluster is deployed in kubernetes using the helm charts provided by confluent with some tweaks in it.
Here is relevants parts :
For values.yaml
configurationOverrides:
  "plugin.path": "/usr/share/java,/usr/share/confluent-hub-components"
  "key.converter": "org.apache.kafka.connect.storage.StringConverter"
  "value.converter": "org.apache.kafka.connect.json.JsonConverter"
  "key.converter.schemas.enable": "false"
  "value.converter.schemas.enable": "false"
  "internal.key.converter": "org.apache.kafka.connect.json.JsonConverter"
  "internal.value.converter": "org.apache.kafka.connect.json.JsonConverter"
  "config.storage.replication.factor": "3"
  "offset.storage.replication.factor": "3"
  "status.storage.replication.factor": "3"
  "security.protocol": SASL_SSL
  "sasl.mechanism": SCRAM-SHA-256

And for the kube cluster part :
releases:
  - name: kafka-connect
    tillerless: true
    tillerNamespace: qa3-search
    chart: ../charts/cp-kafka-connect
    namespace: qa3-search
    values:
      - replicaCount: 2
      - configurationOverrides:
          config.storage.topic: kafkaconnectKApp_connect-config_private_json
          offset.storage.topic: kafkaconnectKApp_connect-offsets_private_json
          status.storage.topic: kafkaconnectKApp_connect-statuses_private_json
          connect.producer.client_id: "connect-worker-producerID"
          groupId: "kafka-connect-group-ID"
          log4j.root.loglevel: "INFO"
          bootstrap_servers: "SASL_SSL://SOME_ACCESSIBLE_URL:9094"
          client.security.protocol: SASL_SSL
          client.sasl.mechanism: SCRAM-SHA-256
      - prometheus:
          jmx:
            enabled: false
      - ingress:
          enabled: true
          hosts:
            - host: kafka-connect.qa3.k8s.XXX.lan
              paths:
                - /
      - cp-schema-registry:
          url: "https://SOME_ACCESSIBLE_URL"

Then I am loading the elasticsearch sink connector as such :
curl -X POST -H 'Content-Type: application/json' http://kafka-connect.qa3.k8s.XXX.lan/connectors -d '{
"name": "similarads3",
"config": {
"connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
"consumer.interceptor.classes": "io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor",
"topics": "SOME_TOPIC_THAT_EXIST",
"topic.index.map": "SOME_TOPIC_THAT_EXIST:test_similar3",
"connection.url": "http://vqa38:9200",
"batch.size": 1,
"type.name": "similads",
"key.ignore": true,
"errors.log.enable": true,
"errors.log.include.messages": true,
"value.converter": "io.confluent.connect.avro.AvroConverter",
"value.converter.schema.registry.url": "SOME_ACCESSIBLE_URL",
"schema.ignore": true
}
}' -vvv

More over I'm loading user and password for brokers auth via environment variable, and I'm pretty sure it is connected with rights ACL...
What is troubling me, is that there is no index creation when the connector starts, and there is no error what so ever in kafka-connect's logs... And it says everything has started
Starting connectors and tasks using config offset 68

When running a curl on /connectors/similarads3/status, everything is running, without errors.
So it seems like I overlooked something, but I can't figure out what is missing.
When I check consumers lag on this particular topics, it seems like no messages where consumed ever.
If there is not enough information, I'm able to provide more.
Does someone have an idea ?
EDIT : I should have mentioned that I tried to configure it with a topic that does not exist : again no error in logs. (I don't know how to interpret this)
EDIT 2 : This issue is solved
Actually we found the issue and it appears that i did overlooked something: in order to read from a topic protected by ACLs rights, you have to provide the SASL configuration for both the connector and the sink consumer.
So just duplicating the configuration prefixed with consumer. fixed this problem.
However I'm still surprised that no logs can point to this.

A: We had issues trying to use the topic.index.map property. Even if you got it working there is a note in the docs that it is deprecated.
topic.index.map
This option is now deprecated. A future version may remove it completely. Please use single message transforms, such as RegexRouter, to map topic names to index names.

I'd try using the RegexRouter to accomplish this instead.
"transforms": "renameTopicToIndex",
"transforms.renameTopicToIndex.type": "org.apache.kafka.connect.transforms.RegexRouter"
"transforms.renameTopicToIndex.regex": ".*"
"transforms.renameTopicToIndex.replacement": "test_similar3"


text:
Q: hive record inserted but then get a error I create a table in hive:
CREATE TABLE `test3`.`shop_dim`  (
    `shop_id`               bigint,
    `shop_name`             string,
    `shop_company_id`       bigint,
    `shop_url1`             string,
    `shop_url2`             string,
    `sid`                   string,
    `shop_open_duration`    string,
    `date_modified`         timestamp)
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe' WITH SERDEPROPERTIES ("path"="hdfs://myhdfs/warehouse/tablespace/managed/hive/test3.db/shop_dim")
STORED AS PARQUET
TBLPROPERTIES ('COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\",\"COLUMN_STATS\":{\"date_modified\":\"true\",\"shop_company_id\":\"true\",\"shop_id\":\"true\",\"shop_name\":\"true\",\"shop_open_duration\":\"true\",\"shop_url1\":\"true\",\"shop_url2\":\"true\",\"sid\":\"true\"}}', 'bucketing_version'='2', 'numFiles'='12', 'numRows'='12', 'rawDataSize'='96', 'spark.sql.create.version'='2.3.0', 'spark.sql.sources.provider'='parquet', 'spark.sql.sources.schema.numParts'='1', 'spark.sql.sources.schema.part.0'='{\"type\":\"struct\",\"fields\":[{\"name\":\"Shop_id\",\"type\":\"long\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Shop_name\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Shop_company_id\",\"type\":\"long\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Shop_url1\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Shop_url2\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"sid\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Shop_open_duration\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"Date_modified\",\"type\":\"timestamp\",\"nullable\":true,\"metadata\":{}}]}', 'totalSize'='17168')
GO

then I insert a record use below sql:
insert into test3.shop_dim values(11,'aaa',22,'11113','2222','sid','opend',unix_timestamp())

I can see the record is inserted,but waited for a long time,there is error:
>[Error] Script lines: 1-2 --------------------------
 Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.StatsTask

 [Executed: 2018-10-24 下午12:00:03] [Execution: 0ms]

I use aqua studio as a tool.Why this error occur?

A: This issue can happen if the values being inserted are not matching to the expected type.
In your case "date_modified" column is of timestamp type, but unix_timestamp() will return bigint (current Unix timestamp in seconds).
If you execute the query
select unix_timestamp();

Output would be like : 1558547043
Instead, you need to use current_timestamp.
select current_timestamp;

Output would be like : 2019-05-22 17:50:18.803
You can refer Hive manual for in-built date functions at https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

A: Below given hive setting can help resolve org.apache.hadoop.hive.ql.exec.StatsTask (state=08S01,code=1)
set hive.stats.column.autogather=false; or set hive.stats.autogather=false
set hive.optimize.sort.dynamic.partition=true;


text:
Q: Triple weighted sum I was trying to vectorize a certain weighted sum but couldn't figure out how to do it. I have created a simple minimal working example below. I guess the solution involves either bsxfun or reshape and kronecker products but I still have not managed to get it working.
rng(1);
N = 200;
T1 = 5;
T2 = 7;
T3 = 10;

A = rand(N,T1,T2,T3);
w1 = rand(T1,1);
w2 = rand(T2,1);
w3 = rand(T3,1);

B = zeros(N,1);

for i = 1:N
 for j1=1:T1
  for j2=1:T2
   for j3=1:T3
    B(i) = B(i) + w1(j1) * w2(j2) * w3(j3) * A(i,j1,j2,j3);
   end
  end
 end
end

A = B;

For the two dimensional case there is a smart answer here.

A: You can use an additional multiplication to modify the w1 * w2' grid from the previous answer to then multiply by w3 as well. You can then use matrix multiplication again to multiply with a "flattened" version of A.
W = reshape(w1 * w2.', [], 1) * w3.';
B = reshape(A, size(A, 1), []) * W(:);

You could wrap the creation of weights into it's own function and make this generalizable to N weights. Since this uses recursion, N is limited to your current recursion limit (500 by default).
function W = createWeights(W, varargin)
    if numel(varargin) > 0
        W = createWeights(W(:) * varargin{1}(:).', varargin{2:end});
    end
end

And use it with:
W = createWeights(w1, w2, w3);
B = reshape(A, size(A, 1), []) * W(:);

Update
Using part of @CKT's very good suggestion to use kron, we could modify createWeights just a little bit.
function W = createWeights(W, varargin)
    if numel(varargin) > 0
        W = createWeights(kron(varargin{1}, W), varargin{2:end});
    end
end

A: This is the logic behind it:
ww1 = repmat (permute (w1, [4, 1, 2, 3]), [N, 1,  T2, T3]);
ww2 = repmat (permute (w2, [3, 4, 1, 2]), [N, T1, 1,  T3]);
ww3 = repmat (permute (w3, [2, 3, 4, 1]), [N, T1, T2, 1 ]);

B = ww1 .* ww2 .* ww3 .* A;
B = sum (B(:,:), 2)

You can avoid permute by creating w1, w2, and w3 in the appropriate dimension in the first place. Also you can use bsxfun instead of repmat as appropriate for extra performance, I'm just showing the logic here and repmat is easier to follow.
EDIT: Generalised version for arbitrary input dimensions:
Dims   = {N, T1, T2, T3};  % add T4, T5, T6, etc as appropriate
Params = cell (1, length (Dims));

Params{1} = rand (Dims{:});
for n = 2 : length (Dims)
  DimSubscripts = ones (1, length (Dims));  DimSubscripts(n) = Dims{n};
  RepSubscripts = [Dims{:}];  RepSubscripts(n) = 1;
  Params{n} = repmat (rand (DimSubscripts), RepSubscripts);
end

B = times (Params{:});
B = sum (B(:,:), 2)

A: Again, you couldn't generalize this that well for N-D unless you made some function to construct the Kronecker product vector, but how about
  A = reshape(A, N, []) * kron(w3, kron(w2, w1));

A: If we're going the route of having functions anyway, and are favoring performance over elegance/brevity, then consider this:
function B = weightReduce(A, varargin)

    B = A;
    for i = length(varargin):-1:1
        N = length(varargin{i});
        B = reshape(B, [], N) * varargin{i};
    end

end

This is the performance comparison I see:
tic;
for i = 1:10000
    W = createWeights(w1,w2,w3);
    B = reshape(A, size(A,1), [])*W(:);
end
toc
Elapsed time is 0.920821 seconds.
tic;
for i = 1:10000
    B2 = weightReduce(A, w1, w2, w3);
end
toc
Elapsed time is 0.484470 seconds.


text:
Q: Would it be possible to create functional, object oriented or declarative architectures? My question originates from the fact that the most common architectures are inherently imperative (i.e. the machine language is imperative).
Would it be possible to create a computer architecture that is fundamentally functional, object oriented or declarative (or any other programming paradigm)? If so, would it be helpful?

A: There are graph reduction CPUs like SKIM, GRIP, and perhaps most widely known, the Reduceron. (The Reduceron's instruction set is basically a subset of Haskell, i.e. a lazy functional language. It also has garbage collection in hardware.)
The FLEET and EDGE architectures focus heavily on communication. In the beginning of computing, computation was expensive, but communication (on the CPU) was practically free. Nowadays, it's the opposite: CPUs can compute insanely fast, it's moving the signals around the CPU that's the problem. But we can't influence communication: we can only tell the CPU to compute, communication on the CPU will happen as a side-effect of that, outside of our control. The FLEET architecture turns this upside down: you only tell the data where to go, computation happens as a side-effect of that.
The Azul Vega-3 CPU has a fairly traditional 3-address RISC instruction set, but its implementation is heavily optimized for object-oriented languages with dynamic polymorphism. So, it's not an object-oriented CPU, but it is a CPU optimized for object-orientation. E.g. OO code has much less locality of time and locality of space than ADT code. But most modern CPUs depend on temporal and spatial locality for a lot of their optimizations. These optimizations are mostly useless for OO languages, though. For example, memory prefetching to prevent cache misses. The Vega, instead of trying to prevent cache misses, reduces the cost of a cache miss by having an insane amount of memory bandwidth and a very sophisticated memory controller. (After all, the cost of cache misses is #misses * cost(miss), and bringing down either will reduce the total cost.) On a Vega system, you can have tens of thousands of cache misses in flight, and still make progress with your computation.


text:
Q: Updating my Android app doesn't work, makes the app crash. Completely reinstall works. Seems to be common. Is there a solution? Whenever I build a new version of my Android app and install it, it doesn't really make a completely new installation (uninstall and reinstall) it kind of patches the previous version I made. When I launch the app it just crashes.
Then I manually completely uninstall my app and then reinstall it from zero. In this case it works like a charm. The problem is that I'm worried about how will this affect the distribution of my app and automatic updates. Is there a solution?
What I'm doing is this: I have my app, let's say v 3.1, I build the v 3.2 then copy the apk into my phone and execute it. It updates... Then, the app crashes on start. Then if I completely uninstall the app and then run the apk file of that very same version v 3.2 it works fine. I don't know why that happens

A: As far as crash is concerned you need to print the log , to know why it is exactly crashing, it could be due to some variable on your launcher screen which gets NPE may be because it is getting cleared. Since the package name of application is same it will obviously work in similar manner as you mentioned. Crash must not be due to reinstall of application.Till you find out the reason for crash it will not be possible to tell that exactly how it is going to affect your application.But it is never ok to distribute app which is crashing in any manner.


text:
Q: Firestore get subcollection data with promises I'm trying to get the data from my subcollections, the things is I need to do it with Promises (If I don't, I can't get the data from the cache)
Here how I am actually doing :

        bookStores = db.collection("bookstores");
        bookStores.onSnapshot((snapshot) => {
          snapshot.docChanges().forEach((change) => {
             bookStoresIds.push(change.doc.id); // I use a list so a can iterate on IDs for subs
             // Doing stuff
          });

          bookStoresIds.forEach(bookStoreId => {
            const task = db.collection('bookstores').doc(bookStoreId).collection('books')
            task.onSnapshot((snapshotTask) => {
              snapshotTask.docChanges().forEach((change) => {
                // Doing stuff
              });
            });
          })

I use a list to store the IDs. This version works, but causes me some troubles and I want to use Promises.
Here what I tried :

async function getBookStores(id,) {
  const bookStoreIds: string[] = [];

  db.collection("bookStores").onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
    snapshot.docChanges().forEach((change) => {
     // Doing Stuff

    });
  });
  return bookStoreIds;
}

async function getBooks(bookStoreIds) {
  bookStoreIds.forEach(bookStoreId => {
    const book = db.collection('bookStores').doc(bookStoreId).collection('books')
    task.onSnapshot({ includeMetadataChanges: true }, (snapshotTask) => {
      snapshotTask.docChanges().forEach((change) => {
        // Doing Stuff
      });
    })
  })
}

getBookStores(id)
        .then((list) => {
          return getBooks(list);
        })

The problem is, when it cames to getBooks, the list is empty ... Is somebody have an idea ?


text:
Q: MQ JMS Message ID returns no text message and how to write the MQ JMSCorrelationID in proper format I tested a standalone JMS client passing a TextMessage to a queue on IBM MQ, and I got the below message id with error:

ID:414d51204243573032413154202020205bc6bd3e25423865
java.lang.RuntimeException: no text message

*

*I sent a TextMessage with This is for Test, but why didn't I receive a TextMessage? There were no other messages in the queue before this code ran.

*In case text message success how to read the message Id  (send request MessageID  and reply message Id) in readable format in Java. Is any thing I need to change in the below code.

TextMessage textMessage = queueSession.createTextMessage("This is for Test");
textMessage.setJMSReplyTo(queue);
textMessage.setJMSType("mcd://xmlns");//message type
textMessage.setJMSExpiration(2*1000);//message expiration
textMessage.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
queueSender = queueSession.createSender(queueSession.createQueue(outputQName));
queueSender.setTimeToLive(2*1000);
queueSender.send(textMessage);

String jmsCorrelationID = " JMSCorrelationID = '" + textMessage.getJMSMessageID() + "'";
while (true) {
    Message message = queueReceiver.receive(60*1000);
    if (! (message instanceof TextMessage))
        throw new RuntimeException("no text message");
    TextMessage tm = (TextMessage) message;
    System.out.println("Message:"+tm.getText());
}

A: In your request-reply use-case the kind of message the requesting client sends has no direct bearing on the kind of message it will receive. The kind of message the requesting client receives depends on what the responding client sends.
As for getting the message ID as a String from the IBM MQ implementation you can refer to this answer.

A: Could this simply be that your message is expiring from the queue?
I see you set the message expiry to 2 seconds.  Many replying applications will copy the remaining expiry value to the reply message.  So if the app that reads the request and sends you the reply does not read your request within 2 seconds from the time it was sent, or if it does and replies with the remaining expiry and the reply does not make it back to be consumed by you, it would disappear from the queue.
Try increasing the expiry time to a higher value.

Also note you are setting the same expiry value via two different methods, one is meant to be a default for all messages sent by the producer and the other is a per message setting.
This sets a default expiry on all messages sent by the producer:
queueSender.setTimeToLive(2*1000);

This sets the expiry on the specific message you are sending and would override the queueSender.setTimeToLive, so you only need one of these lines.
textMessage.setJMSExpiration(2*1000);//message expiration

A: Is your session transactional?
If yes then your message is not "visible" on the queue until the transaction is "commit" and you never commit...
I'm curious to know what is the content ofmessage when you test its class..is it null?
Does the receivereturn immediately or only after the timeout expired (in your case 60*1000ms)?
Denis


text:
Q: I want to setup Active directory in Ubuntu server for mix environmet (Windows/linux) to authenticate I want to migrate my all windows Server and workstation to linux system (Ubuntu server 12.04). I am new to Linux.
I want to create Active directory for my Linux (Ubuntu) as well as Windows Workstations to work parallel (Some system will have Ubuntu workstation and some Windows 7).
Now i need assistance to which application would help me to achieve this and what would be the perquisite. Needed best procedure to install and maintain the Ubuntu server.
I hope you understand my requirement.
Thanks & Regards,
Sam

A: Here are some resources I have found that may be of help to you. According to these, there are several different options but most of them center around the use of Samba4 with OpenLDAP.
http://linuxdrops.com/install-samba-4-on-centos-rhel-fedora-debian-ubuntu/
http://www.ittables.com/2013/06/samba-4-active-directory-configuration.html


text:
Q: How can I check if a string contains only a particular set of special characters in Javascript? This question provides a solution to match special characters and numbers.
What should be the regular expression that I need to use to match only a particular set of special characters in Javascript?
For instance, I want to check if a string contains anything other than following special characters ~!@#$.
I've tried the below code, but I'm not sure if it is correct:
var myRegex = \~!@#\;
var testString = "!!@@ABCD[]";  // This contains [], so it must be false
if(myRegex.test(testString))
{
   //do something
}

Do let me know the reason for downvoting so that I can avoid my mistakes in the future.
Downvoting without any reason won't help either of us to learn anything. Thanks.

A:
I want to check if a string contains anything other than following special characters ~!@#$

You can try below regex
^[^~!@#$]+$

Pattern explanation:
  ^                        the beginning of the line
  [^~!@#$]+                any character except:
                           '~', '!', '@', '#', '$'
                           (1 or more times )
  $                        the end of the line

Learn more... about character sets


text:
Q: Can I keep my stuff in New Game+? Assassin Creed Odyssey has a very huge map and so many places to go, so many choices and different endings.
I was wondering if in NG+ I can keep my inventory and stay at my high level. I mean, if I want to play it again, I won't have enough free time to play my other games.
Is it possible to keep everything, or should I save my games at specific times to get back?
My Alexios is mean and angry; I wonder if I can save more lives if my new choices make him soft and friendly.

A: As described here you keep your current level and all your stuff but start the story again with the map reset.
What carries over:

*

*Your level and mastery levels

*Your unlocked abilities

*All of your weapons and armour

*Your ship upgrades

*Your ship cosmetics

*Any ship lieutenants that you acquired from the in-game store/Ubisoft Club

*All of your resources, including orichalcum

*All of your drachmae

What doesn't carry over:

*

*Story progression

*Quest progression

*Map markers

*Location completion

*Cultist progression


text:
Q: Magento 2.3.1 Not install sample data, need CMS code for LUMA home page If we see from the demo here: http://demo-acm-2.bird.eu
There's banners and featured product at Home CMS which i don't get because sample data isn't installed
Is there another way to get the CMS code needed on this one page?

A: Not easily no.
My best advice would be to install sample data on another dev store and then manually transfer across what you need.


text:
Q: Conditional Field Selection I have data like this
id | bookDate   | regisDate  | payDate    | status
1  | 2001-12-31 | 2002-12-31 | 2003-12-31 | 1
2  | 2001-12-31 | 2002-12-31 | 2003-12-31 | 2
3  | 2001-12-31 | 2002-12-31 | 2003-12-31 | 3

and i want the result is like this
id | date | status
x  | x    | x

notice date field is reduced from 3 into 1 field. and the conditional is like this. if the status is 1 then take date from bookDate, if 2 take from regisDate, if 3 take from payDate
example for data with id 1, then the result of query will be like this
id | date       | status
1  | 2001-12-31 | 1

it is possible do that in MySQL query?

A: You have case statements in MySQL.
SELECT id,
 CASE status
  WHEN 1 THEN bookDate
  WHEN 2 THEN regisDate
  WHEN 3 THEN payDate
 END
 AS date,
 status
 FROM table

A: SELECT id,
    CASE status
    WHEN 1 THEN bookDate
    WHEN 2 THEN regisDate
    WHEN 3 THEN payDate END as Date,
    Status
FROM YourTable;


text:
Q: Laravel 5.2 & Postman GET Requests are not passing $request->send() I'm having some difficulty with sending a simple GET request via Postman (An application extension in google chrome) to my Laravel 5.2 server. Here are some details to what I'm doing:
Route here:

Next is the code containing the route
Code here (within the laravel routes.php file):

Finally the error that gets thrown
Error Here

I've gone through multiple tutorials (if resources are needed I will post them on request) and videos and yet I think I may have overlooked something. I've even dived into the source code of Laravel's Route handler but it doesn't even get to the method:
     $request->send();

located within the public\index.php file on line 56.
When I perform the:
 php artisan route:list

I get the following response:
+--------+----------+-----------------------+------+--------------------------------------------------------+-----------------------------------+
| Domain | Method   | URI                   | Name | Action                                         | Middleware  |
+--------+----------+-----------------------+------+------------------------------------------------------------------------------+-------------+
|        | POST     | here                  |      | Closure                                        | web         |
|        | GET|HEAD | user/:id/validate|    | \Controllers\UserController@getOAuthValidation | web,api  |
+--------+----------+-----------------------+------+--------------------------------------------------------+-----------------------------------+

If ANYONE can shed some light on this I would greatly appreciate it.

A: strange. Your routes file is /user/validate but your route is expecting an id.
I'm assuming that the validate method requires an id field in its signature?
Remove that, or change your postman get to /user/1/validate


text:
Q: Batch : Dynamic variable name (eval equivalent) I have a variable containing the name of an environnent variable. I would like to eval this value. For example:
:: TOTO_1_2 defined outside of batch file
set varName="TOTO_1_2"
echo %TOTO_1_2% :: Display env var
echo %%varName%% :: Broken

The idea is to pass the value of the env var pointed by varName to a command then.
Thank you

A: if you want to evaluate a evaluated variable, you have to parse it twice:
There are different possibilities to do that. Here are three of them:
@echo off
SET TOTO_1_2=hello
set "varName=TOTO_1_2"
echo 0: %TOTO_1_2%
call echo 1: %%%varName%%%

setlocal enabledelayedexpansion
for %%i in (%varname%) do echo 2: !%%i!
echo 3: !%varName%!


text:
Q: Angular Cli Req Node version ^14.15 I have global cli v 12.1 and local version 12.1
5th row from end told that i need version >=14.0.0
But When i try to ng serve or ng v i got:
Node.js version v14.3.0 detected.
The Angular CLI requires a minimum Node.js version of either v12.14 or v14.15.

Please update your Node.js version or visit https://nodejs.org/ for additional instructions.

@angular/cli package.json (from node modules, package-lock told same):
{
  "name": "@angular/cli",
  "version": "12.1.0",
  "description": "CLI tool for Angular",
  "main": "lib/cli/index.js",
  "bin": {
    "ng": "./bin/ng"
  },
  "keywords": [
    "angular",
    "Angular CLI",
    "devkit",
    "sdk",
    "Angular DevKit",
    "angular-cli"
  ],
  "scripts": {
    "postinstall": "node ./bin/postinstall/script.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/angular/angular-cli.git"
  },
  "author": "Angular Authors",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/angular/angular-cli/issues"
  },
  "homepage": "https://github.com/angular/angular-cli",
  "dependencies": {
    "@angular-devkit/architect": "0.1201.0",
    "@angular-devkit/core": "12.1.0",
    "@angular-devkit/schematics": "12.1.0",
    "@schematics/angular": "12.1.0",
    "@yarnpkg/lockfile": "1.1.0",
    "ansi-colors": "4.1.1",
    "debug": "4.3.1",
    "ini": "2.0.0",
    "inquirer": "8.1.1",
    "jsonc-parser": "3.0.0",
    "npm-package-arg": "8.1.5",
    "npm-pick-manifest": "6.1.1",
    "open": "8.2.1",
    "ora": "5.4.1",
    "pacote": "11.3.4",
    "resolve": "1.20.0",
    "semver": "7.3.5",
    "symbol-observable": "4.0.0",
    "uuid": "8.3.2"
  },
  "ng-update": {
    "migrations": "@schematics/angular/migrations/migration-collection.json",
    "packageGroup": {
      "@angular/cli": "12.1.0",
      "@angular-devkit/architect": "0.1201.0",
      "@angular-devkit/build-angular": "12.1.0",
      "@angular-devkit/build-webpack": "0.1201.0",
      "@angular-devkit/core": "12.1.0",
      "@angular-devkit/schematics": "12.1.0"
    }
  },
  "engines": {
    "node": "^12.14.1 || >=14.0.0",
    "npm": "^6.11.0 || ^7.5.6",
    "yarn": ">= 1.13.0"
  }
}