text:
Q: Precise Definition of $\mathbb{E}[X\mid \sigma(A)]$ Conditional Expectation of Random Variable given Sigma Algebra generated by a set I want to define precisely, exhaustively and constructively the conditional expectation of a random variable given the sigma algebra generated by a set. This question has some discussion on it but the definition is not made explicit.
Set Up
Let $(\Omega, \mathcal{F}, \mathbb{P})$ be a probability space, $(\mathsf{E}, \mathcal{E})$ be a measurable space (Banach space should be enough) and $X:\Omega\to\mathsf{E}$ be a random variable whose expectation exists and $\mathbb{E}[|X|] < \infty$. Let $\mathsf{A}\in\mathcal{F}$ be an event and define the sigma algebra generated by it as
$$
\sigma(\mathsf{A}) := \{\emptyset, \Omega, \mathsf{A}, \mathsf{A}^c\}.
$$
The conditional expectation $\mathbb{E}[X\mid \sigma(\mathsf{A})]:\Omega\to\mathsf{E}$ is a $\sigma(\mathsf{A})$-measurable random variable such that
$$
\int_\mathsf{B} X(\omega) \mathbb{P}(d\omega) = \int_\mathsf{B}\mathbb{E}[X\mid \sigma(A)](\omega) \mathbb{P}(d\omega) \qquad\qquad\forall\, \mathsf{B}\in\{\emptyset, \Omega, \mathsf{A}, \mathsf{A}^c\}. \qquad\qquad (*)
$$
I would like to construct this random variable. For instance, when $\mathsf{A} = \Omega$ and $\sigma(\mathsf{A}) = \{\emptyset, \Omega\}$ then it's easy to show that the constant random variable $Y(\omega) = \mathbb{E}[X]$ does the job. When $\mathsf{A}\neq \Omega$ things get a bit more complicated. We aim means that to find a version of $\mathbb{E}[X\mid \sigma(\mathsf{A})]$, that is a random variable $Y:\Omega\to\mathsf{E}$ that is $\sigma(\mathsf{A})$-measurable and satisfies $(*)$. I cannot show that either holds (constructively). Even simply showing measurability is tricky because I don't know how to construct this random variable.
Measurability
Most measure theory books define the conditional expectation $\mathbb{E}[X\mid \mathsf{A}]$ to be a number, typically
$$
\mathbb{E}[X \mid \mathsf{A}] = \begin{cases}
    \displaystyle \frac{1}{\mathbb{P}(\mathsf{A})}\int_\mathsf{A} X(\omega) \mathbb{P}(d\omega) & \text{ if } \mathbb{P}(\mathsf{A}) > 0 \\
    \text{any value in } \mathsf{E} & \text{ if } \mathbb{P}(\mathsf{A}) = 0.
\end{cases}
$$
My guess is that this number must appear somewhere in our definition of the random variable $Y(\omega) = \mathbb{E}[X\mid \sigma(\mathsf{A})](\omega)$. Recall that for $Y(\omega)$ to be $\sigma(\mathsf{A})$-measurable we require that for any $\mathsf{C}\in\mathcal{E}$
$$
Y^{-1}(\mathsf{C}) \in \{\emptyset, \Omega, \mathsf{A}, \mathsf{A}^c\}.
$$
Now when $\mathbb{P}(\mathsf{A}) > 0$ then one has that $Y^{-1}(\mathsf{C})\in\sigma(\mathsf{A})$ because
$$
Y^{-1}(\mathsf{C}) = \{\omega\in\Omega\,:\, \mathbb{E}[X\mid \mathsf{A}]\in\mathsf{C}\} = \begin{cases}
    \emptyset & \text{if } \mathbb{P}(\mathsf{A})^{-1}\mathbb{E}[X 1_\mathsf{A}]\in\mathsf{C}\\
    \Omega & \text{if } \mathbb{P}(\mathsf{A})^{-1}\mathbb{E}[X 1_\mathsf{A}]\notin\mathsf{C}.
\end{cases}
$$
When $\mathbb{P}(\mathsf{A}) = 0$ things get more tricky. Ideally I would want that for any $\mathsf{C}\in\mathcal{E}$ we have that $Y^{-1}(\mathsf{C})$ is either $\mathsf{A}$ or $\mathsf{A}^c$. I cannot seem to find a way of defining $Y$ so that this is true.


text:
Q: Files of build folder in self-published package not consumed by third-party projects Having a problem publishing a package with only build utilities. Being precise: I followed the nuget guideline which files have to be where. So I created a simple [project][2] in which I just want deploy the .props and .targets files in the build folder for third-party projects. When I pack it with dotnet pack Teronis.Packaging.ProjectBuildInPackage.csproj --configuration Release) the .nupkg file does contain all necessary files:
Listing archive: bin\Release\Teronis.Packaging.ProjectBuildInPackage.1.0.0.nupkg

--
Path = bin\Release\Teronis.Packaging.ProjectBuildInPackage.1.0.0.nupkg
Type = zip
Physical Size = 3027

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2020-01-11 18:13:12 .....          533          297  _rels\.rels
2020-01-11 18:13:12 .....          696          358  Teronis.Packaging.ProjectBuildInPackage.nuspec
2020-01-11 17:03:22 .....          435          208  build\Teronis.Packaging.ProjectBuildInPackage.props
2020-01-11 11:28:08 .....         1188          532  build\Teronis.Packaging.ProjectBuildInPackage.targets
2020-01-11 18:13:12 .....          534          219  [Content_Types].xml
2020-01-11 18:13:12 .....          735          413  package\services\metadata\core-properties\3bab4543af344c95ae6210e86f61f55a.psmdcp
------------------- ----- ------------ ------------  ------------------------
2020-01-11 18:13:12               4121         2027  6 files

When I add this package (nuget add bin/Release/Teronis.Packaging.ProjectBuildInPackage.1.0.0.nupkg -Source "C:\Users\<user>\.nuget\packages") to my local feed, after I have deleted it of course, and let a sample project with customized feed sources include that specific package, the generated obj/project.assets.json will not contain the .props and .targets files it should:
{
  "version": 3,
  "targets": {
    ".NETStandard,Version=v2.0": {
      "Microsoft.NETCore.Platforms/1.1.0": {
        ...
      },
      "NETStandard.Library/2.0.3": {
        ...
      },
      // ###############################################
      "Teronis.Packaging.ProjectBuildInPackage/1.0.0": {
        "type": "package"
        // Here should the .props and .targets files be referenced
      },
      "Test.Localization/1.0.0": {
        ...
      }
    }
  },
  "libraries": {
    "Microsoft.NETCore.Platforms/1.1.0": {
      ...
    },
    "NETStandard.Library/2.0.3": {
      ...
    },
    // ###############################################
    "Teronis.Packaging.ProjectBuildInPackage/1.0.0": {
      "sha512": "vKfduDW8+hIYQ1s6zFO0EnCmJTSVGAzsvcDDM2YIEiIqksGX1WO/ERMvAkXmJR2Q0x92wFk+z0i448HuYmUWSQ==",
      "type": "package",
      "path": "teronis.packaging.projectbuildinpackage/1.0.0",
      "files": [
        ".nupkg.metadata",
        // Here are the .props and .targets files missing
        "teronis.packaging.projectbuildinpackage.1.0.0.nupkg.sha512",
        "teronis.packaging.projectbuildinpackage.nuspec"
      ]
    },
    "Test.Localization/1.0.0": {
      "type": "project",
      "path": "../../Teronis.DotNet/src/Packaging/ProjectBuildInPackage/test/Test.Localization/Test.Localization.csproj",
      "msbuildProject": "../../Teronis.DotNet/src/Packaging/ProjectBuildInPackage/test/Test.Localization/Test.Localization.csproj"
    }
  },
  "projectFileDependencyGroups": {
    ...
  },
  "packageFolders": {
    "C:\\Users\\<user>\\.nuget\\packages\\": {},
    "C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder": {}
  },
  "project": {
    "version": "2.0.0",
    "restore": {
      "projectUniqueName": "C:\\Users\\<user>\\source\\repos\\Teronis.Packaging.ProjectBuildInPackage.Test\\Teronis.Packaging.ProjectBuildInPackage.Test\\Teronis.Packaging.ProjectBuildInPackage.Test.csproj",
      "projectName": "Teronis.Packaging.ProjectBuildInPackage.Test",
      "projectPath": "C:\\Users\\<user>\\source\\repos\\Teronis.Packaging.ProjectBuildInPackage.Test\\Teronis.Packaging.ProjectBuildInPackage.Test\\Teronis.Packaging.ProjectBuildInPackage.Test.csproj",
      "packagesPath": "C:\\Users\\<user>\\.nuget\\packages\\",
      "outputPath": "C:\\Users\\<user>\\source\\repos\\Teronis.Packaging.ProjectBuildInPackage.Test\\Teronis.Packaging.ProjectBuildInPackage.Test\\obj\\",
      "projectStyle": "PackageReference",
      "fallbackFolders": [
        "C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
      ],
      "configFilePaths": [
        "C:\\Users\\<user>\\source\\repos\\Teronis.Packaging.ProjectBuildInPackage.Test\\NuGet.Config",
        "C:\\Users\\<user>\\AppData\\Roaming\\NuGet\\NuGet.Config",
        "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
      ],
      "originalTargetFrameworks": [
        "netstandard2.0"
      ],
      "sources": {
        "C:\\Users\\<user>\\.nuget\\packages": {},
        "https://api.nuget.org/v3/index.json": {}
      },
      "frameworks": {
        "netstandard2.0": {
          "projectReferences": {
            "C:\\Users\\<user>\\source\\repos\\Teronis.DotNet\\src\\Packaging\\ProjectBuildInPackage\\test\\Test.Localization\\Test.Localization.csproj": {
              "projectPath": "C:\\Users\\<user>\\source\\repos\\Teronis.DotNet\\src\\Packaging\\ProjectBuildInPackage\\test\\Test.Localization\\Test.Localization.csproj"
            }
          }
        }
      },
      "warningProperties": {
        "warnAsError": [
          "NU1605"
        ]
      }
    },
    "frameworks": {
      "netstandard2.0": {
        "dependencies": {
          "NETStandard.Library": {
            "suppressParent": "All",
            "target": "Package",
            "version": "[2.0.3, )",
            "autoReferenced": true
          },
          "Teronis.Packaging.ProjectBuildInPackage": {
            "include": "Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
            "suppressParent": "All",
            "target": "Package",
            "version": "[1.0.0, )"
          }
        },
        "imports": [
          "net461",
          "net462",
          "net47",
          "net471",
          "net472",
          "net48"
        ],
        "assetTargetFallback": true,
        "warn": true,
        "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\3.1.100\\RuntimeIdentifierGraph.json"
      }
    }
  }
}

