问:
Cannot render csv file retrieved with Flask with the d3.js library
I have made a flask application that correctly retrieves data from an API and then save this data as a csv file. I then try to use this csv file on a HTML template containing JavaScript and D3.js to make a Heatmap with that csv. The HTML/JS file works nice when the csv file is retrieved from a remote server but not when is located in the same directory as the application. The application is the following:

```<code>from flask import Flask, render_template
from chembl_webresource_client.new_client import new_client
import csv

targets =["CHEMBL325", "CHEMBL1937", "CHEMBL1829", "CHEMBL3524", "CHEMBL2563", "CHEMBL1865", "CHEMBL2716", "CHEMBL3192", "CHEMBL4145", "CHEMBL5103", "CHEMBL3310"]

molecules = ["CHEMBL98", "CHEMBL99", "CHEMBL27759", "CHEMBL2018302", "CHEMBL483254", "CHEMBL1213490", "CHEMBL356769", "CHEMBL272980", "CHEMBL430060", "CHEMBL1173445", "CHEMBL356066", "CHEMBL1914702"]

app = Flask(__name__)

@app.route("/")
def index():

  with open('./templates/data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['group','variable','value'])
    for target in targets:
      total_entries = 0
      avg_pchembl_value = 0
      pchembl_value_sum = 0
      for molecule in molecules:
        filtered_acts = new_client.activity.filter(molecule_chembl_id=molecule, target_chembl_id=target, pchembl_value__isnull=False)
        for act in filtered_acts:
          total_entries += 1
          pchembl_value_sum += float(act['pchembl_value'])
        avg_pchembl_value = round(pchembl_value_sum / total_entries, 2)
        writer.writerow([target, molecule, str(avg_pchembl_value)])

  return render_template("index.html")

if __name__ == "__main__":
  app.run()

</code>```

where the index.html template is the following:

```<code><!-- Code from d3-graph-gallery.com -->
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<!-- Load color palettes -->
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>

<script>
  // set the dimensions and margins of the graph
  var margin = {top: 80, right: 25, bottom: 30, left: 40},
    width = 450 - margin.left - margin.right,
    height = 450 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

  //Read the data
  d3.csv("data.csv", function(data) {

    // Labels of row and columns -> unique identifier of the column called 'group' and 'variable'
    var myGroups = d3.map(data, function(d){return d.group;}).keys()
    var myVars = d3.map(data, function(d){return d.variable;}).keys()

    // Build X scales and axis:
    var x = d3.scaleBand()
      .range([ 0, width ])
      .domain(myGroups)
      .padding(0.05);
    svg.append("g")
      .style("font-size", 15)
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x).tickSize(0))
      .select(".domain").remove()

    // Build Y scales and axis:
    var y = d3.scaleBand()
      .range([ height, 0 ])
      .domain(myVars)
      .padding(0.05);
    svg.append("g")
      .style("font-size", 15)
      .call(d3.axisLeft(y).tickSize(0))
      .select(".domain").remove()

    // Build color scale
    var myColor = d3.scaleSequential()
      .interpolator(d3.interpolateInferno)
      .domain([1,100])

    // create a tooltip
    var tooltip = d3.select("#my_dataviz")
      .append("div")
      .style("opacity", 0)
      .attr("class", "tooltip")
      .style("background-color", "white")
      .style("border", "solid")
      .style("border-width", "2px")
      .style("border-radius", "5px")
      .style("padding", "5px")

    // Three function that change the tooltip when user hover / move / leave a cell
    var mouseover = function(d) {
      tooltip
        .style("opacity", 1)
      d3.select(this)
        .style("stroke", "black")
        .style("opacity", 1)
    }
    var mousemove = function(d) {
      tooltip
        .html("pchEMBL<br>value: " + d.value)
        .style("left", (d3.mouse(this)[0]+70) + "px")
        .style("top", (d3.mouse(this)[1]) + "px")
    }
    var mouseleave = function(d) {
      tooltip
        .style("opacity", 0)
      d3.select(this)
        .style("stroke", "none")
        .style("opacity", 0.8)
    }

    // add the squares
    svg.selectAll()
      .data(data, function(d) {return d.group+':'+d.variable;})
      .enter()
      .append("rect")
        .attr("x", function(d) { return x(d.group) })
        .attr("y", function(d) { return y(d.variable) })
        .attr("rx", 4)
        .attr("ry", 4)
        .attr("width", x.bandwidth() )
        .attr("height", y.bandwidth() )
        .style("fill", function(d) { return myColor(d.value)} )
        .style("stroke-width", 4)
        .style("stroke", "none")
        .style("opacity", 0.8)
      .on("mouseover", mouseover)
      .on("mousemove", mousemove)
      .on("mouseleave", mouseleave)
  })

  // Add title to graph
  svg.append("text")
          .attr("x", 0)
          .attr("y", -50)
          .attr("text-anchor", "left")
          .style("font-size", "22px")
          .text("A d3.js heatmap");

  // Add subtitle to graph
  svg.append("text")
          .attr("x", 0)
          .attr("y", -20)
          .attr("text-anchor", "left")
          .style("font-size", "14px")
          .style("fill", "grey")
          .style("max-width", 400)
          .text("A short description of the take-away message of this chart.");
</script>
</code>```

答: Make a separate js file rather than the inline scripts, import the csv file into this js file as "data.csv" and it should work.</p>

Body:
I have made a flask application that correctly retrieves data from an API and then save this data as a csv file. I then try to use this csv file on a HTML template containing JavaScript and D3.js to make a Heatmap with that csv. The HTML/JS file works nice when the csv file is retrieved from a remote server but not when is located in the same directory as the application. The application is the following:

from flask import Flask, render_template
from chembl_webresource_client.new_client import new_client
import csv

targets =["CHEMBL325", "CHEMBL1937", "CHEMBL1829", "CHEMBL3524", "CHEMBL2563", "CHEMBL1865", "CHEMBL2716", "CHEMBL3192", "CHEMBL4145", "CHEMBL5103", "CHEMBL3310"]

molecules = ["CHEMBL98", "CHEMBL99", "CHEMBL27759", "CHEMBL2018302", "CHEMBL483254", "CHEMBL1213490", "CHEMBL356769", "CHEMBL272980", "CHEMBL430060", "CHEMBL1173445", "CHEMBL356066", "CHEMBL1914702"]

app = Flask(__name__)