The package in a sample project is referenced as
  <ItemGroup>
    <PackageReference Include="Teronis.Packaging.ProjectBuildInPackage" Version="1.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

So it should include the build assets. I think it has something to do with the supported frameworks as this package should be supported for every framework/"framework" like netcore, netcoreapp, net, netstandard, and so on.
It should be said, that when creating the package the nuget analyzer does complain about
1>------ Build started: Project: Teronis.Packaging.ProjectBuildInPackage, Configuration: Release Any CPU ------
1>Teronis.Packaging.ProjectBuildInPackage -> C:\Users\<user>\source\repos\Teronis.Packaging.ProjectBuildInPackage\Teronis.Packaging.ProjectBuildInPackage\bin\Release\netstandard2.0\Teronis.Packaging.ProjectBuildInPackage.dll
1>Successfully created package 'C:\Users\<user>\source\repos\Teronis.Packaging.ProjectBuildInPackage\Teronis.Packaging.ProjectBuildInPackage\bin\Release\Teronis.Packaging.ProjectBuildInPackage.1.0.0.nupkg'.
1>C:\Program Files\dotnet\sdk\3.1.100\Sdks\NuGet.Build.Tasks.Pack\build\NuGet.Build.Tasks.Pack.targets(198,5): warning NU5128: Some target frameworks declared in the dependencies group of the nuspec and the lib/ref folder do not have exact matches in the other location. Consult the list of actions below:
1>C:\Program Files\dotnet\sdk\3.1.100\Sdks\NuGet.Build.Tasks.Pack\build\NuGet.Build.Tasks.Pack.targets(198,5): warning NU5128: - Add lib or ref assemblies for the netstandard2.0 target framework
1>Done building project "Teronis.Packaging.ProjectBuildInPackage.csproj".
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

Even when I know how to fix it by just creating lib/netstandard2.0/_._ it does not solve my problem, that the .props and .targets files are not taken up by the nuget target that creates obj/project.assets.json intermediately.

A: After a little journey I found the solution. So there were two issues to solve.
First the source path: Do not use any nuget cache as feed source. Here for me (nuget locals all -list):
http-cache: C:\Users\<user>\AppData\Local\NuGet\v3-cache
global-packages: C:\Users\<user>\.nuget\packages\
temp: C:\cygwin64\tmp\NuGetScratch
plugins-cache: C:\Users\<user>\AppData\Local\NuGet\plugins-cache

The command nuget add .. does not fully "install" it, it won't unzip the assets (build, buildMultiTargeting, lib, ..) of .nupkg-file in its resprective folder (<local-nuget-source-folder>/<package-id>/<package-version>/). So the .props and .targets files will not be included by those projects who installed them. But when you specify another source location, add the package to it and then install it in a project, the package will be cached with its unzipped assets and the project will include them in obj\project.assets.json, yay.
The second issue belongs to the complain from the nuget analyzer. So, if I convert the .csproj to a .nuspec that would look like
<?xml version="1.0" encoding="utf-8"?>
<package >
  <metadata>
    <id>Teronis.Packaging.ProjectBuildInPackage</id>
    <version>1.0.0</version>
    <title>*not in use*</title>
    <authors>*not in use*</authors>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <summary>*not in use*</summary>
    <description>*not in use*</description>
    <copyright>*not in use*</copyright>
    <tags>*not in use*</tags>
    <developmentDependency>true</developmentDependency>
  </metadata>
  <files>
    <file src="build\*" target="build" />
    <file src="buildMultiTargeting\*" target="buildMultiTargeting" />
  </files>
</package>

it won't complain about anything when packing it with nuget pack. Why is that so? When packing with dotnet pack (we use it because of .csproj file) it will also try to pack the symbols by default, but when the packing does erronous cancel, it won't tell you that, instead it annoys you with C:\Program Files\dotnet\sdk\3.1.100\Sdks\NuGet.Build.Tasks.Pack\build\NuGet.Build.Tasks.Pack.targets(198,5): error NU5017: Cannot create a package that has no dependencies nor content., but the .nupkg (not .snupkg) is already created. So you have to specify <IncludeSymbols>false</IncludeSymbols> to accomplimish a non-canceled build.
So for a fully only-build-files package, you would have a .csproj file like that:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <Description>Allows project reference content to be added to the packing parent nuget package.</Description>

    <!-- We don't build a executable package.
         We build an only-build-time package. -->
    <SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
    <DevelopmentDependency>true</DevelopmentDependency>
    <IncludeBuildOutput>false</IncludeBuildOutput>
    <IncludeSymbols>false</IncludeSymbols>
  </PropertyGroup>

  <ItemGroup>
    <None Include="build\**" Pack="true" PackagePath="build\" />
    <None Include="buildMultiTargeting\**" Pack="true" PackagePath="buildMultiTargeting\" />
  </ItemGroup>

</Project>

The .props and .targets files in buildMultiTargeting are just importing the .props and .targets files in build\.
Cheers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shell Script for renaming and relocating the files I am working on something and need to solve the following. I am giving a analogous version of mine problem.
Say we have a music directory, in which there are 200 directories corresponding to different movies. In each movie directory there are some music files.
Now, say a file music.mp3 is in folder movie.mp3 . I want to make a shell script such that it renames the file to movie_music.mp3 and put it in some folder that I mention to it. Basically, all the files in the subdirectories are to be renamed and to be put in a new directory.
Any workaround for this?

A: This script receives two arguments: the source folder and the destination folder. It will move every file under any directory under the source directory to the new directory with the new filename:
#!/bin.sh
echo "Moving from $1 to $2"
for dir in "$1"/*; do
  if [ -d "$dir" ]; then
    for file in "$dir"/*; do
      if [ -f "$file" ]; then
        echo "${file} -> $2/`basename "$dir"`_`basename "${file}"`"
        mv "${file}" "$2"/`basename "$dir"`_`basename "${file}"`
      fi
    done
  fi
done

Here is a sample:

bash move.sh dir dir2
Moving from dir to dir2
dir/d1/f1 -> dir2/d1_f1
dir/d1/f2 -> dir2/d1_f2
dir/d2/f1 -> dir2/d2_f1
dir/d2/f2 -> dir2/d2_f2

A: Bash:
newdir=path/to/new_directory;
find . -type d |while read d; do
  find "$d" -type f -maxdepth 1 |while read f; do
    movie="$(basename "$d" |sed 's/\(\..*\)\?//')"
    mv "$f" "$newdir/$movie_$(basename $f)";
  done;
done

A: Assuming the following directory tree:
./movie1:
movie1.mp3

./movie2:
movie2.mp3

The following one-liner will create 'mv' commands you can use:
find ./ | grep "movie.*/" | awk '{print "mv "$1" "$1}' | sed 's/\(.*\)\//\1_/'

EDIT:
If your directory structure contains only the relevant directories, you can expand use the following grep instead:
grep "\/.*\/.*"

Notice it looks file anything with at least one directory and one file. If you have multiple inner directories, it won't be good enough.


text:
Q: R Conditionally Merge Rows I have a very large database (with thousands of questions) from a forum where people answer questions and their answers are accepted or not. If someone answers more than once I need to combine their answers and put them at the first time they answered.  Here is a made up example of what I'm dealing with

Here is the dataframe
        df1 <- data.frame(
          questionID = c(1,1,1,1,2,2,2),
          userID = c(101, 101, 101, 102, 102,103,102),
          accepted=c(0,0,1,0,0,1,0),
          answer=c('text1','text2','text3','text4','text5','text6','text7'),
          time=c('12:00','12:30',"1:00","1:30","2:00","2:30","3:00"))

Since userID (101) answered question ID (1) 3 times, and the third answer was accepted, I need to concatenate the answers and put this at the earliest time (which is 12:00). The same thing for userID(102) who answered twice and neither was accepted. The result would be like this (with the output dataframe):

     out <- data.frame(
        questionID = c(1,1,2,2),
        userID = c(101, 102, 102,103),
        accepted=c(1,0,0,1),
        answer=c('text1+text2+text3','text4','text5+text7','text6'),
        time=c('12:00',"1:30","2:00","2:30"))

I've seen some solutions for problems like this but none appear to address this precise situation. Is there some way to do this in R?

A: We could summarise by pasteing the 'answer' into a single string, while getting the last of 'accepted' and first 'time' value after doing a group by
library(dplyr)
library(stringr)
df1 %>%
    group_by(questionID, userID) %>%
    summarise(accepted = last(accepted),
              answer = str_c(answer, collapse="+"),
              time = first(time))
# A tibble: 4 x 5
# Groups:   questionID [2]
#  questionID userID accepted answer            time
#       <dbl>  <dbl>    <dbl> <chr>             <fct>
#1          1    101        1 text1+text2+text3 12:00
#2          1    102        0 text4             1:30
#3          2    102        0 text5+text7       2:00
#4          2    103        1 text6             2:30

Or using data.table
library(data.table)
setDT(df1)[, .(accepted = last(accepted),
   answer = paste(answer, collapse= "+"), time = first(time), .(questionID, userID)]

A: I think any answer can be accepted (not only the last one), so using data.table, we can do
library(data.table)

setDT(df1)[,.(accepted = +any(accepted == 1),answer = paste(answer, collapse = "+"),
          time = first(time)), .(questionID, userID)]

#   questionID userID accepted            answer  time
#1:          1    101        1 text1+text2+text3 12:00
#2:          1    102        0             text4  1:30
#3:          2    102        0       text5+text7  2:00
#4:          2    103        1             text6  2:30


text:
Q: Can't netboot a PowerMac G4 I'm trying to install Debian (by net booting off tftp) on my old Mac Mini G4. I get into OpenFirmware (option-cmd-o-f after boot chime) and enter:
boot my.mac.ip.address,yaboot

After I hit enter this appears for a split second:

Then I am stuck at this screen:


text:
Q: Re-use rules and avoid CyclicGraphException with snakemake I'm writing a pipeline in which a first mapping of reads on a reference genome results in a sam file (rule map_on_genome), and then in a sorted and indexed bam file (rule sam2indexedbam). After processing this bam file (rule small_RNA_seq_annotate), I extract some reads that I would like to re-map again on the same genome with the same parameters. I also trim extra nucleotides from reads that did not map during the first mapping (rule extract_nomap_siRNAs), and I would like to try to map the resulting trimmed reads again similarly.
Ideally, the rules map_on_genome and sam2indexedbam would therefore be used a first time before small_RNA_seq_annotate and extract_nomap_siRNAs and then again on the output of these rules.
In my attempt to do so, a wildcard I name read_type was supposed to help snakemake make the difference between the first mapping and the other, but apparently I failed because I end up getting the following error:
Cyclic dependency on rule sam2indexedbam.

What is the recommended way to achieve what I want (i.e. avoid code duplication)?

Example
I tried to reproduce the error in a simplified version of my real pipeline. Here is an example that results in CyclicGraphException:
rule all:
    input:
        expand("results/{read_type}_on_genome_sorted.bam", read_type=["reads", "nomap_siRNA", "piRNA", "siRNA", "miRNA"]),

def source_fastq(wildcards):
    if wildcards.read_type == "nomap_siRNA":
        return rules.extract_nomap_siRNA.output.fastq
    elif wildcards.read_type == "piRNA":
        return rules.small_RNA_seq_annotate.output.pi_fastq
    elif wildcards.read_type == "siRNA":
        return rules.small_RNA_seq_annotate.output.si_fastq
    elif wildcards.read_type == "miRNA":
        return rules.small_RNA_seq_annotate.output.mi_fastq
    elif wildcards.read_type == "reads":
        return "data/reads.fastq"
    else:
        raise NotImplementedError("Unknown read type: %s" % wildcards.read_type)

rule map_on_genome:
    input:
        source_fastq
    output:
        sam = "results/{read_type}_on_genome.sam",
        nomap = "results/{read_type}_nomap.fastq"
    shell:
        """
        touch {output}
        """

rule extract_nomap_siRNA:
    input:
        rules.map_on_genome.output.sam
        #"results/reads_nomap.fastq"
    output:
        fastq = "results/{read_type}_unmapped_siRNA.fastq"
    shell:
        """
        touch {output}
        """

rule sam2indexedbam:
    input:
        rules.map_on_genome.output.sam
    output:
        "results/{read_type}_on_genome_sorted.bam"
    shell:
        """
        touch {output}
        """

rule small_RNA_seq_annotate:
    input:
        "results/reads_on_genome_sorted.bam"
    output:
        pi_fastq = "results/piRNA.fastq",
        si_fastq = "results/siRNA.fastq",
        mi_fastq = "results/miRNA.fastq"
    shell:
        """
        touch {output.pi_fastq}
        touch {output.si_fastq}
        touch {output.mi_fastq}
        """

Solution
If I change the input of rule extract_nomap_siRNA to a hard-coded file path instead of the output of the map_on_genome rule, the error disappears.
I suppose this hard-coding breaks the cyclic dependency.


text:
Q: How to define specific actions for each item in a listview Well, so my listview has some rows and in these there's a text view that has to be modified by two buttons that also are in the row. The text view is a number (0) and one button increments this number and another one decreases it.
The problem is that when I increment or decrease the number of one of the items in my list, this number doesn't stay in its row and moves to the others when I scroll up and down. If you didn't understand this, here's a video of what happens: https://drive.google.com/open?id=11UYnu-sebZcbUIiG9oLoXtF8UeP1PAuv
So, how could I make that these numbers stay in their place? This is the code
CartListActivity.java

public class CartListActivity extends AppCompatActivity {

    ListView userList;
    UserCustomAdapter userAdapter;
    ArrayList<User> userArray = new ArrayList<User>();

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

        /**
         * add item in arraylist
         */
        userArray.add(new User("Olives verdes", "1,20€", "Aperitius", "0"));
        userArray.add(new User("Olives negres", "1,30€", "Aperitius", "0"));
        userArray.add(new User("Cogombrets", "1,80€", "Aperitius","0"));
        userArray.add(new User("Patates Lay's", "1,19€", "Aperitius","0"));
        userArray.add(new User("Potet", "0,95€", "Bebè","0"));
        userArray.add(new User("Biberó", "3,85€", "Bebè","0"));
        userArray.add(new User("Tovalloletes", "1,10€", "Bebè","0"));
        userArray.add(new User("Perxes de nadó", "1,95€", "Bebè","0"));
        /**
         * set item into adapter
         */
        userAdapter = new UserCustomAdapter(CartListActivity.this, R.layout.view_row,
                userArray);
        userList = (ListView) findViewById(R.id.listView);
        userList.setItemsCanFocus(false);
        userList.setAdapter(userAdapter);
        /**
         * get on item click listener
         */
        userList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    final int position, long id) {
                Log.i("List View Clicked", "**********");
                Toast.makeText(CartListActivity.this,
                        "List View Clicked:" + position, Toast.LENGTH_LONG)
                        .show();
            }
        });

    }

}

User.java

public class User {
    String name;
    String price;
    String category;
    String quantity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String address) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public User(String name, String address, String location, String quantity) {
        super();
        this.name = name;
        this.price = price;
        this.category = category;
        this.quantity = quantity;
    }

}

UserCustomAdapter.java

public class UserCustomAdapter extends ArrayAdapter<User> {
    Context context;
    int layoutResourceId;
    ArrayList<User> data = new ArrayList<User>();

    public UserCustomAdapter(Context context, int layoutResourceId,
                             ArrayList<User> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        UserHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new UserHolder();
            holder.textName = (TextView) row.findViewById(R.id.textView1);
            holder.textPrice = (TextView) row.findViewById(R.id.textView2);
            holder.textCategory = (TextView) row.findViewById(R.id.textView3);
            holder.textQuantity = (TextView) row.findViewById(R.id.quantityTxt);
            holder.btnEdit = (Button) row.findViewById(R.id.button1);
            holder.btnDelete = (Button) row.findViewById(R.id.button2);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
        }
        User user = data.get(position);
        holder.textName.setText(user.getName());
        holder.textPrice.setText(user.getPrice());
        holder.textCategory.setText(user.getCategory());
        final UserHolder finalHolder = holder;
        holder.btnEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String value1 = finalHolder.textQuantity.getText().toString();
                int a = Integer.parseInt(value1);

                if(a <= 99) {
                    int sum = a + 1;

                    Log.i("Edit Button Clicked", "**********");
                    finalHolder.textQuantity.setText(Integer.toString(sum));
                }
            }
        });
        holder.btnDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                    String value2 = finalHolder.textQuantity.getText().toString();
                    int a = Integer.parseInt(value2);

                    if(a > 0) {
                        int substract = a - 1;
                        Log.i("Delete Button Clicked", "**********");
                        finalHolder.textQuantity.setText(Integer.toString(substract));
                    }
            }
        });
        return row;

    }

    static class UserHolder {
        TextView textName;
        TextView textPrice;
        TextView textCategory;
        TextView textQuantity;
        Button btnEdit;
        Button btnDelete;
    }
}

A: You need to set the userQuantity at each call of getView and update your the value of quantity in the User object when edit or delete is clicked. Add the lines like below:
    final User user = data.get(position);   // CHANGE TO FINAL
    holder.textName.setText(user.getName());
    holder.textPrice.setText(user.getPrice());
    holder.textCategory.setText(user.getCategory());
    holder.textQuantity.setText(user.getQuantity()); // ADD THIS LINE
    final UserHolder finalHolder = holder;
    holder.btnEdit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String value1 = finalHolder.textQuantity.getText().toString();
            int a = Integer.parseInt(value1);

            if(a <= 99) {
                int sum = a + 1;

                Log.i("Edit Button Clicked", "**********");
                user.setQuantity(Integer.toString(sum)); // ADD THIS LINE
                finalHolder.textQuantity.setText(Integer.toString(sum));
            }
        }
    });
    holder.btnDelete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                String value2 = finalHolder.textQuantity.getText().toString();
                int a = Integer.parseInt(value2);

                if(a > 0) {
                    int substract = a - 1;
                    Log.i("Delete Button Clicked", "**********");

                     user.setQuantity(Integer.toString(subtract)); // ADD THIS LINE

                 finalHolder.textQuantity.setText(Integer.toString(substract));
                }
        }
    });


text:
Q: How can I do an AJAX request with an authenticated user in Django? I need to do an HTTP call using AJAX with an already authenticated user using Django.
Is there any standard simple way to do this? I've read this other question but uses a different technology.
I'm using HTTP (not HTTPS) and using a third-party app like django-tastypie for this unique "simple" purpose would be overkill, wouldn't it?

A: Ajax requests are no different from any other kind of request. If the user is already authenticated, then the Ajax request will be authenticated too: the session cookie which identifies the user will be sent along with the Ajax request just as it would be with any other one.
(That linked question is irrelevant because it is talking about authenticating the user within the request, not using an already-authenticated user as you want.)

A: For this, you would simple make an AJAX call to your URL, and in the view that handles the URL, you would add the @login_required decorator. For some reason, the django project is down right now, so I will send you to another place where you can get the information.
However, you will need to watch out for a few things, one is that you need to add the CSRF token, and secondly you will need to make a few changes in the SETTINGS.PY file.
I think the video covers it all, sorry I cannot send you to the official docs, because it seems to be down at the moment.