@app.route("/")
def index():

  with open('./templates/data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['group','variable','value'])
    for target in targets:
      total_entries = 0
      avg_pchembl_value = 0
      pchembl_value_sum = 0
      for molecule in molecules:
        filtered_acts = new_client.activity.filter(molecule_chembl_id=molecule, target_chembl_id=target, pchembl_value__isnull=False)
        for act in filtered_acts:
          total_entries += 1
          pchembl_value_sum += float(act['pchembl_value'])
        avg_pchembl_value = round(pchembl_value_sum / total_entries, 2)
        writer.writerow([target, molecule, str(avg_pchembl_value)])

  return render_template("index.html")

if __name__ == "__main__":
  app.run()

where the index.html template is the following:

<!DOCTYPE html>
<meta charset="utf-8">


来源: stackexchange

问:
Define cluster centers manually
Doing Kmeans cluster analysis, how to I manually define a certain cluster-center?
For example I want to say my cluster centers are [1,2,3] and [3,4,5] and now I want to cluster my vectors to the predefined centers.

something like kmeans.cluster_centers_ = [[1,2,3],[3,4,5]] ?

to work around my problem thats what I do atm:

```<code>number_of_clusters = len(vec)
kmeans = KMeans(number_of_clusters, init='k-means++', n_init=100)
kmeans.fit(vec)
</code>```

it basically defines a cluster for each vector. But it takes ages to compute as I have thousands of vectors/sentences. There must be an option to set the vector coordinates directly as cluster coordinates without the need to compute them with the kmeans algorithm. (as the center outputs are basically the vector coordinates after i run the algorithm...)

Edit to be more specific about my task:

So what I do want is I have tonns of vectors ( generated from sentences) and now I want to cluster these. But imagine I have two columns of sentences and always want to sort a B column sentence to an A column sentence. Not A column sentences to each other. Thats why I want to set cluster centers for the A column vectors and afterwards predict the clostest B vectors to these Centers. Hope that makes sense

I am using sklearn kmeans atm

答:
I think I know what you want to do. So you want to manually select the centroids for k-Means with some known examples and then perform the clustering to assign the closests data points to your pre-defined centroids.

The parameter you are looking for is the k-Means initialization named as init see documentation.

I have prepared a small example that would do exactly this.

```<code>import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial import distance_matrix

# 5 datapoints with 3 features
data = [[1, 0, 0],
        [1, 0.2, 0],
        [0, 0, 1],
        [0, 0, 0.9],
        [1, 0, 0.1]]

X = np.array(data)

distance_matrix(X,X)
</code>```

The pairwise distance matrix shows which examples are the closests.

```<code>> array([[0.        , 0.2       , 1.41421356, 1.3453624 , 0.1       ],
>       [0.2       , 0.        , 1.42828569, 1.36014705, 0.2236068 ],
>       [1.41421356, 1.42828569, 0.        , 0.1       , 1.3453624 ],
>       [1.3453624 , 1.36014705, 0.1       , 0.        , 1.28062485],
>       [0.1       , 0.2236068 , 1.3453624 , 1.28062485, 0.        ]])
</code>```

you can select certain data points to be used as your initial centroids

```<code>centroid_idx = [0,2] # let data point 0 and 2 be our centroids
centroids = X[centroid_idx,:]
print(centroids) # [[1. 0. 0.]
                 # [0. 0. 1.]]

kmeans = KMeans(n_clusters=2, init=centroids, max_iter=1) # just run one k-Means iteration so that the centroids are not updated

kmeans.fit(X)
kmeans.labels_

>>> array([0, 0, 1, 1, 0], dtype=int32)
</code>```

As you can see k-Means labels the data points as expected. You might want to omit the max_iter parameter if you want your centroids to be updated.

ContentLicense: CC BY-SA 4.0

Title: Define cluster centers manually

Body:
Doing Kmeans cluster analysis, how to I manually define a certain cluster-center?
For example I want to say my cluster centers are [1,2,3] and [3,4,5] and now I want to cluster my vectors to the predefined centers.

something like kmeans.cluster_centers_ = [[1,2,3],[3,4,5]] ?

to work around my problem thats what I do atm:

number_of_clusters = len(vec)
kmeans = KMeans(number_of_clusters, init='k-means++', n_init=100)
kmeans.fit(vec)

it basically defines a cluster for each vector. But it takes ages to compute as I have thousands of vectors/sentences. There must be an option to set the vector coordinates directly as cluster coordinates without the need to compute them with the kmeans algorithm. (as the center outputs are basically the vector coordinates after i run the algorithm...)

Edit to be more specific about my task:

So what I do want is I have tonns of vectors ( generated from sentences) and now I want to cluster these. But imagine I have two columns of sentences and always want to sort a B column sentence to an A column sentence. Not A column sentences to each other. Thats why I want to set cluster centers for the A column vectors and afterwards predict the clostest B vectors to these Centers. Hope that makes sense

I am using sklearn kmeans atm

Body:
I think I know what you want to do. So you want to manually select the centroids for k-Means with some known examples and then perform the clustering to assign the closests data points to your pre-defined centroids.

The parameter you are looking for is the k-Means initialization named as init see documentation.

I have prepared a small example that would do exactly this.

import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial import distance_matrix

# 5 datapoints with 3 features
data = [[1, 0, 0],
        [1, 0.2, 0],
        [0, 0, 1],
        [0, 0, 0.9],
        [1, 0, 0.1]]

X = np.array(data)

distance_matrix(X,X)

The pairwise distance matrix shows which examples are the closests.

> array([[0.        , 0.2       , 1.41421356, 1.3453624 , 0.1       ],
>       [0.2       , 0.        , 1.42828569, 1.36014705, 0.2236068 ],
>       [1.41421356, 1.42828569, 0.        , 0.1       , 1.3453624 ],
>       [1.3453624 , 1.36014705, 0.1       , 0.        , 1.28062485],
>       [0.1       , 0.2236068 , 1.3453624 , 1.28062485, 0.        ]])

you can select certain data points to be used as your initial centroids

centroid_idx = [0,2] # let data point 0 and 2 be our centroids
centroids = X[centroid_idx,:]
print(centroids) # [[1. 0. 0.]
                 # [0. 0. 1.]]

kmeans = KMeans(n_clusters=2, init=centroids, max_iter=1) # just run one k-Means iteration so that the centroids are not updated

kmeans.fit(X)
kmeans.labels_

>>> array([0, 0, 1, 1, 0], dtype=int32)

As you can see k-Means labels the data points as expected. You might want to omit the max_iter parameter if you want your centroids to be updated.


问:
Using Model Factory getting [BadMethodCallException] Call to undefined method Illuminate\Database\Query\Builder::fishes()
I am trying to SEED my DB using MODEL FACTORY. I have written the following code. But when i run php artisan db:seed , it Shows :

```<code>[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::fishes()
</code>```

My Code :

```<code>factory(App\Bear::class, 10)->create()->each(function($u) {
            $u->fishes()->save(factory(App\Fish::class)->make());
        });
</code>```

Any help will be appreciated. TIA ..

答:
Out of curiosity: are your model's functions public or protected?

Make sure they are public, like:

```<code>public function historico()
{
    return $this->hasMany('App\Historico', 'participante_id');
}
</code>```

It works fine for me.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to SEED my DB using MODEL FACTORY. I have written the following code. But when i run php artisan db:seed , it Shows :

[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::fishes()

My Code :

factory(App\Bear::class, 10)->create()->each(function($u) {
            $u->fishes()->save(factory(App\Fish::class)->make());
        });

Any help will be appreciated. TIA ..

Body:
Out of curiosity: are your model's functions public or protected?

Make sure they are public, like:

public function historico()
{
    return $this->hasMany('App\Historico', 'participante_id');
}

It works fine for me.


问:
Calculate Invoice Date and Discount Date based on Custom Date field in Bills and Adjustments
I have created a custom date field 'Invoice Date' in Bills and Adjustments. In Bils and Adjustments, Due Date and Cash Discount Date calculated based on DocDate and selected TermsID.

But instead of DocDate, I would like to use the date from my custom field 'Invoice Date' for the calculation of Due Date and Cash Discount Date.

I tried searching for DocDate and TermsID's field updated event in the APInvoiceEntry graph and also tried to find the PXFormula attribute in CacheAttached for Due Date and Cash Discount date in the graph. Moreover, I also looked at APInvoice DAC to find the formula for Due Date and Cash Discount Date but couldn't find anywhere. I tried to find methods in DiscountEngine class as well, but no luck.

Thank you.

答:
TL;DR

Create a new attribute derived from TermsAttribute and rewrite
CalcTerms method. Replace attribute on TermsID field.

Proper Answer

The most robust way to understand the logic that updates some field is to use debugger.
To do that can use the following steps:

Add event that you use for setting a breakpoint using a customization. In that case FieldUpdating is the best match.

```<code>public class APInvoiceEntry_Extension : PXGraphExtension<APInvoiceEntry>
{
    public void APInvoice_DueDate_FieldUpdating(PXCache cache, PXFieldUpdatingEventArgs e)
    {
    }
}
</code>```

Publish the customization.

Open the code in Visual Studio

A. If you use runtime code (built in code editor in customization project), go to SiteFolder\App_RuntimeCode and open the needed file in visual studio (administrator mode).

B. If you use Extension library, open your Visual studio project (administrator mode)

Set a breakpoint to the event

Attach debugger. In Visual studio Menu go to Debug -> Attach to process -> attach to IIS process (usually the name is w3wp.exe) (make sure checkbox Show processes from all users is checked)

Trigger field update. In this case you can change Doc Date to trigger Due Date recalculation.

When breakpoint is hit, check the Call Stack Window

You can navigate through call stack double clicking on rows. In that case PX.Objects.dll!PX.Objects.CS.TermsAttribute.CalcTerms(PX.Data.PXCache sender, PX.Data.PXFieldUpdatedEventArgs e) Line 3461 looks promising.

Normally, you should see the code of everything that is in PX.Objects.dll, but if you don't see it, here are steps to fix it:

Make sure you set Install debugger toolswhen you install Acumatica ERP

Disable Enable Just My Code option in Visual Studio Settings

You can manually point visual studio to source code located in SiteFolder\App_Data\CodeRepository\PX.Objects

Explore the code to find a best place to override the logic. In that case, the best way would be to create a new attribute derived from TermsAttribute and rewrite CalcTerms method (that way you will still be able to reuse base CalcTermsDates method)

Body:
TL;DR

Create a new attribute derived from TermsAttribute and rewrite
CalcTerms method. Replace attribute on TermsID field.

Proper Answer

The most robust way to understand the logic that updates some field is to use debugger.
To do that can use the following steps:

Add event that you use for setting a breakpoint using a customization. In that case FieldUpdating is the best match.

public class APInvoiceEntry_Extension : PXGraphExtension<APInvoiceEntry>
{
    public void APInvoice_DueDate_FieldUpdating(PXCache cache, PXFieldUpdatingEventArgs e)
    {
    }
}

Publish the customization.

Open the code in Visual Studio

A. If you use runtime code (built in code editor in customization project), go to SiteFolder\App_RuntimeCode and open the needed file in visual studio (administrator mode).

B. If you use Extension library, open your Visual studio project (administrator mode)

Set a breakpoint to the event

Attach debugger. In Visual studio Menu go to Debug -> Attach to process -> attach to IIS process (usually the name is w3wp.exe) (make sure checkbox Show processes from all users is checked)

Trigger field update. In this case you can change Doc Date to trigger Due Date recalculation.

When breakpoint is hit, check the Call Stack Window

You can navigate through call stack double clicking on rows. In that case PX.Objects.dll!PX.Objects.CS.TermsAttribute.CalcTerms(PX.Data.PXCache sender, PX.Data.PXFieldUpdatedEventArgs e) Line 3461 looks promising.

Normally, you should see the code of everything that is in PX.Objects.dll, but if you don't see it, here are steps to fix it:

Make sure you set Install debugger toolswhen you install Acumatica ERP

Disable Enable Just My Code option in Visual Studio Settings

You can manually point visual studio to source code located in SiteFolder\App_Data\CodeRepository\PX.Objects

Explore the code to find a best place to override the logic. In that case, the best way would be to create a new attribute derived from TermsAttribute and rewrite CalcTerms method (that way you will still be able to reuse base CalcTermsDates method)


问:
How do I throw an exception in my Java code?
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?</p>

```<code>class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}
</code>```

答:
Should use enums and switch for this task:</p>

```<code>public class Methode {

    public enum Animal {
        DEER (0),
        BIRD (1),
        COW (2),
        PIG (3);

        private final int value;
        private static Map valueMap = new HashMap<>();

        Animal(int value)
        {
            this.value = value;
        }

        static {
            for (Animal enumVal : Animal.values()) {
                valueMap.put(enumVal.value, enumVal);
            }
        }

        public static Animal valueOf(int animalId) {
            return (Animal) valueMap.get(animalId);
        }

        public int getValue()
        {
            return value;
        }
    }

    public static void main(String[] args) throws Exception {
        printAnimal(1);
    }

    public static void printAnimal (int id) throws Exception {
        Animal animal = Animal.valueOf(id);

        if(animal == null) {
            throw new Exception("Animal not found"); //better use own exception
        } else {
            switch (animal) {
                case DEER:
                    System.out.println("Deer");
                    break;
                case BIRD:
                    System.out.println("Bird");
                    break;
                case COW:
                    System.out.println("COW");
                    break;
                case PIG:
                    System.out.println("Pig");
                    break;
                default:
                    System.out.println(animal.name());
            }
        }
    }

}
</code>```

Body:
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?

class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}

Body:
Should use enums and switch for this task:

public class Methode {

    public enum Animal {
        DEER (0),
        BIRD (1),
        COW (2),
        PIG (3);

        private final int value;
        private static Map valueMap = new HashMap<>();

        Animal(int value)
        {
            this.value = value;
        }

        static {
            for (Animal enumVal : Animal.values()) {
                valueMap.put(enumVal.value, enumVal);
            }
        }

        public static Animal valueOf(int animalId) {
            return (Animal) valueMap.get(animalId);
        }

        public int getValue()
        {
            return value;
        }
    }

    public static void main(String[] args) throws Exception {
        printAnimal(1);
    }

    public static void printAnimal (int id) throws Exception {
        Animal animal = Animal.valueOf(id);

        if(animal == null) {
            throw new Exception("Animal not found"); //better use own exception
        } else {
            switch (animal) {
                case DEER:
                    System.out.println("Deer");
                    break;
                case BIRD:
                    System.out.println("Bird");
                    break;
                case COW:
                    System.out.println("COW");
                    break;
                case PIG:
                    System.out.println("Pig");
                    break;
                default:
                    System.out.println(animal.name());
            }
        }
    }

}


问:
A constraint with function that contains Select is never satisfied
I have a table like this:

```<code>CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))
</code>```

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

```<code>if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0
</code>```

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

```<code>select dbo.CheckFunc(1, 10, 15, 1, 1)
</code>```

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?

答:
This answers the original version of the question.

Your first condition should be handled with a check constraint:

```<code>check (occ_end > occ_start)
</code>```

Then, correct logic for overlaps might help.  I would suggest:

```<code>if exists (select 1
           from dbo.RoomSchedule rs
           where p.roomId = @rn and
                 p.occ_end >= @startTime and
                 p.occ_start < @endTime
          )
</code>```

Two time periods overlap if the first starts before the second ends and the first ends after the first starts.

Body:
I have a table like this:

CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

select dbo.CheckFunc(1, 10, 15, 1, 1)

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?

Body:
This answers the original version of the question.

Your first condition should be handled with a check constraint:

check (occ_end > occ_start)

Then, correct logic for overlaps might help.  I would suggest:

if exists (select 1
           from dbo.RoomSchedule rs
           where p.roomId = @rn and
                 p.occ_end >= @startTime and
                 p.occ_start < @endTime
          )

Two time periods overlap if the first starts before the second ends and the first ends after the first starts.


问:
How to Toggle video recording in Twilio
I am trying to add a Toggle recording feature into my web application,
Using Twilio Client version 2.0 and Generating token via Java Server side code.
Toggle(just to be clear)-> Being able to pause/start recording when a call is already underway.

Question : How to implement toggle recording feature in Twilio, If that's possible?

答:
As of now, Pause/Start video recording on a video call is not possible.

Response from Twilio support:

Thanks for reaching out to us! At this time, pausing and resuming a recording isn't possible. This is a feature we're looking to add in the future, but I don't have a specific date to share on when that will be available. I'll add your ticket to the feature request so that we can accurately set a priority for implementing it. Please let me know if you have any questions!

Title: How to Toggle video recording in Twilio


问:
How to implement Paypal callbacks in Rails? (Getting InvalidAuthenticityToken error)
Edit: This is a mostly Rails question

I'm trying to implement instant payment notification API (IPN), which calls your server if the Paypal payment goes through. The problem I'm seeing now is when Paypal IPN hits the url I designated, it is failing with the following error:

> Started POST "/checkout/complete?id=1&amount=3445&authenticity_token=NkOwgJ1H2TEmwO6T+hROu96kWr4yGcTzHD6MbTswgyU="

> ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

The authenticity_token it uses is the one I passed during the initial phase while redirecting to Paypal. Apparently, that's not a valid option. When I leave that blank, though, it's throwing the same error.

I wonder if I can disable authenticity_token requirement or get around it somehow, so that when Paypal posts to my app it can go through without any errors.

答:
Sounds like the csrf is causing the issue, adding skip_before_filter :verify_authenticity_token to your controller should allow it to process.

If your using that authenticity_token as a security measure, then store and check it manually in your controllers.


问:
Using withEnv in a declarative pipeline
I'm trying to run docker command in my declarative pipeline, to install docker env on my slave machine i'm trying to use docker commons plugin "https://plugins.jenkins.io/docker-commons/", but no success.

Further research i have got below link mentioning how to use this plugin.

https://automatingguy.com/2017/11/06/jenkins-pipelines-simple-delivery-flow/

I have configured docker in manage jenkins -> global tool configuration, but dont find how to use below section in my declarative pipeline of jenkins, i think below structure/syntax will work for scripted jenkins pipeline

```<code>def dockerTool = tool name: 'docker', type:
'org.jenkinsci.plugins.docker.commons.tools.DockerTool'
withEnv(["DOCKER=${dockerTool}/bin"]) {
   stages{}
}
</code>```

Can someone pls help, how i can use docker common tool in declarative pipeline of jenkins.
Note: I cannot switch to scripted pipeline due to standardization with other projects

答:
Here is the working example</p>

```<code>pipeline{
    agent any
    stages{
        stage('test') {
            steps{
                script{
                    test_env="this is test env"
                    withEnv(["myEnv=${test_env}"]){
                        echo "${env.myEnv}"
                    }
                }
            }
        }
    }
}
</code>```

Title: Using withEnv in a declarative pipeline

Body:
I'm trying to run docker command in my declarative pipeline, to install docker env on my slave machine i'm trying to use docker commons plugin "https://plugins.jenkins.io/docker-commons/", but no success.

Further research i have got below link mentioning how to use this plugin.

https://automatingguy.com/2017/11/06/jenkins-pipelines-simple-delivery-flow/

I have configured docker in manage jenkins -> global tool configuration, but dont find how to use below section in my declarative pipeline of jenkins, i think below structure/syntax will work for scripted jenkins pipeline

def dockerTool = tool name: 'docker', type:
'org.jenkinsci.plugins.docker.commons.tools.DockerTool'
withEnv(["DOCKER=${dockerTool}/bin"]) {
   stages{}
}

Can someone pls help, how i can use docker common tool in declarative pipeline of jenkins.
Note: I cannot switch to scripted pipeline due to standardization with other projects

Body:
Here is the working example

pipeline{
    agent any
    stages{
        stage('test') {
            steps{
                script{
                    test_env="this is test env"
                    withEnv(["myEnv=${test_env}"]){
                        echo "${env.myEnv}"
                    }
                }
            }
        }
    }
}


问:
Assigning K,V pairs to a JSON object in NodeJS
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}
```

<p>I have defined the JSON object as an empty structure.</p>

<pre class="lang-js prettyprint-override"><code>let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}
</code>```

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}
```

<p>I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.</p>

<p>EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.</p>

<p>EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:</p>

```Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"
```

<p>And convert it to a dissimilarly named JSON object</p>

<pre class="lang-js prettyprint-override"><code>{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}
</code>```

Potentially using some form of mapping, instead of using ~200 if statements

答:
```<code>   for (let i = 0; i < pairs.length; i++) {
      const key = pairs[i].key;
      const value = pairs[i].value;

      if (pairs[i].key == "name") {
        jsonObject[key] = value;
      } else {
        jsonObject.properties[key] = value;
      }
    }
</code>```

After the 'name' all values goes to the properties object, so a simple if would do it

Body:
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}

I have defined the JSON object as an empty structure.

let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}

I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.

EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.

EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:

Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"

And convert it to a dissimilarly named JSON object

{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}

Potentially using some form of mapping, instead of using ~200 if statements

Body:
   for (let i = 0; i < pairs.length; i++) {
      const key = pairs[i].key;
      const value = pairs[i].value;

      if (pairs[i].key == "name") {
        jsonObject[key] = value;
      } else {
        jsonObject.properties[key] = value;
      }
    }

After the 'name' all values goes to the properties object, so a simple if would do it


问:
Randomly select number (without repetition) for each group in R
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

```<code>group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5
</code>```

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

```<code>group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...
</code>```

any suggestions on how I can achieve this?

答:
Give this a try:

```<code>df <- read.table(text = "group    elements
1        3
2        1
3        14
4        10
30       5", header = TRUE)

# reproducibility
set.seed(1)
df_split2 <- do.call("rbind",
                     (lapply(split(df, df$group),
                             function(m) cbind(m,
                                               `number(randomly selected)` =
                                                 sample(1:30, replace = TRUE,
                                                        size = m$elements),
                                               row.names = NULL
                                        ))))

# remove element column name
df_split2$elements <- NULL
head(df_split2)
#>     group number(randomly selected)
#> 1.1     1                        25
#> 1.2     1                         4
#> 1.3     1                         7
#> 2       2                         1
#> 3.1     3                         2
#> 3.2     3                        29
</code>```