text:
Q: Cypress preventing API call from finishing I have a weird issue. I have a page that is sending an API (I'm using both async/await and $.ajax().then for testing).
On its own, it's working perfectly fine, with the code after the await and in the then firing. However, it doesn't work when running through Cypress. Although the network tab shows that the API has succeed, none of the code continue running, meaning that both of the console.log never gets called.
Originally, I was doing to intercepting to stub the API so I thought that's the issue, but now, removing that .intercept also do nothing. Where should I start looking?
Some related code:
//testing
describe('The feature', () => {
before(() => {
    cy.loginAsAdmin();
    // 01-Aug-2021
    cy.clock(1627740000000);
    cy.visit('/dataChecking');
});

beforeEach(() => {
    Cypress.Cookies.preserveOnce('PHPSESSID');
    cy.reload();
});

after(() => {
    cy.clearCookies();
});

describe.only('when no data is return', () => {
    it('will show no error box', () => {
        cy.intercept(
            'POST',
            '/dataChecking/forStore',
            // {
            //  body: {
            //      data: [],
            //  },
            //  delay: 5000,
            // },
        ).as('api');

        cy.get('#store-id').type('1');
        cy.get('#submitBtn').click();

        cy.wait('@api').then(() => {
            cy.get('#no-error-message').should('be.visible');
        });
    });
});

});
// Page code
$.ajax({
        url: '/dataChecking/forStore',
        method: 'POST',
        data: {
            storeId,
            from: from.toString(),
            to: to.toString(),
        },
    }).then((msg) => {
        console.log(msg);
    });

    const { data } = await $.ajax({
            url: '/dataChecking/forStore',
            method: 'POST',
            data: {
                storeId,
                from: from.toString(),
                to: to.toString(),
            },
        });
    console.log('hello');

API in network tab

A: Intercept need the url to match
it('will show no error box', () => {

  cy.intercept('POST', '/dataChecking/forStore').as('api')

  cy.get('#store-id').type('1');
  cy.get('#submitBtn').click();

  cy.wait('@api').then(() => {
    cy.get('#no-error-message').should('be.visible');
  });
});

or you might need
cy.intercept('POST', '**/dataChecking/forStore').as('api')


text:
Q: Issue with the jquerymodal.com control I'm trying to make use of the really cool Jquery Modal framework, which can be found here. I've done the first step and nothing happens. Maybe I'm just stupid, but the jquerymodal.com site says it's as easy as the following:
<!DOCTYPE html>

</style>

Thanks for clicking.  That felt good.  Close or press ESC

Open Modal

When I launch my HTML page and click the "Open Modal" link, it does nothing. Nothing happens in any browser. Even if I host it in IIS and run it from VS as an admin. And yes, of course, I have placed the JqueryModal js and project zip files into the same directory as my HTML file. But, that said... there's no WAY the developer of this framework was negligent enough to publish his files without testing them. So what in the world am I doing wrong??? Can someone please slap me in the face and spell it out for me?

A: The below works fine for me. I included jQuery library and the CSS file for jQuery modal to make it work.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.8.2/jquery.modal.min.css" />

Thanks for clicking. That felt good. Close or press ESC

Open Modal

A: Now I see the comment in the sample code "Don't forget to include jquery". LOL. I blew it :)


text:
Q: Problems with Xtext in eclipse I'm working on a Java project in eclipse. Trying to open a file through Ctrl+Mouse click, I got a popup that asked me if I want to add "Xtext nature to my project". I said ok. And now, I tried to put on a CSS file the following line:

@import "myfile.css";

as first line. But I get this error, because of Xtext Check (fast):

missing EOF at ';'.

Can anybody help me on how to deal with this kind of error?
Thanks.

A: You have two ways to solve this issue:

*

*First, you could uninstall the plug-in contributing the CssDsl editor. A quick Google search told me that it is contributed by the e(fx)Eclipse plugins. To uninstall a plug-in, go to the About dialog, click on the Installation details feature, and in the upcoming dialog you could look for the feature to uninstall.

*If the previous solution does not work for you (e.g. you need the e(fx)Eclipse environment), you have to change the default file associations to avoid opening css files with the Xtext-based editor, and remove the Xtext nature from the projects you added.

*

*Setting file associations: open Eclipse Preferences, navigate to the General->Editors -> File Associations page, where you can look for the CSS extension, and select a different default editor for it.

*Removing the Xtext nature: you can right click on your project, and select Configure -> Remove Xtext nature. If that does not work for some reason, you have to open the hidden .project file, and remove the <nature>org.eclipse.xtext.ui.shared.xtextNature</nature> entry and the corresponding org.eclipse.xtext.ui.shared.xtextBuilder buildCommand manually.

A: I had the same error, when I was creating CSS via New -> Other... -> Web -> CSS File.
Zoltan's solutions did not work, but when I create the file with New -> File and name it *.css the error did not occur.


text:
Q: Git: how to exclude a subfolder in a repository? I have created a repository in a folder with my project, you know, git init, I have the Webstorm folder .idea and another one not related to this, I am not interested in keeping in the repository, and I don't want this folder to appear even as new files to add.
I want to forget about these subfolders.

*

*How can I exclude this subfolder before committing the whole repository?

*How can I exclude this subfolder after committing the whole repository?

A: Open the .git/info/exclude file in a text editor and add the folder to ignore. This file remains private to you. You can also create a .gitignore file in the repository's root directory, outside the .git directory and write the folder entry there. Then add this file to the repository to share with others what content should be ignored, should others have this directory-to-ignore in their repository too.
If you already committed this directory then just remove it with git rm -r --cached, commit the deletion and mark the directory ignored as I described above. You might want to make a backup of the directory before you wipe it.


text:
Q: Format a PayPal account to not take e-checks? How do you configure a paypal account to NOT accept e-checks? Is this something that I adjust in my PP panel or can I send it in code when I make my "Buy Now" buttons?

A: You'll find the option in: Profile - Preferences - Selling Preferences.
The only stipulation is that Paypal won't let you refuse eCheques from eBay users.


text:
Q: Can't set image URI because Permission Denial: opening provider Good afternon,
I crate an app with Room database to save items (name, desc, price, image). I have 3 activities. The 1st activity for create, the 2nd MainActivity with RecyclerView and the last activity (ChangeActivity) open when I click on item in MainActivity. When I create an item I pick image and save uri in database. I want to set image in ImageView in ChangeActivity but get
Unable to start activity ComponentInfo {hop.test.aah/hop.test.aah.ChangeActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{7a3e034 25078:hop.test.aah/u0a95} (pid=25078, uid=10095) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs.
I tried some solutions what I found but nothing help or maybe I wrong and it is why I ask some help.
ChangeActivity:
In manifest I only add READ_EXTERNAL_PERMISSION and WRITE_EXTERNAL PERMISSION.
This is how I pick image:
UPD 2:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val resolver = applicationContext.contentResolver
        val flags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION
         resolver.takePersistableUriPermission(image!!, flags)
and fun to get
@Throws(IOException::class)
    fun getBitmapFromUri(uri: Uri): Bitmap {
        val parcelFileDescriptor: ParcelFileDescriptor? =
            contentResolver.openFileDescriptor(uri, "r")
        val fileDescriptor: FileDescriptor = parcelFileDescriptor!!.fileDescriptor
        val image: Bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor)
        parcelFileDescriptor.close()
        return image
    }

A: This works for me:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/jpeg"
        startActivityForResult(
            Intent.createChooser(
                intent,
                getString(R.string.chooser_title)
            ), RC_GALLERY)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RC_GALLERY) {
                imgUri = data?.data

                val contentResolver = applicationContext.contentResolver
                val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION

                imgUri?.let { contentResolver.takePersistableUriPermission(it, takeFlags) }
            }
        }
    }

A: Step #1: Switch to ACTION_OPEN_DOCUMENT.
Step #2: In onActivityResult(), when you get the Uri, call takePersistableUriPermission() on a ContentResolver
Then, and only then, will you be able to save the Uri in a database and use it to access content in the future.
With your current approach, the Uri works for the activity that receives the onActivityResult() call, but it will not work for future processes.


text:
Q: How to redirect powershell.exe OUPUT and ERROR to two separate files? I need to redirect the STDERR and STDOUT to two separate files.
I tried the following:

*

*This will output error only to an error file:
powershell.exe -file c:\test.ps1 2> test.txt

*This will output all output to a result file:
powershell.exe -file c:\test.ps1 2>&1> test.txt

My question is how can I redirect STDERR and STDOUT to two separate files by running powershell.exe just once?

A: You can specify multiple redirections. Ex.
powershell.exe -file Sample.ps1 2>errors.txt 1>output.txt

Sample.ps1
Write-Error "This is a critial error"
Write-Output "This is output"
"This is also output"

Errors.txt
C:\Users\frode\Desktop\Sample.ps1 : This is a critial error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Untitled202.ps1

Output.txt
This is output
This is also output


text:
Q: ios10.0 system jump to the system settings, the system set the interface appears flash back My problem is more than ios10.0 system jump to the system settings, the system set the interface appears flash back, but app itself is nothing, the problem is the occasional appearance, I use the xcode8.1. puzzled me for a long time, hope to get the answer.

I am here to jump to the system settings interface is configured in the project.

My code is like the above figure.


text:
Q: Changing background of link when clicked using jQuery I have 4 links with background color that I need to be changed when I click, I use this code to change the background :
jQuery:
$(document).ready(function() {
  $('#content_area').load($('.pm_class:first').attr('href'));

  $('.pm_class').click(function() {
    var href = $(this).attr('href');
    $(this).css('background-color', '#3B581E');
    $(this).css('color', '#fff');
    $('#content_area').hide().load(href).fadeIn('normal');
    return false;
  });
});

The issue is: when I click a different link the css in my jQuery is still applied to the previous link I clicked along with the second one. I need the first to return to the original state as shown in the image below. I need it to return back to be like the "send message" and "archive" links :
jQuery issue

A: You could change the style of all .pm_class elements back to the original, and then change the styles of this to the new style:
$('.pm_class').click(function() {
    var href = $(this).attr('href');
    $(".pm_class").css({
        backgroundColor: "oldColor",
        color: "oldColor"
    });
    $(this).css({
        backgroundColor: "#3B581E",
        color: "#fff"
    });
    $('#content_area').hide().load(href).fadeIn('normal');
    return false;
});

Note that I've consolidated your calls to the css method into one, as it will accept an object representing a map of CSS properties and values as an argument.

A: JS functions are objects, and can be assigned member variables.  These work like what in some C like languages is called a "static" local variable, meaning it retains its value between invocations.
$('pm_class').click(function () { switchBG($(this)) });

function switchBG (elem) {
    if (switchBG.prev) {
        switchBG.prev.css('background', '#ffffff');
    }
    elem.css('background', '#ffff00');
    switchBG.prev = elem;
}

You could do the same thing with a global, but this is tidier.


text:
Q: What does all capitalized Function name means in WinAPI? Informs the provider that a directory enumeration is starting
`
PRJ_START_DIRECTORY_ENUMERATION_CB PrjStartDirectoryEnumerationCb;

HRESULT PrjStartDirectoryEnumerationCb(
  const PRJ_CALLBACK_DATA *callbackData,
  const GUID *enumerationId
)
{...}

`
I am confused how to use this function.

A: You're looking at a callback (a generic programming concept, not specific to Win32), which is usually a reference to a function that you have to write yourself. In order to have the C/C++ compiler check that you've defined your callback function correctly, and to simplify usage of such callbacks, a typedef is often used. The Win32 API often uses all caps to define types of callbacks. In this case, PRJ_START_DIRECTORY_ENUMERATION_CB is the type of the function pointer (a pointer to the callback function that you have to write), and it is defined in projectedfslib.h as:
typedef
_Function_class_(PRJ_START_DIRECTORY_ENUMERATION_CB)
HRESULT
(CALLBACK PRJ_START_DIRECTORY_ENUMERATION_CB)(
    _In_ const PRJ_CALLBACK_DATA* callbackData,
    _In_ const GUID* enumerationId
    );

This definition has a lot of excess stuff in it that helps the Microsoft toolset validate various things related to the usage of this type of function pointer. When writing your own function that works for this type of callback, you don't necessarily have to repeat a lot of the things that are used in the typedef. The MSDN documentation for callbacks often shows an example of how you would write the method signature for your callback, and that example is usually simplified to strip off the excess stuff that the toolset needs, leaving the stuff the developer needs to define when writing their callback.
In this case, the example function is called PrjStartDirectoryEnumerationCb, but there is no function defined with that name. It's up to you to define a function that looks like what you see on MSDN. It doesn't have to have the same name -- you can name it whatever you like, and then you use your function's name anywhere the callback is needed.
HRESULT MyCallback(const PRJ_CALLBACK_DATA *callbackData, const GUID* enumerationId)
{
     // implement your callback here
}


text:
Q: Java Large File Upload throws java.io.IOException: Map failed I am using Spring and Hibernate and try to upload large file but when i try to upload
more then 150 Mb then it is generating error like
Caused by: java.lang.OutOfMemoryError: Map failed
at sun.nio.ch.FileChannelImpl.map0(Native Method)
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:755)
... 157 more

I am using windows 64bit OS. After lots of googling i find that this is bug available in JDK.
Can any one help me to solve this issue?
Some one write about this issue https://github.com/MLCL/Byblo/issues/78. but i am not sure this is bug or not. if bug then how can i resolve it. It any other appropriate solution for this.

A: Increase your JVM heap size?
-Xmx1024m


text:
Q: Getting error while installing pysqlite I am trying to install pysqlite, but getting the below error-
running install
running build
running build_py
creating build
creating build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\pysqlite2
copying lib\dbapi2.py -> build\lib.win-amd64-2.7\pysqlite2
copying lib\dump.py -> build\lib.win-amd64-2.7\pysqlite2
copying lib\__init__.py -> build\lib.win-amd64-2.7\pysqlite2
creating build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\dbapi.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\dump.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\factory.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\hooks.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\regression.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\transactions.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\types.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\userfunctions.py -> build\lib.win-amd64-2.7\pysqlite2\test
copying lib\test\__init__.py -> build\lib.win-amd64-2.7\pysqlite2\test
creating build\lib.win-amd64-2.7\pysqlite2\test\py25
copying lib\test\py25\py25tests.py -> build\lib.win-amd64-2.7\pysqlite2\test\py25
copying lib\test\py25\__init__.py -> build\lib.win-amd64-2.7\pysqlite2\test\py25
running build_ext
building 'pysqlite2._sqlite' extension
error: Unable to find vcvarsall.bat

I have tried pip also.. but no luck !!
Can anyone please suggest the how to trace this error ? Thanks !

A: You will ned to use a compiled binaries, you can download yours here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pysqlite
Keep in mine that this is an Unofficial Windows Binaries, but it is works for me.


text:
Q: Labels placement in ArcGIS I need all labels to be placed outside of the boundary (polyline features).  Most of the labels are placed outside the boundary line, while others (marked with red color) are placed inside the boundary.
What is the best way place all labels on the outside of the polyline?

A: The most simple solution may be to convert to graphics and manually re-position the offending labels.

A: Convert your polylines to a polygon and then adjust the label placement properties to 'Outside the Feature'.