The split function splits the df into chunks based on the group column. We then take those smaller data frames and add a column to them by sampling 1:30 a total of elements time. We then do.call on this list to rbind back together.

Body:
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...

any suggestions on how I can achieve this?

Body:
Give this a try:

df <- read.table(text = "group    elements
1        3
2        1
3        14
4        10
30       5", header = TRUE)

# reproducibility
set.seed(1)
df_split2 <- do.call("rbind",
                     (lapply(split(df, df$group),
                             function(m) cbind(m,
                                               `number(randomly selected)` =
                                                 sample(1:30, replace = TRUE,
                                                        size = m$elements),
                                               row.names = NULL
                                        ))))

# remove element column name
df_split2$elements <- NULL
head(df_split2)
#>     group number(randomly selected)
#> 1.1     1                        25
#> 1.2     1                         4
#> 1.3     1                         7
#> 2       2                         1
#> 3.1     3                         2
#> 3.2     3                        29

The split function splits the df into chunks based on the group column. We then take those smaller data frames and add a column to them by sampling 1:30 a total of elements time. We then do.call on this list to rbind back together.


问:
one hot encode each column in a Int matrix in R
I have an issue of translating matrix into one hot encoding in R. I implemented in Matlab but i have difficulty in handling the object in R. Here i have an object of type 'matrix'.

I would like to apply one hot encoding to this matrix. I have problem with column names.

here is an example:

```<code>> set.seed(4)
> t <- matrix(floor(runif(10, 1,9)),5,5)

      [,1] [,2] [,3] [,4] [,5]
[1,]    5    3    5    3    5
[2,]    1    6    1    6    1
[3,]    3    8    3    8    3
[4,]    3    8    3    8    3
[5,]    7    1    7    1    7
> class(t)
[1] "matrix"
</code>```

Expecting:

```<code>      1_1 1_3 1_5 1_7  2_1 2_3 2_6 2_8 ...
[1,]   0   0   1   0    0   1   0   0  ...
[2,]   1   0   0   0    0   0   1   0  ...
[3,]   0   1   0   0    0   0   0   1  ...
[4,]   0   1   0   0    0   0   0   1  ...
[5,]   0   0   0   1    1   0   0   0  ...
</code>```

I tried the following, but the matrix remains the same.

```<code>library(data.table)
library(mltools)
test_table <- one_hot(as.data.table(t))
</code>```

Any suggestions would be very much appreciated.

答:
Your data table must contain some columns (variables) that have class "factor". Try this:

```<code>> t <- data.table(t)
> t[,V1:=factor(V1)]
> one_hot(t)
   V1_1 V1_3 V1_5 V1_7 V2 V3 V4 V5
1:    0    0    1    0  3  5  3  5
2:    1    0    0    0  6  1  6  1
3:    0    1    0    0  8  3  8  3
4:    0    1    0    0  8  3  8  3
5:    0    0    0    1  1  7  1  7
</code>```

But I read that from here that the dummyVars function from the caret package is quicker if your matrix is large.

Edit: Forgot to set the seed. :P

And a quick way to factor all variables in a data table:

```<code>t.f <- t[, lapply(.SD, as.factor)]
</code>```

Body:
I have an issue of translating matrix into one hot encoding in R. I implemented in Matlab but i have difficulty in handling the object in R. Here i have an object of type 'matrix'.

I would like to apply one hot encoding to this matrix. I have problem with column names.

here is an example:

> set.seed(4)
> t <- matrix(floor(runif(10, 1,9)),5,5)

      [,1] [,2] [,3] [,4] [,5]
[1,]    5    3    5    3    5
[2,]    1    6    1    6    1
[3,]    3    8    3    8    3
[4,]    3    8    3    8    3
[5,]    7    1    7    1    7
> class(t)
[1] "matrix"

Expecting:

      1_1 1_3 1_5 1_7  2_1 2_3 2_6 2_8 ...
[1,]   0   0   1   0    0   1   0   0  ...
[2,]   1   0   0   0    0   0   1   0  ...
[3,]   0   1   0   0    0   0   0   1  ...
[4,]   0   1   0   0    0   0   0   1  ...
[5,]   0   0   0   1    1   0   0   0  ...

I tried the following, but the matrix remains the same.

library(data.table)
library(mltools)
test_table <- one_hot(as.data.table(t))

Any suggestions would be very much appreciated.

Body:
Your data table must contain some columns (variables) that have class "factor". Try this:

> t <- data.table(t)
> t[,V1:=factor(V1)]
> one_hot(t)
   V1_1 V1_3 V1_5 V1_7 V2 V3 V4 V5
1:    0    0    1    0  3  5  3  5
2:    1    0    0    0  6  1  6  1
3:    0    1    0    0  8  3  8  3
4:    0    1    0    0  8  3  8  3
5:    0    0    0    1  1  7  1  7

But I read that from here that the dummyVars function from the caret package is quicker if your matrix is large.

Edit: Forgot to set the seed. :P

And a quick way to factor all variables in a data table:

t.f <- t[, lapply(.SD, as.factor)]


问:
Array Should Only Contains Values From Other Array
I Have Two Arrays.

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");
</code>```

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

```<code>$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}
</code>```

答:
Thats it:</p>

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

foreach( $uploaded_array as $key => $mime ) {
  if( !in_array( $mime, $allowed_array ) )  {
    unset( $uploaded_array[$key] );
  }
}

print_r( $uploaded_array );
</code>```

Body:
I Have Two Arrays.

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}

Body:
Thats it:

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

foreach( $uploaded_array as $key => $mime ) {
  if( !in_array( $mime, $allowed_array ) )  {
    unset( $uploaded_array[$key] );
  }
}

print_r( $uploaded_array );


问:
Delete previous image after updating the new one in laravel
I updated and image is showed after that, but i need to delete the previous image (from folder) after updating with the new one.

//update
    public function edit ($id)
    {
      $user = User::find($id);
      // $user = User::where('id', $id)->first();
      // $user = DB::table('users')->where('id', $id)->first();

      return view('edit', compact('user'));
    }

    public function postEdit (Request $request) {
      request()->validate([
          'email' => 'required',
          'fullname' => 'required',
          'birthday' => 'required',
          'address' => 'required|min:10',
      ]);

      $image = $request->image;
      // dd($image);
      $id = $request->id;
      $email = $request->email;
      $fullname = $request->fullname;
      $address = $request->address;
      $birthday = $request->birthday;
      $country = $request->country;

      $image = $request -> file('image');
      $destination = base_path().'/public/img';
      $file_name = rand(100,1).date('h-i-s');
      $image->move($destination, $file_name.".".$image->getClientOriginalExtension());
      $img = $file_name.".".$image->getClientOriginalExtension();

      User::where('id',$id)->update([
        'image'    => $img,
        'email'    => $email,
        'fullname' => $fullname,
        'birthday' => $birthday,
        'address'  => $address,
        'country'  => $country,
      ]);

      return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
    }
```

答:
You can use File facade to delete a file:

use Illuminate\Support\Facades\File;

$pathToFile = base_path('public/img/'.$user->image);

File::delete($pathToFile);
```


问:
C# Assembly Injection Check
I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.

Is there a simple function in C# to prevent SQL injection?

For example

```<code>string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";
</code>```

This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?

For example, these probably wont work:

using @dbName;