text:
Q: How to identify company/domain with new OAuth2 authentication? I'm converting an existing Google Apps Marketplace app to support OAuth2.
I understand the use of access keys to identify the user account but how can this be used to link a user to a 'company' or 'domain'?
Our app supports having multiple user logins under one business account - we need to be able to identify what company a user belongs to using OAuth2. How can this be done? (we're using C#).
Is there an additional user API that needs to be called after initial authentication, if so, which one? (we're using C#).


text:
Q: Разные варианты вызова операторов из функций-членов Есть ли разница, каким образом вызывать операторы класса из функций-членов? Например
(*this)(x);
this->operator()(x);
operator()(x);

Если да, то что лучше использовать?

A: Есть или нет разницы - зависит от контекста. Если задаться целью, то можно "высосать из пальца" пример, на котором будут наблюдаться некоторые различия
template <typename T> struct B
{
  void operator()(int) {}
};

template <typename T> struct D : B<T>
{
  void foo()
  {
    (*this)(42);          // OK
    this->operator()(42); // OK
    D::operator()(42);    // OK
    operator()(42);       // ERROR
  }
};

int main()
{
  D<int> d;
  d.foo();
}

В данном примере вызов operator()(42) не скомпилируется по причинам, которые не имеют отношения к операторам. В то же время варианты с this и с квалифицированным именем будут работать без проблем.


text:
Q: JAXB Unmarshaling unsuccessful using jersey I have the following class which represents a POJO object
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

// Class to marshall and unmarshall the XML to POJO

 // This is a class for the request XML

@XmlRootElement
public class KeyProvision {

    private String Consumer ;
    private String API ;
    private String AllowedNames ;

    public void setConsumer( String Consumer)
    {
        this.Consumer= Consumer;

    }

    public void setAPI( String API){

        this.API = API;

    }

    public void setAllowedNames(String AllowedStoes){

        this.AllowedNames = AllowedNames;

    }

    @XmlElement
    public String  getConsumer(){

        return Consumer;
    }

    @XmlElement
    public String getAPI(){

        return API;
    }

    @XmlElement
    public String getAllowedNames(){

        return AllowedNames;
    }

}

A function from my class to which requests are mapped
@POST
 @Path("/request")
 @Consumes(MediaType.APPLICATION_XML)
 public Response getRequest(KeyProvision keyInfo){

    /* StringReader reader = new StringReader(keyInfo); // this code just leads to an execution failure for some reason
     try{
         JAXBContext jaxbContext = JAXBContext.newInstance(KeyProvision.class);

         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
         KeyProvision api = (KeyProvision) jaxbUnmarshaller.unmarshal(reader);
         System.out.println(api);

     }   catch(JAXBException e){
         e.printStackTrace();

     }
      */

     String result = "Track saved : " + keyInfo;
     return Response.status(201).entity(result).build() ;

  //   return "success" ;

 }

if I change
 public Response getRequest(KeyProvision keyInfo)

to
public Response getRequest(String keyInfo)

I can see that the request is accepted but not stored as a POJO object .
if I leave it as  public Response getRequest(KeyProvision keyInfo) , I get a 400 error with the following message <u>The request sent by the client was syntactically incorrect.</u> in my REST client when I try making the request.
this is my request body:
<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>

What am I missing here that is preventing a successfull Unmarshalling from XML to POJO

A: By JAXB defaults naming rules it will expect the element names to start with lower case. You will need to specify the names on @XmlRootElement and @XmlElement to match your document.
@XmlRootElement(name="KeyProvision")
public class KeyProvision {

And
@XmlElement(name="Consumer")
public String  getConsumer(){

JAXB Debugging Trick
When unmarshal isn't working correctly try populating the object model and marshalling it out to see the expected document structure.


text:
Q: Does the Amazon SQS Queue have a specified IP range or subnet? I need to know if the Amazon SQS Queue has a specified IP range or subnet that it lives in. The reason being is my firewall needs an exact range of IPs that it is allowed to connect to.
I found AWS IP address ranges - AWS General Reference in the AWS Docs. SQS Queues are not one of the services that show up on the json file and I am not sure which service it would be under.
What is the best range of IPs that I can use to add to my firewall?
Thanks.

A:
SQS Queues are not one of the services that show up on the json file

Indeed, as shown by parsing the json file:
% curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | .service' | sort -u
AMAZON
AMAZON_APPFLOW
AMAZON_CONNECT
API_GATEWAY
CHIME_MEETINGS
CHIME_VOICECONNECTOR
CLOUD9
CLOUDFRONT
CLOUDFRONT_ORIGIN_FACING
CODEBUILD
DYNAMODB
EBS
EC2
EC2_INSTANCE_CONNECT
GLOBALACCELERATOR
KINESIS_VIDEO_STREAMS
ROUTE53
ROUTE53_HEALTHCHECKS
ROUTE53_HEALTHCHECKS_PUBLISHING
ROUTE53_RESOLVER
S3
WORKSPACES_GATEWAYS

So the best we can do is to figure out which service SQS is classified under. Look up some SQS IPs and correlate them back to the ranges file:
% nslookup sqs.us-west-2.amazonaws.com 1.1.1.1
Server:     1.1.1.1
Address:    1.1.1.1#53

Non-authoritative answer:
sqs.us-west-2.amazonaws.com canonical name = us-west-2.queue.amazonaws.com.
Name:   us-west-2.queue.amazonaws.com
Address: 44.242.184.144

This IP corresponds to a CIDR mask marked as AMAZON back in the ip-ranges.json file:
{
  "ip_prefix": "44.242.184.128/25",
  "region": "us-west-2",
  "service": "AMAZON",
  "network_border_group": "us-west-2"
}

It's not very specific, corresponding to nearly 4600 ipv4 ranges:
% curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select( .service == "AMAZON" ) | .ip_prefix' | wc -l
4592

This is the best I can do with the docs they've given us.


text:
Q: Replace order currency when creating a manual order in Woocommerce admin In WooCommerce, when creating and saving a manual order via Admin, I am trying to replace the order currency value with a custom meta data value (which meta key is _wcj_order_currency)
Here are 2 screenshots of the related meta data (key/value pairs):

*

*The order currency:

*The custom currency (from Booster plugin):

So I would like to replace the order currency EUR to the custom currency USD from _order_currency meta key on save.
References I used:

*

*How can I populate meta fields of a Woocommerce manual order

*WooCommerce admin order edit save post
My code attempt:
// Saving (Updating) or doing an action when submitting
add_action( 'save_post', 'update_order_custom_field_value' );
function update_order_custom_field_value( $post_id ){

    // Only for shop order
 //    if ( 'shop_order' != $_POST[ 'post_type' ] )
    if ( 'shop_order')
        return $post_id;

    // Checking that is not an autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions (for 'shop_manager' and 'administrator' user roles)
    if ( ! current_user_can( 'edit_shop_order', $post_id ) )
        return $post_id;

//Up to above is fine for Admin order

    // Updating custom field data
    if( isset( $_POST['_wcj_order_currency'] ) ) {
        $order = wc_get_order( $post_id );

        // Replacing and updating the value
        update_post_meta( $post_id, '_order_currency', $_POST['_wcj_order_currency'] );
}}

// Testing output in order edit pages (below billing address):
//This displays the existing values well
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_order_custom_field_value' );
function display_order_custom_field_value( $order ){
    echo '
'.__('Order Currency').':
' . get_post_meta( $order->get_id(), '_order_currency', true ) . '
';
    echo '
'.__('Booster Order Currency').':
' . get_post_meta( $order->get_id(), '_wcj_order_currency', true ) . '
';
}

Testing output in order edit pages (below billing address). The code works well.

But I am unable to make it work and update the order currency on order creation.
Any help on this is welcome.

A: To make your script work on new order creation only, try the following revisited code (commented):
// Save order data
add_action( 'save_post_shop_order', 'update_order_currency_on_creation', 1000 );
function update_order_currency_on_creation( $order_id ){
    // Ensure that this is a manual new order
    if( $created = get_post_meta( $order_id, '_created_via', true ) ) {
        return $order_id;
    }

    // Checking that is not an autosave  (not sure that this is really needed on Woocommerce orders)
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return $order_id;
    }

    // Check the user's permissions (for 'shop_manager' and 'administrator' user roles)
    if ( ! current_user_can( 'edit_shop_order', $order_id ) ) {
        return $order_id;
    }

    ## ---- Updating order currency ---- ##

    // Get the WC_Order object
    $order    = wc_get_order($order_id);

    // HERE below the Booster meta key for Order currency
    $meta_key = '_wcj_order_currency';

    // If Booster currency is already in database (in case of, to be sure)
    if ( $value = $order->get_meta($meta_key) ) {
        $order->set_currency( esc_attr($value) );
        $order->save(); // Save order data
    }
    // If not, we get the posted Booster currency value (else)
    elseif ( isset($_POST[$meta_key]) && ( $value = esc_attr($_POST[$meta_key]) ) ) {
        $order->set_currency( esc_attr($_POST[$meta_key]) );
        $order->save(); // Save order data
    }
}

// Testing output in order edit pages (below billing address): This displays the existing values as well.
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_specific_order_details' );
function display_specific_order_details( $order ){
    echo '

'.__('Order Currency').': ' . $order->get_currency() . '

'.__('Booster Order Currency').': ' . $order->get_meta( '_wcj_order_currency' ) . '

';
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


text:
Q: Meteor - Disable autopublish warning Is there a way to disable to Meteor autopublish warning?
I'm just getting in to Meteor again after quite a while and so I'm still learning. I set up a single publish() because I needed it for an onWait in Iron Router. This however triggers a large warning from Meteor:
** You've set up some data subscriptions with Meteor.publish(), but
** you still have autopublish turned on. Because autopublish is still
** on, your Meteor.publish() calls won't have much effect. All data
** will still be sent to all clients.
**
** Turn off autopublish by removing the autopublish package:
**
**   $ meteor remove autopublish
**
** .. and make sure you have Meteor.publish() and Meteor.subscribe() calls
** for each collection that you want clients to see.

which was actually good info... the first time it told me. However, as I'm transitioning, learning and experimenting, I don't necessarily want to remove autopublish.
Every time I make a change and the server restarts, I get this message, which makes it hard to spot when I have an exception thrown or something.
It'd be nice if there was a switch I could set to indicate that I don't want the warning shown. Is there?

A: If you have a look at the source of livedata_server.js, you'll see that publish actually takes three parameters - the last of which is options. You can use the is_auto property of options to trick publish into thinking that your function is part of the autopublish mechanism, which will then cause it to avoid printing the error. For example:
Meteor.publish('messages',
  function() {
    return Messages.find();
  },
  {is_auto: true}
);

Note that you'd need to apply this hack to each of your publishers in order to avoid seeing the warning.


text:
Q: Writing a C++ console application in Code::Blocks and getting a WinMain@16 undefined ref I'm taking a programming 101 class and I have an assignment to do which has me modify the following example files. I'm not asking for help on that part as I think I understand what I have to do to the files. My issue is that the files as given (both typed by hand from the text and copy/pasted directly from the given example files) result in the same error.
As far as I can tell, the example is to setup the header file to be reusable (as headers are). And then to make a call to the header to obtain the course name and insert it into the welcome message.
I'm using Code::Blocks 16.01. I selected the GNU GCC Compiler (C++11) as recommended by the book (a Pearson product). I've set my project up as a console application, and all the other code I have run has been the same type of application and has compiled/worked without error. I have done two examples using the split source code and header file. The last one worked perfectly. So I'm not sure what is wrong.
Build Log
-------------- Build: Debug in PE3-11 (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe  -o bin\Debug\PE3-11.exe obj\Debug\GradeBook.o
C:/Program Files (x86)/CodeBlocks/MinGW/bin/../lib/gcc/mingw32/4.9.2/../../../libmingw32.a(main.o):main.c:(.text.startup+0xa7): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
2 error(s), 0 warning(s) (0 minute(s), 0 second(s))

So two questions:
What is causing the error?
Aren't I supposed to have an int main() somewhere?
GradeBook.h
// Fig. 3.11: GradeBook.h
// GradeBook class definition. This file presents GradeBook's public
// interface without revealing the implementations of GradeBook's member
// functions, which are defined in GradeBook.cpp.
#include <string> // class GradeBook uses C++ standard string class
// GradeBook class definition
class GradeBook
{
public:
   explicit GradeBook( std::string ); // constructor initialize courseName
   void setCourseName( std::string ); // sets the course name
   std::string getCourseName() const; // gets the course name
   void displayMessage() const; // displays a welcome message
private:
   std::string courseName; // course name for this GradeBook
}; // end class GradeBook

GradeBook.cpp
// Fig. 3.12: GradeBook.cpp
// GradeBook member-function definitions. This file contains
// implementations of the member functions prototyped in GradeBook.h.
#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// constructor initializes courseName with string supplied as argument
GradeBook::GradeBook( string name )
   : courseName( name ) // member initializer to initialize courseName
{
   // empty body
} // end GradeBook constructor

// function to set the course name
void GradeBook::setCourseName( string name )
{
   courseName = name; // store the course name in the object
} // end function setCourseName

// function to get the course name
string GradeBook::getCourseName() const
{
   return courseName; // return object's courseName
} // end function getCourseName

// display a welcome message to the GradeBook user
void GradeBook::displayMessage() const
{
   // call getCourseName to get the courseName
   cout << "Welcome to the grade book for\n" << getCourseName()
      << "!" << endl;
} // end function displayMessage

There is a third file, which according to the book is part of a separate exercise, but seems to be related, listed below. The issue there is, aside from a common use of the header, I don't see how these .cpp's link. But it also includes the int main() as I expected. So I'm really confused.
This file also refs the same header (and works fine with just the header in the build/project), but it creates two grade book objects and then tells us it's done so. So I'm not sure what is missing from the previous .cpp to make it work, or how/why it integrates with this one.
// Fig. 3.13: fig03_13.cpp
// GradeBook class demonstration after separating
// its interface from its implementation.
#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// function main begins program execution
int main()
{
   // create two GradeBook objects
   GradeBook gradeBook1( "CS101 Introduction to C++ Programming" );
   GradeBook gradeBook2( "CS102 Data Structures in C++" );

   // display initial value of courseName for each GradeBook
   cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
      << "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
      << endl;
} // end main


text:
Q: TypeError: object.__new__() takes exactly one argument (the type to instantiate) in keras sequential I am currently facing this error while running a pretrained model in spyder.
File "C:\Users\catch\anaconda3\lib\site-packages\keras\engine\sequential.py", line 490, in from_config
TypeError: object.new() takes exactly one argument (the type to instantiate)
enter image description here
Please help me, thanks in advance.


text:
Q: Abbreviated syntax for a C++11 enum class nested in a class? I use a C++11 library which has a header with an enum class nested in a class:
class ClassWithARatherLongName
{
public:
    enum class EnumWithARatherLongName
    {
        VALUE1,
        VALUE2,
        VALUE3
    };
    (other code)
};

Then I use the enumerators in my code:
void foo()
{
    ... ClassWithARatherLongName::EnumWithARatherLongName::VALUE1 ...
}

This works, but is tedious. Isn't there a way to abbreviate the syntax?
Ideally, I would like to be able to write something like:
void foo()
{
    (some directive that allows to use an abbreviated syntax)
    ... VALUE1 ...
}

A: You can use a typedef or using to create a "shortcut":
using E = ClassWithARatherLongName::EnumWithARatherLongName;
E::VALUE1

A: Just add a typedef:
void foo()
{
    typedef ClassWithARatherLongName::EnumWithARatherLongName e;
    e::VALUE1
}

You might be able to shorten the names, by using namespaces.


text:
Q: How to get results from a table and alert them using jQuery I need to write a script to get data from a table and alert them, but I'm not sure how to do that. Right now I only know how to get the button name and alert it. How would I get the data from the table and alert it using jQuery?
 Data:
<button id = 'btnMain'> Click me </button>

 one
 two
 three

 four
 five
 six

 Script:
(function() {
'use strict';

$("#btnMain").click(function(){
var text = document.getElementById("btnMain").innerHTML;
alert(text);
});

})(); //end of (function()

 Result:  Alerts "Click me".
 Need Result:  Alerts "one two three four five six".
I need the results from the TD to be separate, because I'll be needing to assign them to different variables. For example, tr1td1 = one, tr1td2 = two, ect...I will need to use these variables later.

A: You can just loop over the elements like:

$("#btnMain").click(function() {
  $('#resultsTable td').each(function(){
    console.log(this.innerHTML)
  });
});

<button id='btnMain'> Click me </button>

     one
     two
     three

     four
     five
     six

A: A simple iteration of all tds in table would do it.Using the index of row and cell we can store the variables in an 2D array.

function getData() {
  var totalRows = $('#resultsTable tr').length;
  //Initialize your 2D array
  var cellData = [];
  //This step is necessary otherwise cellData[3][1] assign will fail due to undefined error
  //Arbitary 2D array initialization is not possible for this case
  for (var i = 0; i < totalRows; i++) {
    cellData[i] = [];
  }
  var cellText = '';
  $('#resultsTable td').each(function() {
    cellText += $(this).html();
    var rowNum = $(this).parent().index();
    var cellNum = $(this).index();
    //Save data for later use
    cellData[rowNum][cellNum] = $(this).html();
  });
  alert(cellText);
  console.log(cellData);
}

$("#btnMain").click(function() {
  getData();
});

<button id='btnMain'> Click me </button>

     one
     two
     three

     four
     five
     six

A: Try this way.
(function() {
    'use strict';

    $("#btnMain").click(function(){

    var tds = $("#resultsTable td"); // select all tds instead selecting button
    var tableValues = "";

      for(var i=0;i<tds.length; i++) {
        var value = tds.eq(i).text(); // manipulate each value here
        tableValues += " " + value;
        tableValues = tableValues.trim();
      }

      alert(tableValues); // all values separated by space
    });

})(); //end of (function()

To get the results separately, just do
var arrValues = tableValues.split(" "); // it will return a array with all your values

A: this should do it:
var text = document.getElementById("resultsTable");
var arr_of_tr_elements = text.children[0].children;
all = '';
for (var tr of arr_of_tr_elements) {
   for (var td of tr.children) {
      all += td.textcontent;
   }
}
alert (all);


text:
Q: Overriding Mage_Catalog_Model_Product_Type_Price Not Work for Configurable and Downloadable Product I have successfully override Mage_Catalog_Model_Product_Type_Price to edit the getPrice function with this code.
class Myc_Mymodule_Model_Product_Type_Price extends Mage_Catalog_Model_Product_Type_Price
{

    public function getPrice($product)
    {
        return 10;
    }

This works for simple and grouped product, but it's not work for Configurable and Downloadable Product.
But if I edit getPrice function directly in the core file app/code/core/Mage/Catalog/Model/Product/Type/Price.php with the above code, it works for all product.
How this can happen? And how to make it works for all product by overiding Mage_Catalog_Model_Product_Type_Price?

A: The problem is, that this model is only used for grouped and simple products. For configurables another model is used:
class Mage_Catalog_Model_Product_Type_Configurable_Price extends Mage_Catalog_Model_Product_Type_Price

And it extends from Mage_Catalog_Model_Product_Type_Price therefore your change works, if you edit the core file.
I answered here a question how to use an observer to change the price, maybe this helps you:
How to create product price in real time based on forms?


text:
Q: turnoff screenshot in robot framework I have created application in robot framework and want to disable screenshot.
Selenium2Library tried  run_on_failure=Capture Page Screenshot but taking screenshot for success case .
I need to stop taking screenshot for both success and failure case

A: To stop the default behavior of creating a screenshot on a selenium failure, change a flag during the import of the library:
Library    SeleniumLibrary    run_on_failure=NOTHING

And if you want to take away that capability entirely, even when a user calls the corresponding keyword in a case, you can override the keyword to do nothing:
Captures Page Screenshot
    [Documentation]    Not allowed.
    No Operation

With robotframework'scoping rules such keyword will take precedence over the library's one.


text:
Q: Error when editing WordPress Menu with Walker Class I am currently following a YouTube tutorial on how to edit the WordPress Menu.  The tutorial has suggested to include the following code within the 'walker.php' file:
function start_lvl( &$output, $depth ){
        $indent = str_repeat("\t",$depth);
        $submenu = ($depth > 0) ' sub-menu' : '';
        $output .= "\n$indent
\n";
    }

When I do include this code, my website returns an 'HTTP ERROR 500' page.  Through commenting out each line of the code, in a method of elimination fashion, I have isolated the problematic code to:
$submenu = ($depth > 0) ' sub-menu' : '';

I have checked out other similarly titled questions here but unable to work out what the issue could be.  Is anyone able to see where I am going wrong with this particular code?
I am not sure if the HTML Markup plays a role in the error but just in case, here is the code for said markup:
wp_nav_menu()

Link

Link

Link

Link

A: $submenu = ($depth > 0) ' sub-menu' : ''; should be:
$submenu = ($depth > 0)?' sub-menu' : '';
You are missing ? in the shorthand if else condition.


text:
Q: How to automate the response of a google-form? I have to fill almost every day a google-form for my enterprise. The information are already present on my computer, so I have to open a browser and copy and paste the data in the form.
Before I will write a javascript or python-script, which can do this annoying taste for me, I like to know if there is a google solution, like a API?

A: You don't need script to fill out a form with the same data. Google forms has a built in option to pre-populate the contents. Do you have edit access to the form?
From there you can get a URL https://docs.google.com/forms/d/e/FORM_ID/viewform?usp=pp_url&entry.1347905640=Option+1. See how there is a an entry with a number and then the option to fill them in? The entries are listed in the forms markup also. So if you don't have a edit access you can create the URL yourself.
In the Google form editor there is this option.


text:
Q: How to run WMI commands on non-domain-joined server from script running using domain admin credentials I have a windows script running from a scheduled task, set to run with domain credentials.
It checks the disk space on all of my domain joined servers using WMI.
Set wmi = GetObject("winmgmts:\\" & hostname & "\root\cimv2")
...

Set wmiresults = wmi.ExecQuery("SELECT * FROM Win32_LogicalDisk WHERE Name = '" & _
    UCase(diskletter) & ":'")

For Each wmiresult In wmiresults
    ptotalspace = Round(CDbl(wmiresult.Size) / 1073741824, 2)
    pfreespace = Round(CDbl(wmiresult.Freespace) / 1073741824, 2)
Next

This script works fine for all domain joined servers.  But I need to include a non-domain-joined server into this checking, and it fails as the script lacks the necessary permissions on the target server.
I have tried the hacky method of creating a local user account with the same name and password as the domain admin acct, and adding it to local admins, but this didn't work.
Is there a way to allow the script permission to check the server's disks without joining it to the domain, and without having to create a duplicate or version of this script that runs using a local account with permission to perform this check?

A: The solution is here: Connecting to WMI Remotely with VBScript
Look at option 2 under the heading "To connect to a remote system using VBScript". You can use the SWbemLocator.ConnectServer method to pass different credentials to the connection. It looks like this:
strComputer = "Computer_B"
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer(strComputer, _
                                                     "Root\CIMv2", _
                                                     "fabrikam\administrator", _
                                                     "password")

Just replace "fabrikam\administrator" and "password" with a username and password that has permission on that machine. Then you can use that objSWbemServices object the same way you were using your wmi object.
That should work if you run it from a machine inside the domain too... I think. Give it a try.


text:
Q: onReceive does'n work properly I have a download manager that downloads an image on clicking a button. with help of broadcast receivers I will do this.
below is my code:
public void myDownloadManager(){

        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();

                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enqueue);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {

                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
//                            download finished successfully
                            Log.e("count downloads", "counting");
                            db.insertDownloadsRows(image_id);

                        }
                    }
                }
            }
        };

        getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

    public void downloadImage(){

        myDownloadManager();

        dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
        request.setDestinationInExternalPublicDir("some directory", name);
        enqueue = dm.enqueue(request);

    }

and downloadImage() is called in button's onClickListener. when I tap the button for the first time, the image will be downloaded once and the Log message shown up once, for the second time when I tap the button, the image will be downloaded once but the Log message shown up twice, and this happens as much as I tap button. why is it this way? how should it be fixed?

A: That happens because you are registering the receiver multiple times without unregistering it, so you have to do one of two things:
even register the receiver only once like within your onCreate() method for example (which is absolutely the better solution):
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.videoview);

    myDownloadManager();
}