SELECT * FROM @table

OPEN SYMMETRIC KEY @keyName

etc

答:
Use bound parameters:</p>

```<code>SqlCommand cmd = new SqlCommand(myQuery, conn);
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 10, lastName);
</code>```

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Title: C# Assembly Injection Check

Body:
I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.

Is there a simple function in C# to prevent SQL injection?

For example

string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";

This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?

For example, these probably wont work:

using @dbName;

SELECT * FROM @table

OPEN SYMMETRIC KEY @keyName

etc

LastEditorDisplayName: Cade Roux

Body:
Use bound parameters:

SqlCommand cmd = new SqlCommand(myQuery, conn);
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 10, lastName);

OwnerDisplayName: Quassnoi


问:
Desperately seeking the answer to my pointer problem
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

```<code>/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}
</code>```

Header definitions:

```<code>/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;
</code>```

答:
In the following code

```<code>category_p = malloc(sizeof(CategoryTypePtr));
.
.
.
pushCategory(menu, category_p);
free(category_p);
category_p = NULL;
</code>```

and

```<code>item_p = malloc(sizeof(ItemTypePtr));
.
.
.
pushItem(category_p, item_p);
free(item_p);
item_p = NULL;
</code>```

You have allocated the memory first, linked it in the list, and that very address you have deallocated. I think this is the problem.

And also you have done:

```<code>item_p = malloc(sizeof(ItemTypePtr));
</code>```

and

```<code>category_p = malloc(sizeof(CategoryTypePtr));
</code>```

the ItemTypePtr and CategoryTypePtr are pointers, so what you allocate is only the size of the pointer, and the memory cannot accomodate the entire data of the structure. You need to do

```<code>item_p = malloc(sizeof(ItemType));
category_p = malloc(sizeof(CategoryType));
</code>```

Also in other locations you need to change the ItemTypePtr to ItemType as needed. I will tell not to typedef the pointers as you have done. This can bring difficulty in reading the code. If you have complex function pointer expressions then typedef ing it okay; in my opinion.

Body:
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}

Header definitions:

/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;

Body:
In the following code

category_p = malloc(sizeof(CategoryTypePtr));
.
.
.
pushCategory(menu, category_p);
free(category_p);
category_p = NULL;

and

item_p = malloc(sizeof(ItemTypePtr));
.
.
.
pushItem(category_p, item_p);
free(item_p);
item_p = NULL;

You have allocated the memory first, linked it in the list, and that very address you have deallocated. I think this is the problem.

And also you have done:

item_p = malloc(sizeof(ItemTypePtr));

and

category_p = malloc(sizeof(CategoryTypePtr));

the ItemTypePtr and CategoryTypePtr are pointers, so what you allocate is only the size of the pointer, and the memory cannot accomodate the entire data of the structure. You need to do

item_p = malloc(sizeof(ItemType));
category_p = malloc(sizeof(CategoryType));

Also in other locations you need to change the ItemTypePtr to ItemType as needed. I will tell not to typedef the pointers as you have done. This can bring difficulty in reading the code. If you have complex function pointer expressions then typedef ing it okay; in my opinion.


问:
How to output all lines to a given writer and return the number of bytes
How can I output to a given writer all the rows in the list that consist only of Latin letters or numbers and return the number of successfully written bytes before the first exception using a lambda expression?

My code:

```<code>public int writeAllCountingBytesTransferred(Writer writer, List<String> list) {
    return list.stream().filter(x -> x.matches("^[a-zA-Z0-9]+$") ).forEach(x-> {
        try {
            writer.write(x);
            how do I count bytes?
        } catch (IOException e) {
            how do I return bytes?

        }
    });
}
</code>```

答:
```<code>public class CountingWriter extends FilterWriter {
    private long count;

    public CountingWriter(Writer out) {
        super(out);
    }

    /**
     * The number of chars written. For ASCII this is the number of bytes.
     * @return the char count.
     */
    public long getCount() {
        return count;
    }

    @Override
    public void write(int c) throws IOException {
        super.write(c);
        ++count;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        super.write(cbuf, off, len);
        count += len;
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        super.write(str, off, len);
        count += len;
    }
}

CountingWriter cWriter = new CountingWriter(writer);
...
long count = cWriter.getCount();
</code>```

A FilterWriter is a nice wrapper class that delegates to the original writer, and can be used for this kind of filtering purposes.

As ASCII implies that every char is written as a single byte. (If the encoding for the file is not UTF-16LE or such.)

Body:
How can I output to a given writer all the rows in the list that consist only of Latin letters or numbers and return the number of successfully written bytes before the first exception using a lambda expression?

My code:

public int writeAllCountingBytesTransferred(Writer writer, List<String> list) {
    return list.stream().filter(x -> x.matches("^[a-zA-Z0-9]+$") ).forEach(x-> {
        try {
            writer.write(x);
            how do I count bytes?
        } catch (IOException e) {
            how do I return bytes?

        }
    });
}

Body:
public class CountingWriter extends FilterWriter {
    private long count;

    public CountingWriter(Writer out) {
        super(out);
    }

    /**
     * The number of chars written. For ASCII this is the number of bytes.
     * @return the char count.
     */
    public long getCount() {
        return count;
    }

    @Override
    public void write(int c) throws IOException {
        super.write(c);
        ++count;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        super.write(cbuf, off, len);
        count += len;
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        super.write(str, off, len);
        count += len;
    }
}

CountingWriter cWriter = new CountingWriter(writer);
...
long count = cWriter.getCount();

A FilterWriter is a nice wrapper class that delegates to the original writer, and can be used for this kind of filtering purposes.

As ASCII implies that every char is written as a single byte. (If the encoding for the file is not UTF-16LE or such.)


问:
My gridView is not showing on the mainactivity
I have a gridView adapter here :

```<code>package com.example.myapplication

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.inflate
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import androidx.cardview.widget.CardView

class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)
        image.setImageResource(images[position])

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return null
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getCount(): Int {
        return 0
    }

}
</code>```

I am trying to set the cardView on every cell of the gridView, here is my card_view.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>
</code>```

I am trying to call the adapter like this:

```<code>class MainActivity : AppCompatActivity() {
    private var initialGridPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
     }
}
</code>```

This is the gridView in my activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingHorizontal="30dp"
    android:paddingVertical="30dp"
    tools:context=".MainActivity"
    >
    <GridView
      android:layout_width="match_parent"
      android:layout_height="200dp"
      android:numColumns="3"
      android:id="@+id/gridView"
      />
  </LinearLayout>
</ScrollView>
</code>```

It is not showing me the gridView while I'm the app, but in the mainActivity gridView.adapter is not null after assigning it to the ImageAdapter object.

答:
issue is  getcount() method returns always 0 so you have return images size in it.</p>

```<code>override fun getCount(): Int {
        return images.size
 }
</code>```

Body:
I have a gridView adapter here :

package com.example.myapplication

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.inflate
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import androidx.cardview.widget.CardView

class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)
        image.setImageResource(images[position])

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return null
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getCount(): Int {
        return 0
    }

}

I am trying to set the cardView on every cell of the gridView, here is my card_view.xml :

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>

I am trying to call the adapter like this:

class MainActivity : AppCompatActivity() {
    private var initialGridPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
     }
}

This is the gridView in my activity:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingHorizontal="30dp"
    android:paddingVertical="30dp"
    tools:context=".MainActivity"
    >
    <GridView
      android:layout_width="match_parent"
      android:layout_height="200dp"
      android:numColumns="3"
      android:id="@+id/gridView"
      />
  </LinearLayout>
</ScrollView>

It is not showing me the gridView while I'm the app, but in the mainActivity gridView.adapter is not null after assigning it to the ImageAdapter object.

Body:
issue is  getcount() method returns always 0 so you have return images size in it.

override fun getCount(): Int {
        return images.size
 }


问:
In a Hugo Base template how can I know which page is being displayed?
I have a Hugo template and as you can see below, header and footer are static and child pages are added to the "main" block. I would like the  to get a class depending on the page being displayed. Is this possible WITHOUT javascript? I mean, do we by any chance have access to the name of the child page from the base?
Thanks in advance.

```<code><body>
    {{ partial "header.html" . }}
    {{ block "main" . }}
    {{ end }}
    {{ partial "footer.html" . }}
    {{ partial "nav.html" . }}
</body>
</code>```

答:
You can use Page Variables to get page information and then use it to change a class on HTML

Page Variable

Body:
I have a Hugo template and as you can see below, header and footer are static and child pages are added to the "main" block. I would like the  to get a class depending on the page being displayed. Is this possible WITHOUT javascript? I mean, do we by any chance have access to the name of the child page from the base?
Thanks in advance.

    {{ partial "header.html" . }}
    {{ block "main" . }}
    {{ end }}
    {{ partial "footer.html" . }}
    {{ partial "nav.html" . }}


问:
StorageException has occurred. Object does not exist at location. Storage FireBase
I want display image in imageView, that's what I'm doing: I'm using FirebaseUI to display images from FireBase Storage.

```<code>FirebaseStorage storageDisplayImg;
StorageReference storageRef;
private FirebaseAuth auth;

        storageDisplayImg=FirebaseStorage.getInstance();
        auth = FirebaseAuth.getInstance();
        FirebaseUser userConnect = auth.getCurrentUser();
        String id_user=userConnect.getUid();
        storageRef = storageDisplayImg.getReference().child(item.getChemin_image()); // return gs://mydreambook-32321.appspot.com/images/test23-03-2017_16:46:55

        if (item.getChemin_image() != null&&id_user != null) {

           Glide.with(convertView.getContext() )
                   .using(new FirebaseImageLoader())
                   .load(storageRef)
                   .into(profilePic);
            profilePic.setVisibility(View.VISIBLE);

        } else {
            profilePic.setVisibility(View.GONE);
        }
</code>```

But I have this error:

```<code>StorageException has occurred.  Object does not exist at location.    Code: -13010 HttpResult: 404
</code>```

Update , Image in storage FireBase

答:
I had a similar problem. I was trying to delete a file with some wrong case letters

Example: Deleting file_of_user_uidabcde.png by searching for file_of_user_uIdAbCdE.png

Body:
I want display image in imageView, that's what I'm doing: I'm using FirebaseUI to display images from FireBase Storage.

FirebaseStorage storageDisplayImg;
StorageReference storageRef;
private FirebaseAuth auth;

        storageDisplayImg=FirebaseStorage.getInstance();
        auth = FirebaseAuth.getInstance();
        FirebaseUser userConnect = auth.getCurrentUser();
        String id_user=userConnect.getUid();
        storageRef = storageDisplayImg.getReference().child(item.getChemin_image()); // return gs://mydreambook-32321.appspot.com/images/test23-03-2017_16:46:55

        if (item.getChemin_image() != null&&id_user != null) {

           Glide.with(convertView.getContext() )
                   .using(new FirebaseImageLoader())
                   .load(storageRef)
                   .into(profilePic);
            profilePic.setVisibility(View.VISIBLE);

        } else {
            profilePic.setVisibility(View.GONE);
        }

But I have this error:

StorageException has occurred.  Object does not exist at location.    Code: -13010 HttpResult: 404

Update , Image in storage FireBase


问:
Convert a multi index dataframe to json
Here is the multi index data frame

```<code>accounting                                         sales
PhNumber    age     firstName      lastName         PhNumber       age  firstName   lastName
0   <PH_Number> 29  <first_Name>    <last_Name>     <PH_Number> 29  <first_Name>    <last_Name>
1   <PH_Number> 38  <first_Name>    <last_Name>     <PH_Number> 48  <first_Name>    <last_Name>
</code>```

How do I convert this to a proper json?
I have used pandas.to_json().
But couldn't get the desired output like this

```<code>{ "accounting": [{"firstName": <first_name>,
   "lastName": <last_name>,
   "age": 29,
   "PhNumber": <PH_Number>},
  {"firstName": <first_name>,
   "lastName": "<last_name>",
   "age": 38,
   "PhNumber": <PH_Number>}],
 "sales": [{"firstName": "<first_name>",
   "lastName": "<last_name>",
   "age": 29,
   "PhNumber": <PH_Number>},
  {"firstName": "<first_name>",
   "lastName": "<last_name>",
   "age": 48,
   "PhNumber": <PH_Number>}]}
</code>```

答:
What you ask is beyond the possibilies of to_json, so you should first compute the Python data structure and then convert it to JSON:

```<code>data_struct = {k: df[k].to_dict(orient='records') for k in df.columns.levels[0]}
</code>```

You can then easily build a JSON file (or string):

```<code>print(json.dumps(data_struct, indent=2)
</code>```

gives:

```<code>{
  "accounting": [
    {
      "PhNumber": "<PH_Number>",
      "age": 29,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    },
    {
      "PhNumber": "<PH_Number>",
      "age": 38,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    }
  ],
  "sales": [
    {
      "PhNumber": "<PH_Number>",
      "age": 29,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    },
    {
      "PhNumber": "<PH_Number>",
      "age": 48,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    }
  ]
}
</code>```

Title: Convert a multi index dataframe to json

Body:
Here is the multi index data frame

accounting                                         sales
PhNumber    age     firstName      lastName         PhNumber       age  firstName   lastName
0   <PH_Number> 29  <first_Name>    <last_Name>     <PH_Number> 29  <first_Name>    <last_Name>
1   <PH_Number> 38  <first_Name>    <last_Name>     <PH_Number> 48  <first_Name>    <last_Name>

How do I convert this to a proper json?
I have used pandas.to_json().
But couldn't get the desired output like this

{ "accounting": [{"firstName": <first_name>,
   "lastName": <last_name>,
   "age": 29,
   "PhNumber": <PH_Number>},
  {"firstName": <first_name>,
   "lastName": "<last_name>",
   "age": 38,
   "PhNumber": <PH_Number>}],
 "sales": [{"firstName": "<first_name>",
   "lastName": "<last_name>",
   "age": 29,
   "PhNumber": <PH_Number>},
  {"firstName": "<first_name>",
   "lastName": "<last_name>",
   "age": 48,
   "PhNumber": <PH_Number>}]}

Body:
What you ask is beyond the possibilies of to_json, so you should first compute the Python data structure and then convert it to JSON:

data_struct = {k: df[k].to_dict(orient='records') for k in df.columns.levels[0]}

You can then easily build a JSON file (or string):