public void downloadImage(){

    dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
    request.setDestinationInExternalPublicDir("some directory", name);
    enqueue = dm.enqueue(request);

}

OR call unregister receiver each time you finish dealing with the downloading file:
public void downloadImage(){

    // Un-registering the receiver
    unregisterReceiver(receiver);

    myDownloadManager();

    dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
    request.setDestinationInExternalPublicDir("some directory", name);
    enqueue = dm.enqueue(request);

}


text:
Q: Nonclustered index uses key into clustered index instead of address? In the documentation for SQL server 2008 R2 is stated:

Wide keys are a composite of several columns or several large-size columns. The key values from the clustered index are used by all nonclustered indexes as lookup keys. Any nonclustered indexes defined on the same table will be significantly larger because the nonclustered index entries contain the clustering key and also the key columns defined for that nonclustered index.

Does this mean, that when there is a search using non-clustered index, than the clustered indes is search also? I originally thought that the non-clustered index contains ditrectly the address of the page (block) with the row it references. From the text above it seems that it contains just the key from the non-clustered index instead of the address.
Could somebody explain please?

A: Yes, that's exactly what happens:

*

*SQL Server searches for your search value in the non-clustered index

*if a match is found, in that index entry, there's also the clustering key (the column or columns that make up the clustered index)

*with that clustered key, a key lookup (often also called bookmark lookup) is now performed - the clustered index is searched for that value given

*when the item is found, the entire data record at the leaf level of the clustered index navigation structure is present and can be returned

SQL Server does this, because using a physical address would be really really bad:

*

*if a page split occurs, all the entries that are moved to a new page would be updated

*for all those entries, all nonclustered indices would also have to be updated

and this is really really bad for performance.
This is one of the reasons why it is beneficial to use limited column lists in SELECT (instead of always SELECT *) and possibly even include a few extra columns in the nonclustered index (to make it a covering index). That way, you can avoid unnecessary and expensive bookmark lookups.
And because the clustering key is included in each and every nonclustered index, it's highly important that this be a small and narrow key - optimally an INT IDENTITY or something like that - and not a huge structure; the clustering key is the most replicated data structure in SQL Server and should be a small as possible.
The fact that these bookmark lookups are relatively expensive is also one of the reasons why the query optimizer might opt for an index scan as soon as you select a larger number of rows - at at time, just scanning the clustered index might be cheaper than doing a lot of key lookups.


text:
Q: Efficient way to compare associative array values without using foreach For an array such as:
$array = array(
    735 => array('name'=>'Alpha', 'num'=>1),
    584 => array('name'=>'Beta', 'num'=>4),
    857 => array('name'=>'Gamma', 'num'=>1),
    982 => array('name'=>'Delta', 'num'=>2)
);