print(json.dumps(data_struct, indent=2)

gives:

{
  "accounting": [
    {
      "PhNumber": "<PH_Number>",
      "age": 29,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    },
    {
      "PhNumber": "<PH_Number>",
      "age": 38,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    }
  ],
  "sales": [
    {
      "PhNumber": "<PH_Number>",
      "age": 29,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    },
    {
      "PhNumber": "<PH_Number>",
      "age": 48,
      "firstName": "<first_Name>",
      "lastName": "<last_Name>"
    }
  ]
}


问:
Android - Oracle 12c Database Connection Issue : java.sql.SQLException: ORA-28040: No matching authentication protocol
Since last 3 days I am getting problem with just simple connection of Android - Oracle 12c Database.

Recently I have uploaded Android-Oracle-Connection but its for 11g version. I have used ojdbc14.jar

I have used following lines of code in that demo:

```<code>/**
 * Driver for Oracle
 */
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";

/**
 * URL to connect database
 */
private static final String DEFAULT_URL = "jdbc:oracle:thin:@192.168.0.102:1521:oracle"; // Change IP_Address:Database

/**
 * Creating Connection
 *
 * @param driver   driver object
 * @param url      url for db
 * @param username username
 * @param password password
 * @return Connection object
 * @throws ClassNotFoundException throwing exception
 * @throws SQLException           throwing exception
 */
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
    Class.forName(driver);
    return DriverManager.getConnection(url, username, password);
}
</code>```

Now Problem is, I am using IP : 192.168.0.102 for 11g which was successfully connected but I have change IP 192.168.0.105 for 12c with same code but its not working.

I am getting error as:

```<code>java.sql.SQLException: ORA-28040: No matching authentication protocol
</code>```

I have already checked this answer and tried but getting error as:

```<code>W/oracle.jdbc: Error while registering Oracle JDBC Diagnosability MBean.
    java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
        at oracle.jdbc.driver.OracleDriver.registerMBeans(OracleDriver.java:321)
        at oracle.jdbc.driver.OracleDriver$1.run(OracleDriver.java:203)
        at java.security.AccessController.doPrivileged(AccessController.java:43)
        at oracle.jdbc.driver.OracleDriver.<clinit>(OracleDriver.java:199)
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at java.lang.Class.forName(Class.java:379)
</code>```

I have already tried this answer too but getting error as:

```<code>2019-11-23 16:36:12.564 28567-28567/com.demo.oracle E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.demo.oracle, PID: 28567
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at oracle.jdbc.driver.OracleDriver.<clinit>(OracleDriver.java:230)
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at java.lang.Class.forName(Class.java:379)
</code>```

I didn't found any tutorial or documentation to connect with 12c. Can anyone help?

答: Old post but just to answer it, you have to add a parameter on the Database Server sqlnet.ora file to allow connection from older clients. This error happens when your client is old and server is only allows connection from recent version of sqlnet client. Example 11g client trying to connect to 18c DB Server. </p>

Body:
Since last 3 days I am getting problem with just simple connection of Android - Oracle 12c Database.

Recently I have uploaded Android-Oracle-Connection but its for 11g version. I have used ojdbc14.jar

I have used following lines of code in that demo:

/**
 * Driver for Oracle
 */
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";

/**
 * URL to connect database
 */
private static final String DEFAULT_URL = "jdbc:oracle:thin:@192.168.0.102:1521:oracle"; // Change IP_Address:Database

/**
 * Creating Connection
 *
 * @param driver   driver object
 * @param url      url for db
 * @param username username
 * @param password password
 * @return Connection object
 * @throws ClassNotFoundException throwing exception
 * @throws SQLException           throwing exception
 */
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
    Class.forName(driver);
    return DriverManager.getConnection(url, username, password);
}

Now Problem is, I am using IP : 192.168.0.102 for 11g which was successfully connected but I have change IP 192.168.0.105 for 12c with same code but its not working.

I am getting error as:

java.sql.SQLException: ORA-28040: No matching authentication protocol

I have already checked this answer and tried but getting error as:

W/oracle.jdbc: Error while registering Oracle JDBC Diagnosability MBean.
    java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
        at oracle.jdbc.driver.OracleDriver.registerMBeans(OracleDriver.java:321)
        at oracle.jdbc.driver.OracleDriver$1.run(OracleDriver.java:203)
        at java.security.AccessController.doPrivileged(AccessController.java:43)
        at oracle.jdbc.driver.OracleDriver.<clinit>(OracleDriver.java:199)
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at java.lang.Class.forName(Class.java:379)

I have already tried this answer too but getting error as:

2019-11-23 16:36:12.564 28567-28567/com.demo.oracle E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.demo.oracle, PID: 28567
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at oracle.jdbc.driver.OracleDriver.<clinit>(OracleDriver.java:230)
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at java.lang.Class.forName(Class.java:379)

I didn't found any tutorial or documentation to connect with 12c. Can anyone help?


答:
The problem is these lines:

```<code>  category_p = malloc(sizeof(CategoryTypePtr));

  item_p = malloc(sizeof(ItemTypePtr));
</code>```

These lines, as written, only allocate enough memory to store a pointer, not the structure you want to point to.

Try:

```<code>  category_p = malloc(sizeof(CategoryType));

  item_p = malloc(sizeof(ItemType));
</code>```

Also, your push functions are overly complicated.  There's no need to copy the list nodes before you add them to the list. Just assign the address in the pointer to the new node to the ->next... pointer in the current tail:

```<code>void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;

   // no need to allocate space just for a pointer

   if (menu->headCategory == NULL) {
      menu->headCategory = category;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = category;
   }
   menu->numCategories++;
}
</code>```

Then you don't want the free(item_p) and free(category_p) calls in the main routine because the memory you've allocated is now being referenced by the list.  You will need to free this memory when you dispose of the list.

Title: Desperately seeking the answer to my pointer problem

Body:
The problem is these lines:

  category_p = malloc(sizeof(CategoryTypePtr));

  item_p = malloc(sizeof(ItemTypePtr));

These lines, as written, only allocate enough memory to store a pointer, not the structure you want to point to.

Try:

  category_p = malloc(sizeof(CategoryType));

  item_p = malloc(sizeof(ItemType));

Also, your push functions are overly complicated.  There's no need to copy the list nodes before you add them to the list. Just assign the address in the pointer to the new node to the ->next... pointer in the current tail:

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;

   // no need to allocate space just for a pointer

   if (menu->headCategory == NULL) {
      menu->headCategory = category;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = category;
   }
   menu->numCategories++;
}

Then you don't want the free(item_p) and free(category_p) calls in the main routine because the memory you've allocated is now being referenced by the list.  You will need to free this memory when you dispose of the list.


答:
You can use array_intersect:

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png","text/php");

print_r(array_intersect($uploaded_array,$allowed_array));
</code>```

Output:

```<code>Array
(
    [0] => image/jpeg
    [1] => image/jpeg
    [2] => image/gif
    [3] => image/png
)
</code>```

Demo

Title: Array Should Only Contains Values From Other Array

Body:
You can use array_intersect:

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png","text/php");

print_r(array_intersect($uploaded_array,$allowed_array));

Output:

Array
(
    [0] => image/jpeg
    [1] => image/jpeg
    [2] => image/gif
    [3] => image/png
)

Demo