what would be the best way to filter elements with least value of num. That is, in this case, the solution would be the following array:
array(
    735 => array('name'=>'Alpha', 'num'=>1),
    857 => array('name'=>'Gamma', 'num'=>1)
);

I'm aware that this can be done via a foreach loop and keeping track of the least value but I was hoping there would be some array function which would do the job.
My current approach is:
$num_values = array();
foreach($array as $id => $meta)
{
    $num_values[] = $meta['num'];
}
$min_num_value = min($num_values);

$filtered_array = array();
foreach($array as $id => $meta)
{
    if($meta['num'] == $min_num_value)
    {
        $filtered_array[$id] = $meta;
    }
}
print_r($filtered_array);

which, as you can see, is clearly not the best way to go about the task.

A: Optimized version of filtering with minimum value calculation and O(n) complexity.
$array = array(
    735 => array('name'=>'Alpha', 'num'=>1),
    584 => array('name'=>'Beta', 'num'=>4),
    857 => array('name'=>'Gamma', 'num'=>1),
    982 => array('name'=>'Delta', 'num'=>2)
);

$minValue      = PHP_INT_MAX;
$filteredArray = [];
foreach ($array as $key=>$data) {
    $itemNumber = $data['num'];
    if ($itemNumber < $minValue) {
        $filteredArray = [$key => $data];
        $minValue      = $itemNumber;
    } elseif ($itemNumber === $minValue) {
        $filteredArray[$key] = $data;
    }
}

var_dump($filteredArray);

Performance of foreach is better than any array_xxx() functions plus invocation of closures/functions. So, this solution must be efficient even for big arrays.

A: Since min gives only one record you can try like this: It will remove first foreach loop, rest is yours.
$array = array(
        735 => array('name'=>'Alpha', 'num'=>1),
        584 => array('name'=>'Beta', 'num'=>4),
        857 => array('name'=>'Gamma', 'num'=>1),
        982 => array('name'=>'Delta', 'num'=>2)
);
$val = min($array);
$filtered_array=array();
foreach($array as $id => $meta)
{
    if($meta['num'] == $val['num'])
    {
        $filtered_array[$id] = $meta;
    }
}
print_r($filtered_array);

A: this might be help you
$arr = array(
    735 => array('name'=>'Alpha', 'num'=>1),
    584 => array('name'=>'Beta', 'num'=>4),
    857 => array('name'=>'Gamma', 'num'=>1),
    982 => array('name'=>'Delta', 'num'=>2)
);

$inventory = array_map("array_values", $arr);
usort($inventory, function ($item1, $item2) {
    if ($item1[1] == $item2[1]) return 0;
    return $item1[1] < $item2[1] ? -1 : 1;
});

echo "<pre>";print_r($inventory);


text:
Q: Reach the following expression I'm working on this utility function:
$$\ u(x_1,x_2)=(\alpha_1x_1^p+\alpha_2x_2^p)^\left(1/p\right) $$
Where:
$$ 0 < \alpha_1 < 1 ; \alpha_1 + \alpha_2=1;-\infty<p<1 $$
And I have to reach the function:
$$ x_1^* = \frac{m}{p_1+p_2(\frac{p_i}{\alpha_1})^\frac{-1}{p-1}(\frac{p_2}{\alpha_2})^\frac{1}{p-1}} $$
I'm trying to solve it by Lagrangian Multiplier method but after divide the derivatives of $x_1$ and $x_2$ and equalizing them to $\frac{p_1}{p_2}$ I'm completely lost.


text:
Q: Load deafult image if Image.asset not found the image I am trying to load an image with this code
CircleAvatar(
    child: Image(
    image: getImage(snapshot.value['img']),
    ),
),

but if the image is not founded I want to replace it with a default image and I try this code
AssetImage getImage(String image) {
    AssetImage img;
    try {
        img = AssetImage('images/${widget.categoria}/$image.png');
    } catch (e) {
        img = AssetImage('images/non_disp_big.png');
    }
    return img;
}

I allready add all images dependencies in pubspec.yaml
I just wanna replace the image with a default if not found it in the folder
This is the error:
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: images/produzioni-tipiche/biplano.png

When the exception was thrown, this was the stack:
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
#2      AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
#3      ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: AssetImage(bundle: null, name: "images/produzioni-tipiche/biplano.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#15081(), name: "images/produzioni-tipiche/biplano.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════

A: you should just return a string for the image asset inside your CircleAvatar widget like the code below:
CircleAvatar(
            child: Image(
          image: AssetImage(getImage(snapshot.value['img'])),
        ))

the method returns a string now:
String getImage(String image) {
    String img;
    try {
      img = 'images/${widget.categoria}/$image.png';
    } catch (e) {
      img = 'images/non_disp_big.png';
    }
    return img;
  }

A: I know this is an old question, but the best way is user errorBuilder function that Image.asset provides and load for alternative widget.
 CircleAvatar(
      child: Image.asset(getImage(snapshot.value['img']),
      errorBuilder: ((context, error, stackTrace) => const Image.asset('images/non_disp_big.png')),
    )),


text:
Q: How to interpret this jnettop output? Looks like I'm currently under a DOS attack or something like that, I've been monitoring the traffic on the server using jnettop, this is a of what I see during normal conditions:
http://imgur.com/xozMvz9
and this is an example of when the issue is happeing:
http://imgur.com/AEgW5he
SO my question is: what does that "IP" in protocol and also "0" in port means????
I replaced the ip of my server with: 1.1.1.1 to make it more readable. Of course this is just an entry of the output, in nomral operation the list has many more entries, and when I'm under the attack, also I see several entries with the same HUGE RX and 0 TX, so the solution is not just block that IP in the example.

A: Could be that the attackers are using some exotic protocol on top of IP, that jnettop doesn't recognize.
You could try to use a network capture tool, with a filter such as not tcp and not udp, and see what remains.


text:
Q: File transfer in winforms using socket is not working when using client machines This is my code for sending and receiving files.It is working when I am transferring files from server to local but when I am using any non server  machines, it is showing exceptions

Background worker is currently busy.

private void BackgroundReceiveLogicMethod(BackgroundWorker bw)
    {

    Socket clientSock;
        try
        {

            string text=null;
            clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //clientSock.Blocking = true;
            textBox2.Invoke((MethodInvoker)delegate
                 {
                text=textBox2.Text;
                 });
            IPHostEntry IPHost = Dns.Resolve(text);
            string[] aliases = IPHost.Aliases;
            IPAddress[] addr = IPHost.AddressList;

            IPEndPoint ipepServer = new IPEndPoint(addr[0], Convert.ToInt32(txtPortNo.Text));
            clientSock.Connect(ipepServer);

            lblReceivingMsg.Invoke((MethodInvoker)delegate
                 {

                     lblReceivingMsg.Text = "Connected to the client";
                 });
            byte[] clientData = new byte[1024 * 5000];
            try
            {
                // If the directory doesn't exist, create it.
                if (!Directory.Exists(@"D:\ShareIt\"))
                {
                    Directory.CreateDirectory(@"D:\ShareIt\");
                }
            }
            catch (Exception e)
            {
                // Fail silently
            }
            string receivedPath = @"D:\ShareIt\";

            int receivedBytesLen = clientSock.Receive(clientData);

            int fileNameLen = BitConverter.ToInt32(clientData, 0);
            string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

            Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName);
               lblReceivingMsg.Invoke((MethodInvoker)delegate
                  {
                      lblReceivingMsg.Text = "Client"+clientSock.RemoteEndPoint +"connected & File"+ fileName+ "started receiving.... ";
                  });

            BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
            bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);

            Console.WriteLine("File: {0} received & saved at path: {1}", fileName, receivedPath);
          //  UpdateLabel(lblReceivingMsg, "File received and saved");
          //  UpdateLabel(label3, "Filename :" + " " + fileName);
         //   UpdateLabel(label4, "Path:" + " " + receivedPath);
            lblReceivingMsg.Invoke((MethodInvoker)delegate
                {
                    lblReceivingMsg.Text = "File received and saved";
                });
            label3.Invoke((MethodInvoker)delegate
                 {
                     label3.Text = "Filename :" + " " + fileName;
                 });
            label4.Invoke((MethodInvoker)delegate
                 {
                     label4.Text = "Path:" + " " + receivedPath;
                 });

            bWrite.Close();
            clientSock.Close();
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Problem connecting to server...");
            lblReceivingMsg.Invoke((MethodInvoker)delegate
              {

                  lblReceivingMsg.Text = "File Sending fail.....Restart the application";
              });
          //  Console.WriteLine("File Sending fail." + ex.Message);
            lblReason.Enabled = true;
            lblReason.Invoke((MethodInvoker)delegate
            {

                lblReason.Text =  ex.Message;
            });

        }

    }

private void BackgroundSendingLogicMethod(BackgroundWorker bw)
    {

            string PathText = null;
            int prtNo = Convert.ToInt32(txtPortNo1.Text);
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, prtNo);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            sock.Bind(ipEnd);
            lblMsg.Invoke((MethodInvoker)delegate
                    {
                        lblMsg.Text = "Sharing started.....";
                    });
            sock.Listen(100);

            textBox1.Invoke((MethodInvoker)delegate
                    {
                        PathText = textBox1.Text;
                    });

            label:
            string fileName = Path.GetFileName(PathText);

            string filePath1 = Path.GetFullPath(PathText);

            string filePath = Path.GetDirectoryName(PathText);//Your File Path;
            byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);

            byte[] fileData = File.ReadAllBytes(filePath + "\\" + fileName);
            byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

            fileNameLen.CopyTo(clientData, 0);
            fileNameByte.CopyTo(clientData, 4);
            fileData.CopyTo(clientData, 4 + fileNameByte.Length);
            //lblMsg.Text = "Waiting for the client to receive";
            Socket clientSock = sock.Accept();
            clientSock.Send(clientData);
            Console.WriteLine("File:{0} has been sent.", fileName);
          //  UpdateLabel(lblReceivingMsg,"File received.....");
            //UpdateLabel(lblMsg, "Sharing done.....");
            lblReceivingMsg.Invoke((MethodInvoker)delegate
            {
                lblReceivingMsg.Text ="File received....." ;
            });

            lblMsg.Invoke((MethodInvoker)delegate
         {
             lblMsg.Text = "Sharing done.....";
         });
            // lblMsg.Text = "File has been sent." + fileName;

            clientSock.Close();
            goto label;
            Console.ReadLine();
      //   }

    }

There are two separate background workers are running.