问:
How to store types, their subtype information all together in binary search tree data structure?
Edited:

To explain my question more in depth. Let's say I have a tool A. Inside tool A there are subtypes of it such as A, B, C, D etc. and each subtype has a quantity.

```<code>Tool A
there are several specific types available in tool A
S.no.   name                quantity
1.    charger                   5
2.    electronic stuff.        10
...
9. so on                       20
</code>```

I want to use binary search to store these values somehow. So when user choose the option tool A, it display all the specific types of things available in them with the quantity and the user can borrow any of these tools and hence the above data can be updated depending upon how much user borrow and return those stuff later. Is there any way to do that using the help of binary search tree?

What I have done till now is:

My code:

public class Tools
    {

```<code>    private string name;
    private string toolInfo;
    private int quantity;

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
        }

    }

    public string ToolInfo
    {
        get { return toolInfo; }
        set
        {
            toolInfo = value;
        }

    }

    public int Quantity
    {
        get { return quantity; }
        set
        {
            quantity = value;
        }

    }

    public Tools(string name, string toolInfo, int quantity) {

        this.name = name;
        this.toolInfo = toolInfo;
        this.quantity = quantity;
    }

    public void toolsInfo()
    {
        //tools info
        WriteLine("Tool name: " + name + " Tool info: " + toolInfo + " Quantity: " + quantity);
    }

    public void addTools()
    {
        //add tools
    }

    public void borrowTools()
    {
        //borrow tools
    }

}
</code>```

}

//main class

```<code>Tools tool1 = new Tools("gardening", "gardening tools...", 40);
            Tools tool2 = new Tools("flooring", "forring tools...", 20);
            Tools tool3 = new Tools("fencing", "fencing tools..", 50);
            Tools tool4 = new Tools("measuring", "measurng tools...", 10);
            Tools tool5 = new Tools("cleaning", "cleaning tools...", 20);
            Tools tool6 = new Tools("painting", "painting tools...", 60);
            Tools tool7 = new Tools("electronic", "electronic tools...", 5);
            Tools tool8 = new Tools("automative", "automative tools..", 20);
            Tools tool9 = new Tools("electricity", "electrucity tools...", 10);'
</code>```

But that only store the types of tools, how could I attach the subtypes to each of the tool them as well  in a way so I can manipulate/change their name or values etc. depending on the user input or some condition?

答:
Is the binary search a prerequisite? You can approach the problem in a different and simpler way.

You can create a new class (e.g. ToolsContainer) that contains sets of Tools. This way you can have a Dictionary that stores key-value pairs that have as a key the Tool type and as a value another Dictionary of tool subtypes and tools. For example:

```<code>using System;
using System.Collections.Generic;

// Your existing code goes here

public class ToolsContainer
{
    private Dictionary<string, Dictionary<string, Tools>> dict = new Dictionary<string, Dictionary<string, Tools>>();

    public ToolsContainer()
    {
    }

    public void add(Tools t)
    {
        Dictionary<string, Tools> nested = null;

        // Check if key exists. If it does update it,
        // else create new entry
        if(dict.TryGetValue(t.Name, out nested))
            nested[t.ToolInfo] = t;
        else
        {
            dict[t.Name] = new Dictionary<string, Tools>();
            dict[t.Name][t.ToolInfo] = t;
        }
    }

    public void printData()
    {
        foreach (KeyValuePair<string, Dictionary<string, Tools>> toolsType in dict)
        {
            foreach(KeyValuePair<string, Tools> tool in toolsType.Value)
                 Console.WriteLine("Type = {0}, Tool = {1}, Quantity = {2}", toolsType.Key, tool.Key, tool.Value.Quantity);
         }
    }
}
</code>```

And test it using the following code:

```<code>public class Program
{
    public static void Main()
    {
        ToolsContainer c = new ToolsContainer();
        // Add new keys
        c.add(new Tools("gardening", "gardeningTool1", 50));
        c.add(new Tools("automotive","automotiveTool1", 20));
        // Update existing key
        c.add(new Tools("gardening", "gardeningTool1", 40));
        c.printData();
    }
}
</code>```

Output:

```<code>Type = gardening, Tool = gardeningTool1, Quantity = 40
Type = automotive, Tool = automotiveTool1, Quantity = 20
</code>```

Using the above approach you can insert new tools and update existing ones. You can also expand on this and use LINQ to order by the data (e.g. order by quantity).

Body:
Edited:

To explain my question more in depth. Let's say I have a tool A. Inside tool A there are subtypes of it such as A, B, C, D etc. and each subtype has a quantity.

Tool A
there are several specific types available in tool A
S.no.   name                quantity
1.    charger                   5
2.    electronic stuff.        10
...
9. so on                       20

I want to use binary search to store these values somehow. So when user choose the option tool A, it display all the specific types of things available in them with the quantity and the user can borrow any of these tools and hence the above data can be updated depending upon how much user borrow and return those stuff later. Is there any way to do that using the help of binary search tree?

What I have done till now is:

My code:

public class Tools
    {

    private string name;
    private string toolInfo;
    private int quantity;

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
        }

    }

    public string ToolInfo
    {
        get { return toolInfo; }
        set
        {
            toolInfo = value;
        }

    }

    public int Quantity
    {
        get { return quantity; }
        set
        {
            quantity = value;
        }

    }

    public Tools(string name, string toolInfo, int quantity) {

        this.name = name;
        this.toolInfo = toolInfo;
        this.quantity = quantity;
    }

    public void toolsInfo()
    {
        //tools info
        WriteLine("Tool name: " + name + " Tool info: " + toolInfo + " Quantity: " + quantity);
    }

    public void addTools()
    {
        //add tools
    }

    public void borrowTools()
    {
        //borrow tools
    }

}

}

//main class

Tools tool1 = new Tools("gardening", "gardening tools...", 40);
            Tools tool2 = new Tools("flooring", "forring tools...", 20);
            Tools tool3 = new Tools("fencing", "fencing tools..", 50);
            Tools tool4 = new Tools("measuring", "measurng tools...", 10);
            Tools tool5 = new Tools("cleaning", "cleaning tools...", 20);
            Tools tool6 = new Tools("painting", "painting tools...", 60);
            Tools tool7 = new Tools("electronic", "electronic tools...", 5);
            Tools tool8 = new Tools("automative", "automative tools..", 20);
            Tools tool9 = new Tools("electricity", "electrucity tools...", 10);'

But that only store the types of tools, how could I attach the subtypes to each of the tool them as well  in a way so I can manipulate/change their name or values etc. depending on the user input or some condition?

Body:
Is the binary search a prerequisite? You can approach the problem in a different and simpler way.

You can create a new class (e.g. ToolsContainer) that contains sets of Tools. This way you can have a Dictionary that stores key-value pairs that have as a key the Tool type and as a value another Dictionary of tool subtypes and tools. For example:

using System;
using System.Collections.Generic;

// Your existing code goes here

public class ToolsContainer
{
    private Dictionary<string, Dictionary<string, Tools>> dict = new Dictionary<string, Dictionary<string, Tools>>();

    public ToolsContainer()
    {
    }

    public void add(Tools t)
    {
        Dictionary<string, Tools> nested = null;

        // Check if key exists. If it does update it,
        // else create new entry
        if(dict.TryGetValue(t.Name, out nested))
            nested[t.ToolInfo] = t;
        else
        {
            dict[t.Name] = new Dictionary<string, Tools>();
            dict[t.Name][t.ToolInfo] = t;
        }
    }

    public void printData()
    {
        foreach (KeyValuePair<string, Dictionary<string, Tools>> toolsType in dict)
        {
            foreach(KeyValuePair<string, Tools> tool in toolsType.Value)
                 Console.WriteLine("Type = {0}, Tool = {1}, Quantity = {2}", toolsType.Key, tool.Key, tool.Value.Quantity);
         }
    }
}

And test it using the following code:

public class Program
{
    public static void Main()
    {
        ToolsContainer c = new ToolsContainer();
        // Add new keys
        c.add(new Tools("gardening", "gardeningTool1", 50));
        c.add(new Tools("automotive","automotiveTool1", 20));
        // Update existing key
        c.add(new Tools("gardening", "gardeningTool1", 40));
        c.printData();
    }
}

Output:

Type = gardening, Tool = gardeningTool1, Quantity = 40
Type = automotive, Tool = automotiveTool1, Quantity = 20

Using the above approach you can insert new tools and update existing ones. You can also expand on this and use LINQ to order by the data (e.g. order by quantity).


来源: stackexchange

问:
Drag and Drop interfering with scroll Angular 7 CDK
I have an Angular 7 app and has angular cdk drag and drop in it to rearrange a list. Drag and drop works fine but it cannot auto scroll the div container. Is there any way to get auto scroll to work without updating the version of angular/cdk as per this link
https://github.com/angular/components/issues/13588

My current version of angular/cdk: 7.3.7.

StackBlitz: https://stackblitz.com/edit/angular-dggptq-rhbitf

答:
Problem was with Your HTML

```<code><div class="container">
<div cdkDropList [cdkDropListData]="timePeriods" class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let timePeriod of timePeriods" cdkDrag>{{timePeriod}}</div>
</div>
</div>
</code>```

To

```<code><div cdkDropList [cdkDropListData]="timePeriods" class="example-list container" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let timePeriod of timePeriods" cdkDrag>{{timePeriod}}</div>
</div>
</code>```

Working Stackblitz :- https://stackblitz.com/edit/angular-dggptq-fmjjjx

Reason :- for autoscroll to work your scroll should be on cdk drop list, so i removed extra div and applied your container class to cdkdrop list div.

ContentLicense: CC BY-SA 4.0

Body:
Problem was with Your HTML

<div class="container">
<div cdkDropList [cdkDropListData]="timePeriods" class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let timePeriod of timePeriods" cdkDrag>{{timePeriod}}</div>
</div>
</div>

To

<div cdkDropList [cdkDropListData]="timePeriods" class="example-list container" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let timePeriod of timePeriods" cdkDrag>{{timePeriod}}</div>
</div>

Working Stackblitz :- https://stackblitz.com/edit/angular-dggptq-fmjjjx

Reason :- for autoscroll to work your scroll should be on cdk drop list, so i removed extra div and applied your container class to cdkdrop list div.


问:
Vim substitution not happening correctly in command line mode when using single quotes
i have a file test.txt with data init=6'b000000; and i want to replace it with init=6'b110111; by using vim script in a bash file. I'm getting error

I'm using following command:

```<code>vim -c '%s/init=6'b000000;/init=6'b110111;/g | write | quit' test.txt
</code>```

this works perfectly in vim, not in bash .

答:
This has nothing to do with Vim, you cannot embed a single quote inside a pair of other single quotes. The shell parses the command line arguments before passing them to the invoked command and it just cannot deal with the inner single quote in the way you have defined.

The literal single quote inside need to be preserved before passing to the command. So use double quote and escape the inner quote

```<code>vim -c "%s/init=6\'b000000;/init=6\'b110111;/g | write | quit" file
</code>```

or use the single quote, but include a multi-level double quote inside

```<code>vim -c '%s/init=6'"\'"'b000000;/init=6'"\'"'b110111;/g | write | quit' file
</code>```

Body:
i have a file test.txt with data init=6'b000000; and i want to replace it with init=6'b110111; by using vim script in a bash file. I'm getting error

I'm using following command:

vim -c '%s/init=6'b000000;/init=6'b110111;/g | write | quit' test.txt

this works perfectly in vim, not in bash .

Body:
This has nothing to do with Vim, you cannot embed a single quote inside a pair of other single quotes. The shell parses the command line arguments before passing them to the invoked command and it just cannot deal with the inner single quote in the way you have defined.

The literal single quote inside need to be preserved before passing to the command. So use double quote and escape the inner quote

vim -c "%s/init=6\'b000000;/init=6\'b110111;/g | write | quit" file

or use the single quote, but include a multi-level double quote inside

vim -c '%s/init=6'"\'"'b000000;/init=6'"\'"'b110111;/g | write | quit' file


问:
Find if 3G is enabled in iphone settings
is it possible to find whether 3G or Edge is enabled in the phone setting through applications?

答:
Its not possible to read the private Settings data (since apps generally can't access data that is not thier own), so I don't think this is possible. However, you can use the [Reachability]
(http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html) code from Apple. Also, you can try going through NSUserDefaults.

ContentLicense: CC BY-SA 3.0


问:
Error in eval(predvars, data, env) : object 'helpfulness' not found
```<code>>hyp1.model1<-clmm(helpfulness~reflectiontype+session+(1+reflectiontype|participant),data=hyp1data)
>summary(hyp1.model1) #summary was produced but I won't replicate it here
>anova(hyp1.model1,type="II")
Error in eval(predvars,data,env):object 'helpfulness' not found
</code>```

I want to run an anova on hyp1.model1 - The model ran fine initially and 'helpfulness' has not come up as a problem in any of my other code using this variable. R has linked with the data set totally fine up until this point and there appears to be no difference between the variable column heading in the data set and the variable label in R (hence all other code has recognised it).

Why is this suddenly a problem when I want to run an anova?

答:
I ran into the same error, but felt that the answer could be more descriptive. I believe the error arises because the stats::anova() and car::Anova() functions don't have the methods to recognize the ordinal::clmm model.

To run a Cumulative Link Mixed Model withordinal::clmm() and obtain the follow-up deviance table, make sure to have both the ordinal and RVAideMemoire packages loaded. RVAideMemoire provides the methods to get the deviance table with Anova.clmm().

```<code># fake data
set.seed(5)
hyp1data <- data.frame(
  participant = c(paste0("id", 1:50),paste0("id", 1:50), paste0("id", 1:50),paste0("id", 1:50)),
  session = c(rep(1, 50), rep(2,50), rep(1, 50), rep(2,50)),
  reflectiontype = c(rep(1, 100), rep(2, 100)),
  helpfulness = sample(1:7, 100, replace = TRUE))

hyp1data[,1:3] <- lapply(hyp1data[,1:3], factor)
hyp1data$helpfulness <- factor(hyp1data$helpfulness, ordered = TRUE)

# load libraries
library(ordinal)
library(RVAideMemoire)

# use RVAideMemoire::Anova.clmm
hyp1.model1<-clmm(helpfulness~reflectiontype+session+(1+reflectiontype|participant),data=hyp1data)
summary(hyp1.model1)
RVAideMemoire::Anova.clmm(hyp1.model1,type="II")

</code>```

Body:
>hyp1.model1<-clmm(helpfulness~reflectiontype+session+(1+reflectiontype|participant),data=hyp1data)
>summary(hyp1.model1) #summary was produced but I won't replicate it here
>anova(hyp1.model1,type="II")
Error in eval(predvars,data,env):object 'helpfulness' not found

I want to run an anova on hyp1.model1 - The model ran fine initially and 'helpfulness' has not come up as a problem in any of my other code using this variable. R has linked with the data set totally fine up until this point and there appears to be no difference between the variable column heading in the data set and the variable label in R (hence all other code has recognised it).

Why is this suddenly a problem when I want to run an anova?

Body:
I ran into the same error, but felt that the answer could be more descriptive. I believe the error arises because the stats::anova() and car::Anova() functions don't have the methods to recognize the ordinal::clmm model.

To run a Cumulative Link Mixed Model withordinal::clmm() and obtain the follow-up deviance table, make sure to have both the ordinal and RVAideMemoire packages loaded. RVAideMemoire provides the methods to get the deviance table with Anova.clmm().

# fake data
set.seed(5)
hyp1data <- data.frame(
  participant = c(paste0("id", 1:50),paste0("id", 1:50), paste0("id", 1:50),paste0("id", 1:50)),
  session = c(rep(1, 50), rep(2,50), rep(1, 50), rep(2,50)),
  reflectiontype = c(rep(1, 100), rep(2, 100)),
  helpfulness = sample(1:7, 100, replace = TRUE))

hyp1data[,1:3] <- lapply(hyp1data[,1:3], factor)
hyp1data$helpfulness <- factor(hyp1data$helpfulness, ordered = TRUE)

# load libraries
library(ordinal)
library(RVAideMemoire)

# use RVAideMemoire::Anova.clmm
hyp1.model1<-clmm(helpfulness~reflectiontype+session+(1+reflectiontype|participant),data=hyp1data)
summary(hyp1.model1)
RVAideMemoire::Anova.clmm(hyp1.model1,type="II")


问:
How do i change the text when i'm submitting
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Birthday: <input type="date" name="bday" id="birth_date">
  <br><br>
</form>

<button onclick="myFunction()">view</button><br>
<h2>Enter your age</h2>
<p id="age"></p></code>```

答:
It's simple, just put id="age" on the

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Birthday: <input type="date" name="bday" id="birth_date">
  <br><br>
</form>

<button onclick="myFunction()">view</button><br>
<h2 id="age">Enter your age</h2></code>```

Body:
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}

<form>
  Birthday: <input type="date" name="bday" id="birth_date">

</form>

<button onclick="myFunction()">view</button>

Enter your age

Body:
It's simple, just put id="age" on the <h2>

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}

<form>
  Birthday: <input type="date" name="bday" id="birth_date">
  <br><br>
</form>

<button onclick="myFunction()">view</button><br>
<h2 id="age">Enter your age</h2>


问:
Two pointers or one pointer + size_t?
I'm working on a library that needs to work with pointers and I came across an important design choice. Let's say I have a function do_stuff that needs to work on a pointer. There are two ways to define such a function

1) void do_stuff(T* first, T* last)

2) void do_stuff(T* ptr, size_t count)

where T names an object type. The first option allows faster iterations. This code

```<code>for(; first < last; ++first)
    do_stuff_impl(*first);
</code>```

just needs to do a check (first < last), and an addition (first + sizeof(T)) every cycle while

```<code>for(size_t i = 0; i < count; ++i)
    do_stuff_impl(ptr[i]);
</code>```

also have to calculate the address of the object we want to refer to, so one more instruction (ptr + i * sizeof(T)) every cycle.

Are there other reason I should prefer the first option over the second one (or vice-versa) in terms of speed, space-efficiency and portability?

Edit: forgot to specify that the second option also need few bytes more to hold a size_t

Edit 2: This question is not opinion based at all, I'm not asking for opinion about what I should use (the first one looks better than the second one), I'm asking for facts..

答:
Size has the advantage that it is not possible to accidentally pass two unrelated pointers to the function. Sure, it is still possible to pass the wrong size, but the fact that second argument is relative rather than absolute makes that approach simpler.

If we generalise the problem to all iterators, then pair of iterators have the advantage that given arbitrary range of unknown size, there is no need to calculate the distance, which would have linear complexity with non random access iterators, and is not an option for non forward iterators.

The difference between these choices is very subtle, and one is not unambiguously better than the other.

Standard library uses pair of iterators with standard algorithms, while it uses pointer + size with std::span and a few string constructors.

My conclusion: Pair of iterators are good for generality, while pointer and size are good for simplicity when generality is not needed or even possible.

Note that writing the pair of pointers variant yourself is unnecessary since the standard library already has an algorithm which does exactly that std::for_each.

Note that once generality is introduced, there is a third option: pass a single object representing the range (by reference). I recommend this approach.

Title: Two pointers or one pointer + size_t?

Body:
I'm working on a library that needs to work with pointers and I came across an important design choice. Let's say I have a function do_stuff that needs to work on a pointer. There are two ways to define such a function

1) void do_stuff(T* first, T* last)

2) void do_stuff(T* ptr, size_t count)

where T names an object type. The first option allows faster iterations. This code

for(; first < last; ++first)
    do_stuff_impl(*first);

just needs to do a check (first < last), and an addition (first + sizeof(T)) every cycle while

for(size_t i = 0; i < count; ++i)
    do_stuff_impl(ptr[i]);

also have to calculate the address of the object we want to refer to, so one more instruction (ptr + i * sizeof(T)) every cycle.

Are there other reason I should prefer the first option over the second one (or vice-versa) in terms of speed, space-efficiency and portability?

Edit: forgot to specify that the second option also need few bytes more to hold a size_t

Edit 2: This question is not opinion based at all, I'm not asking for opinion about what I should use (the first one looks better than the second one), I'm asking for facts..


问:
creating producer and consumer application in python
I am trying to write a producer and consumer code in python using pika for rabbitmq. However for my specific case, I need to run producer on a different host and consumer on other.

I have already written a producer code as:

```<code>import pika

credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('ip add of another host', 5672, '/', credentials)

connection = pika.BlockingConnection()
channel = connection.channel()

channel.queue_declare(queue='test')

channel.basic_publish(exchange='', routing_key='test', body='hello all!')
print (" [x] sent 'Hello all!")

connection.close()
</code>```

The above producer code is running without any error. I also created a new user and gave administrator credentials to it on rabbitmq-server. However when I run the consumer code on another host running rabbitmq-server, I do not see any output:

```<code>import pika

credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)

connection = pika.BlockingConnection()
channel = connection.channel()

channel.queue_declare(queue='test')

def callback(ch, method, properties, body):
   print(" [x] Recieved %r" % body)

channel.basic_consume(
      queue='test', on_message_callback=callback, auto_ack=True)

print (' [x] waiting for messages. To exit press ctrl+c')

channel.start_consume()
</code>```

So, here i had two hosts on the same network which had rabbitmq installed. However one has 3.7.10 and other had 3.7.16 version of rabbitmq.

The producer is able to send the text without error, but the consumer on another host is not receiving any text.

I do not get any problem when both run on same machine, as i just replace connection settings with localhost. Since user guest is only allowed to connect on localhost by default, i created a new user on consumer host running rabbitmq-server.

Please look if anyone can help me out here...

答:
You don't seem to be passing the parameters to the BlockingConnection instance.

```<code>import pika

rmq_server = "ip_address_of_rmq_server"
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters(rmq_server, 5672, '/', credentials)

connection = pika.BlockingConnection(parameters)
channel = connection.channel()
</code>```

Also, your consumer is attaching to the localhost hostname.  Make sure this actually resolves and that your RabbitMQ service is listening on the localhost address (127.0.0.1)  It may not be bound to that address.  I believe that RMQ will bind to all interfaces (and thus all addresses) by default but I'm not sure.

Body:
I am trying to write a producer and consumer code in python using pika for rabbitmq. However for my specific case, I need to run producer on a different host and consumer on other.

I have already written a producer code as:

import pika

credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('ip add of another host', 5672, '/', credentials)

connection = pika.BlockingConnection()
channel = connection.channel()

channel.queue_declare(queue='test')

channel.basic_publish(exchange='', routing_key='test', body='hello all!')
print (" [x] sent 'Hello all!")

connection.close()

The above producer code is running without any error. I also created a new user and gave administrator credentials to it on rabbitmq-server. However when I run the consumer code on another host running rabbitmq-server, I do not see any output:

import pika

credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)

connection = pika.BlockingConnection()
channel = connection.channel()

channel.queue_declare(queue='test')

def callback(ch, method, properties, body):
   print(" [x] Recieved %r" % body)

channel.basic_consume(
      queue='test', on_message_callback=callback, auto_ack=True)

print (' [x] waiting for messages. To exit press ctrl+c')

channel.start_consume()

So, here i had two hosts on the same network which had rabbitmq installed. However one has 3.7.10 and other had 3.7.16 version of rabbitmq.

The producer is able to send the text without error, but the consumer on another host is not receiving any text.

I do not get any problem when both run on same machine, as i just replace connection settings with localhost. Since user guest is only allowed to connect on localhost by default, i created a new user on consumer host running rabbitmq-server.

Please look if anyone can help me out here...

Body:
You don't seem to be passing the parameters to the BlockingConnection instance.

import pika

rmq_server = "ip_address_of_rmq_server"
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters(rmq_server, 5672, '/', credentials)

connection = pika.BlockingConnection(parameters)
channel = connection.channel()

Also, your consumer is attaching to the localhost hostname.  Make sure this actually resolves and that your RabbitMQ service is listening on the localhost address (127.0.0.1)  It may not be bound to that address.  I believe that RMQ will bind to all interfaces (and thus all addresses) by default but I'm not sure.


问:
Rounded corners for UITabBar
I would like to create a UITabBar with rounded corners. Is there a way I can make the UITabBar have rounded corners? It would take the shape of the second picture.

The app starts off with a tableView. When the user taps a topic, they are sent to a tabBar controller.

-----edit-----

This is my AppDelegate:

```<code>func application(_application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool{

    let tabBarController = window?.rootViewController as! UITabBarController
    let image = UIImage(named: "bar")
    let tabBarImage = resize(image: image!, newWidth: tabBarController.view.frame.width)
    tabBarController.tabBar.backgroundImage = tabBarImage

    return true
}

func resize(image: UIImage, newWidth: CGFloat) -> UIImage {

UIGraphicsBeginImageContext(CGSize(width: newWidth, height: image.size.height))
image.drawInRect( CGRect(x: 0, y: 0, width: newWidth, height: image.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage!
}
</code>```

Edit: Dec '21
Replaced image to omit name on project.

答:
Its working fine for me</p>

```<code>override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        self.tabBarController?.tabBar.layer.masksToBounds = true
        self.tabBarController?.tabBar.isTranslucent = true
        self.tabBarController?.tabBar.barStyle = .default
        self.tabBarController?.tabBar.layer.cornerRadius = 25
        self.tabBarController?.tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

    }
</code>```

Title: Rounded corners for UITabBar

Body:
I would like to create a UITabBar with rounded corners. Is there a way I can make the UITabBar have rounded corners? It would take the shape of the second picture.

The app starts off with a tableView. When the user taps a topic, they are sent to a tabBar controller.

-----edit-----

This is my AppDelegate:

func application(_application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool{

    let tabBarController = window?.rootViewController as! UITabBarController
    let image = UIImage(named: "bar")
    let tabBarImage = resize(image: image!, newWidth: tabBarController.view.frame.width)
    tabBarController.tabBar.backgroundImage = tabBarImage

    return true
}

func resize(image: UIImage, newWidth: CGFloat) -> UIImage {

UIGraphicsBeginImageContext(CGSize(width: newWidth, height: image.size.height))
image.drawInRect( CGRect(x: 0, y: 0, width: newWidth, height: image.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage!
}

Edit: Dec '21
Replaced image to omit name on project.

Body:
Its working fine for me

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        self.tabBarController?.tabBar.layer.masksToBounds = true
        self.tabBarController?.tabBar.isTranslucent = true
        self.tabBarController?.tabBar.barStyle = .default
        self.tabBarController?.tabBar.layer.cornerRadius = 25
        self.tabBarController?.tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

    }


问:
Build pjsip 2.10 using msys2
I'm compiling pjsip 2.10 using msys2:

1) open msys2 console: C:\msys64\msys2_shell.cmd

2) Run those to update:

```<code>pacman -Sy
pacman --needed -S bash pacman pacman-mirrors msys2-runtime
pacman -Su
pacman -S perl
pacman -S mingw-w64-i686-toolchain mingw-w64-x86_64-toolchain
pacman -S base-devel
</code>```

3) Restart msys2 console

4) export PATH="/c/msys64/mingw32/bin/:$PATH"

5) Config:

```<code>./configure --prefix=$PWD/dist_mingw --disable-ffmpeg --enable-shared --disable-video --disable-speex-aec --disable-speex-aec --disable-g711-codec --disable-l16-codec --disable-gsm-codec --disable-g722-codec --disable-g7221-codec --disable-speex-codec --disable-ilbc-codec --disable-vpx --disable-opus --disable-libyuv --disable-libwebrtc
</code>```

6) make CFLAGS+="-DPJ_WIN32=1 -DPJ_M_I386=1 -D_LIB -DWIN32 -DPJ_M_I386=1"

7) But error:

```<code>output/pjlib-x86_64-pc-msys/log.o:log.c:(.text+0xcb): undefined reference to `pj_time_decode'
output/pjlib-x86_64-pc-msys/ssl_sock_ossl.o:ssl_sock_ossl.c:(.text+0x205): undefined reference to `pj_time_encode'
output/pjlib-x86_64-pc-msys/ssl_sock_dump.o:ssl_sock_dump.c:(.text+0x9c): undefined reference to `pj_time_decode'
output/pjlib-x86_64-pc-msys/ssl_sock_dump.o:ssl_sock_dump.c:(.text+0xb2): undefined reference to `pj_time_decode'
</code>```

8) As I see pj_time_encode is in pjproject-2.10\pjlib\src\pj\os_time_win32.cbut this file is not compiled. Instead, file os_time_unix.c was compiled. I think this is the cause. So how to make the file os_time_win32.c be compiled instead of os_time_unix.c.

I'm not good in makefile so this is hard to me to custom the build. Thank you very much!

答:
In my MSYS environment PJSIP 2.10 compiles fine with (replace x86_64-w64-mingw32 with i686-w64-mingw32 for 32-bit):

```<code>./configure --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --enable-shared --enable-libsamplerate --with-external-speex --with-external-gsm --with-external-srtp --with-external-pa &&
make dep &&
make &&
echo SUCCESS
</code>```

I did compile the dependancies first myself, hence the with-external- flags.

Title: Build pjsip 2.10 using msys2

Body:
I'm compiling pjsip 2.10 using msys2:

1) open msys2 console: C:\msys64\msys2_shell.cmd

2) Run those to update:

pacman -Sy
pacman --needed -S bash pacman pacman-mirrors msys2-runtime
pacman -Su
pacman -S perl
pacman -S mingw-w64-i686-toolchain mingw-w64-x86_64-toolchain
pacman -S base-devel

3) Restart msys2 console

4) export PATH="/c/msys64/mingw32/bin/:$PATH"

5) Config:

./configure --prefix=$PWD/dist_mingw --disable-ffmpeg --enable-shared --disable-video --disable-speex-aec --disable-speex-aec --disable-g711-codec --disable-l16-codec --disable-gsm-codec --disable-g722-codec --disable-g7221-codec --disable-speex-codec --disable-ilbc-codec --disable-vpx --disable-opus --disable-libyuv --disable-libwebrtc

6) make CFLAGS+="-DPJ_WIN32=1 -DPJ_M_I386=1 -D_LIB -DWIN32 -DPJ_M_I386=1"

7) But error:

output/pjlib-x86_64-pc-msys/log.o:log.c:(.text+0xcb): undefined reference to `pj_time_decode'
output/pjlib-x86_64-pc-msys/ssl_sock_ossl.o:ssl_sock_ossl.c:(.text+0x205): undefined reference to `pj_time_encode'
output/pjlib-x86_64-pc-msys/ssl_sock_dump.o:ssl_sock_dump.c:(.text+0x9c): undefined reference to `pj_time_decode'
output/pjlib-x86_64-pc-msys/ssl_sock_dump.o:ssl_sock_dump.c:(.text+0xb2): undefined reference to `pj_time_decode'

8) As I see pj_time_encode is in pjproject-2.10\pjlib\src\pj\os_time_win32.cbut this file is not compiled. Instead, file os_time_unix.c was compiled. I think this is the cause. So how to make the file os_time_win32.c be compiled instead of os_time_unix.c.

I'm not good in makefile so this is hard to me to custom the build. Thank you very much!

Body:
In my MSYS environment PJSIP 2.10 compiles fine with (replace x86_64-w64-mingw32 with i686-w64-mingw32 for 32-bit):

./configure --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --enable-shared --enable-libsamplerate --with-external-speex --with-external-gsm --with-external-srtp --with-external-pa &&
make dep &&
make &&
echo SUCCESS

I did compile the dependancies first myself, hence the with-external- flags.


问:
Randomly shuffle letters in words in sentences
I want to randomly disrupt the order of the letters that make up words in sentences. I can do the shuffling for single words, e.g.:

```<code>a <- "bach"
sample(unlist(str_split(a, "")), nchar(a))
[1] "h" "a" "b" "c"
</code>```

but I fail to do it for sentences, e.g.:

```<code>b <- "bach composed fugues and cantatas"
</code>```

What I've tried so far:

split into words:

```<code>b1 <- str_split(b, " ")
[[1]]
[1] "bach"     "composed" "fugues"   "and"      "cantatas"
</code>```

calculate the number of characters per word:

```<code>n <- lapply(b1, function(x) nchar(x))
n
[[1]]
[1] 4 8 6 3 8
</code>```

split words in b1 into single letters:

```<code>b2 <- str_split(unlist(str_split(b, " ")), "")
b2
[[1]]
[1] "b" "a" "c" "h"
[[2]]
[1] "c" "o" "m" "p" "o" "s" "e" "d"
[[3]]
[1] "f" "u" "g" "u" "e" "s"
[[4]]
[1] "a" "n" "d"
[[5]]
[1] "c" "a" "n" "t" "a" "t" "a" "s"
</code>```

Jumble the letters in each word based on the above:

```<code>lapply(b2, function(x) sample(unlist(x), unlist(n), replace = T))
[[1]]
[1] "h" "a" "c" "b"
[[2]]
[1] "o" "p" "o" "s"
[[3]]
[1] "g" "s" "s" "u"
[[4]]
[1] "d" "d" "a" "d"
[[5]]
[1] "c" "n" "s" "a"
</code>```

That's obviously not the right result. How can I randomly jumble the sequence of letters in each word in the sentence?

答:
After b2 you can randomly shuffle character using sample and paste the words back.

```<code>paste0(sapply(b2, function(x) paste0(sample(x), collapse = "")), collapse = " ")
#[1] "bhac moodscpe uefusg and tsatnaac"
</code>```

Note that you don't need to mention the size in sample if you want the output to be of same length as input with replace = FALSE.

Body:
I want to randomly disrupt the order of the letters that make up words in sentences. I can do the shuffling for single words, e.g.:

a <- "bach"
sample(unlist(str_split(a, "")), nchar(a))
[1] "h" "a" "b" "c"

but I fail to do it for sentences, e.g.:

b <- "bach composed fugues and cantatas"

What I've tried so far:

split into words:

b1 <- str_split(b, " ")
[[1]]
[1] "bach"     "composed" "fugues"   "and"      "cantatas"

calculate the number of characters per word:

n <- lapply(b1, function(x) nchar(x))
n
[[1]]
[1] 4 8 6 3 8

split words in b1 into single letters:

b2 <- str_split(unlist(str_split(b, " ")), "")
b2
[[1]]
[1] "b" "a" "c" "h"
[[2]]
[1] "c" "o" "m" "p" "o" "s" "e" "d"
[[3]]
[1] "f" "u" "g" "u" "e" "s"
[[4]]
[1] "a" "n" "d"
[[5]]
[1] "c" "a" "n" "t" "a" "t" "a" "s"

Jumble the letters in each word based on the above:

lapply(b2, function(x) sample(unlist(x), unlist(n), replace = T))
[[1]]
[1] "h" "a" "c" "b"
[[2]]
[1] "o" "p" "o" "s"
[[3]]
[1] "g" "s" "s" "u"
[[4]]
[1] "d" "d" "a" "d"
[[5]]
[1] "c" "n" "s" "a"

That's obviously not the right result. How can I randomly jumble the sequence of letters in each word in the sentence?

Body:
After b2 you can randomly shuffle character using sample and paste the words back.

paste0(sapply(b2, function(x) paste0(sample(x), collapse = "")), collapse = " ")
#[1] "bhac moodscpe uefusg and tsatnaac"

Note that you don't need to mention the size in sample if you want the output to be of same length as input with replace = FALSE.


问:
How do you get a file in C++?
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

```<code>#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}
</code>```

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

```<code>char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);
</code>```

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

答:
I figured it out!  To be honest no one answer helped, it was a combination of the three, plus the comments from them.  Thank you all very much! I've attached the code I used, as well as a copy of the document.  The program reads in every character, then spits out the deciphered text. (IE: 1h.e0l/lqo is hello) The next step (extra credit) is to set it up so the user inputs how many characters to skip before reading in the next character to input.

This step I intend to do on my own, but again, thank you very much for all the assistance everyone! Proving once again how awesome this site is, one line of code at a time!

EDIT:: Code adjusted to accept user input, as well as allow for multiple uses without recompiling (I realize it looks like a huge sloppy mess, but that's why it's EXTREMELY commented...because in my mind it looks nice and neat)

```<code>#include<iostream>
#include<fstream>   //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    program:
    char choice;  //lets user choose whether to do another document or not.
    char letter;  //used to track each character in the document.
    int x = 1;    //first counter for tracking correct letter.
    int y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
    int z;        //third counter (used as a check to see if the first two counters are equal).
    string filename;    //allows for user to input the filename they wish to use.
    cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
    cin >> filename; //getline(cin, filename);
    cout << endl;
    cout << "'Every nth character is good', what number is n?: ";
    cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
    cout << endl;
    z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
    ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
    if(infile.is_open()) //checks to see if the file is opened.
    {
        while(!infile.eof())    //continues looping until the end of the file.
        {
                infile.get(letter);  //gets the letters in the order that that they are in the file.
                if (x == y)          //checks to see if the counters match...
                {
                    x++;             //...if they do, adds 1 to the x counter.
                }
                else
                {
                    if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                    {
                        cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                        y = x;                  //sets both counters equal to restart the process of counting.
                    }
                    else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                    {                           //counter until the first and second counters are equal.
                        x++;
                    }
                }
        }
        cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl;
        infile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive).";
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    else  //this prints out and program is skipped in case an incorrect file name is used.
    {
        cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
        cout << "IE:" << "     filename.txt" << endl;
        cout << "You input: " << filename << endl;
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    getchar();  //because I use visual C++ express.
}
</code>```

EDIT:::

I tried inserting the text, but I couldn't get it to come out right, it kept treating some of the characters like coding (ie an apostrophe apparently is the equivalent of the bold command), but you could just try putting in "0h1e.l9lao" without the parenthesis into a .txt and it should give the same outcome.

Thanks again everyone for the help!

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

Title: How do you get a file in C++?

Body:
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

LastEditorDisplayName: EvilTeach

Body:
I figured it out!  To be honest no one answer helped, it was a combination of the three, plus the comments from them.  Thank you all very much! I've attached the code I used, as well as a copy of the document.  The program reads in every character, then spits out the deciphered text. (IE: 1h.e0l/lqo is hello) The next step (extra credit) is to set it up so the user inputs how many characters to skip before reading in the next character to input.

This step I intend to do on my own, but again, thank you very much for all the assistance everyone! Proving once again how awesome this site is, one line of code at a time!

EDIT:: Code adjusted to accept user input, as well as allow for multiple uses without recompiling (I realize it looks like a huge sloppy mess, but that's why it's EXTREMELY commented...because in my mind it looks nice and neat)

#include<iostream>
#include<fstream>   //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    program:
    char choice;  //lets user choose whether to do another document or not.
    char letter;  //used to track each character in the document.
    int x = 1;    //first counter for tracking correct letter.
    int y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
    int z;        //third counter (used as a check to see if the first two counters are equal).
    string filename;    //allows for user to input the filename they wish to use.
    cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
    cin >> filename; //getline(cin, filename);
    cout << endl;
    cout << "'Every nth character is good', what number is n?: ";
    cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
    cout << endl;
    z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
    ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
    if(infile.is_open()) //checks to see if the file is opened.
    {
        while(!infile.eof())    //continues looping until the end of the file.
        {
                infile.get(letter);  //gets the letters in the order that that they are in the file.
                if (x == y)          //checks to see if the counters match...
                {
                    x++;             //...if they do, adds 1 to the x counter.
                }
                else
                {
                    if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                    {
                        cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                        y = x;                  //sets both counters equal to restart the process of counting.
                    }
                    else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                    {                           //counter until the first and second counters are equal.
                        x++;
                    }
                }
        }
        cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl;
        infile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive).";
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    else  //this prints out and program is skipped in case an incorrect file name is used.
    {
        cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
        cout << "IE:" << "     filename.txt" << endl;
        cout << "You input: " << filename << endl;
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    getchar();  //because I use visual C++ express.
}

EDIT:::

I tried inserting the text, but I couldn't get it to come out right, it kept treating some of the characters like coding (ie an apostrophe apparently is the equivalent of the bold command), but you could just try putting in "0h1e.l9lao" without the parenthesis into a .txt and it should give the same outcome.

Thanks again everyone for the help!

LastEditorDisplayName: Jeff


问:
wtforms validate_on_submit with empty values behaviour
I would like a little bit of help into understanding how the validation function in this case. I have the following code:
1. forms.py - here I define my form

```<code>    from flask_wtf import FlaskForm
    from wtforms import StringField, PasswordField, SubmitField, BooleanField
    import email_validator
    from wtforms.validators import DataRequired, Length, Email, EqualTo

    class RegistrationForm(FlaskForm):
        username = StringField('Username',
                               validators=[DataRequired(),
                                           Length(min=2, max=20)])

        email = StringField('Email',
                            validators=[DataRequired(), Email()])

        password = PasswordField('Password',
                                 validators=[DataRequired()])

        confirm_password = PasswordField('Confirm Password',
                                         validators=[DataRequired(),
                                                     EqualTo('password')])

        submit = SubmitField('Sign Up')
</code>```

app.py - the main app

```<code>    from flask import Flask, render_template, url_for, flash, redirect
    from forms import RegistrationForm, LoginForm

    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'giberish'

    @app.route("/")
    @app.route("/home")
    def home():
        return render_template("home.html", title="Home", posts=posts)

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        form = RegistrationForm()
        if form.validate_on_submit():
            flash(f'Account created for {form.username.data}!', 'success')
            return redirect(url_for('home'))
        return render_template('register.html', title='register', form=form)

    if __name__ == '__main__':
        app.run(debug=True)
</code>```

register.html - the template

```<code>{% extends "layout.html" %}
{% block content %}
  <div class="content-section">
    <form method="POST" action="">
      {{ form.hidden_tag() }}
      <fieldset class="form-group">
        <legend class="border-bottom mb-4">Join Today</legend>
        <div class="form-group">
          {{ form.username.label(class="form-control-label") }}
          {% if form.username.errors %}
            {{ form.username(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.username.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
            {% else %}
            {{ form.username(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.email.label(class="form-control-label") }}
          {% if form.email.errors %}
            {{ form.email(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.email.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.email(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.password.label(class="form-control-label") }}
          {% if form.password.errors %}
            {{ form.password(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.password.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.password(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.confirm_password.label(class="form-control-label") }}
          {% if form.confirm_password.errors %}
            {{ form.confirm_password(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.confirm_password.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.confirm_password(class="form-control form-control-lg") }}
          {% endif %}
        </div>
      </fieldset>
      <div class="form-group">
        {{ form.submit(class="btn btn-outline-info") }}
      </div>
  </div>
  <div class="border-top pt-3">
    <small class="text-muted">
      Already Have An Account? <a href="{{url_for('login')}}" class="ml-2">Sign In</a>.
    </small>
  </div>
  {% if form.errors %}
      {{ form.errors }}
  {% endif %}
{% endblock content %}
</code>```

As some could see this is from the videos of Corey Schafer and the code functions, but not exactly as expected at least in the case when I submit an empty form.

In the video from Corey when he submits an empty form than the form.field.errors gets populated and the errors are displayed below each field.

In my case I only get the fields with a red outline and a pop up with please fill in this field.
I would like to know if either I am doing something wrong or this is eventually a new behavior in form validation.

I spend several hours trying to understand and I have not managed. In the case when I fill in one character than the form.field.errors gets populated and the error messages are displayed.
My bed is on the fact that the DataRequired() validator is somehow short-circuiting the validation, but I am not 100% sure as I am a beginner in this.

I would appreciate also eventually a way of approaching this type of errors and where to look for such small details (into documentation or (my) code).

Thanks!

答:
Thanks to Akib Rhast I have found the answer: it is in the change log for wtforms 2.2 and has something to do with this pull request:

Widgets render the required attribute when using a validator that provides the 'required' flag, such as DataRequired. #361

Using the wtforms 2.1 I can confirm that the behavior is as per Corey's video on youtube and the error messages are displayed below the form field upon empty submit.

From version 2.2 onward the verification is done before post in case of empty submits.

The take away from here: read the docs boys and girls. Thanks once again Akib Rhast!!!

Body:
I would like a little bit of help into understanding how the validation function in this case. I have the following code:
1. forms.py - here I define my form

    from flask_wtf import FlaskForm
    from wtforms import StringField, PasswordField, SubmitField, BooleanField
    import email_validator
    from wtforms.validators import DataRequired, Length, Email, EqualTo

    class RegistrationForm(FlaskForm):
        username = StringField('Username',
                               validators=[DataRequired(),
                                           Length(min=2, max=20)])

        email = StringField('Email',
                            validators=[DataRequired(), Email()])

        password = PasswordField('Password',
                                 validators=[DataRequired()])

        confirm_password = PasswordField('Confirm Password',
                                         validators=[DataRequired(),
                                                     EqualTo('password')])

        submit = SubmitField('Sign Up')

app.py - the main app

    from flask import Flask, render_template, url_for, flash, redirect
    from forms import RegistrationForm, LoginForm

    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'giberish'

    @app.route("/")
    @app.route("/home")
    def home():
        return render_template("home.html", title="Home", posts=posts)

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        form = RegistrationForm()
        if form.validate_on_submit():
            flash(f'Account created for {form.username.data}!', 'success')
            return redirect(url_for('home'))
        return render_template('register.html', title='register', form=form)

    if __name__ == '__main__':
        app.run(debug=True)

register.html - the template

{% extends "layout.html" %}
{% block content %}

    <form method="POST" action="">
      {{ form.hidden_tag() }}
      <fieldset class="form-group">
        <legend class="border-bottom mb-4">Join Today</legend>

          {{ form.username.label(class="form-control-label") }}
          {% if form.username.errors %}
            {{ form.username(class="form-control form-control-lg is-invalid") }}

              {% for error in form.username.errors %}
                {{ error }}
              {% endfor %}

            {% else %}
            {{ form.username(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.email.label(class="form-control-label") }}
          {% if form.email.errors %}
            {{ form.email(class="form-control form-control-lg is-invalid") }}

              {% for error in form.email.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.email(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.password.label(class="form-control-label") }}
          {% if form.password.errors %}
            {{ form.password(class="form-control form-control-lg is-invalid") }}

              {% for error in form.password.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.password(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.confirm_password.label(class="form-control-label") }}
          {% if form.confirm_password.errors %}
            {{ form.confirm_password(class="form-control form-control-lg is-invalid") }}

              {% for error in form.confirm_password.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.confirm_password(class="form-control form-control-lg") }}
          {% endif %}

      </fieldset>

        {{ form.submit(class="btn btn-outline-info") }}

      Already Have An Account? Sign In.

  {% if form.errors %}
      {{ form.errors }}
  {% endif %}
{% endblock content %}

As some could see this is from the videos of Corey Schafer and the code functions, but not exactly as expected at least in the case when I submit an empty form.

In the video from Corey when he submits an empty form than the form.field.errors gets populated and the errors are displayed below each field.

In my case I only get the fields with a red outline and a pop up with please fill in this field.
I would like to know if either I am doing something wrong or this is eventually a new behavior in form validation.

I spend several hours trying to understand and I have not managed. In the case when I fill in one character than the form.field.errors gets populated and the error messages are displayed.
My bed is on the fact that the DataRequired() validator is somehow short-circuiting the validation, but I am not 100% sure as I am a beginner in this.

I would appreciate also eventually a way of approaching this type of errors and where to look for such small details (into documentation or (my) code).

Thanks!


问:
could not convert string to float: '10,000' Using Django
How do i convert string to float in django?

this is my views.py

```<code>def UpdateFamilyIncomes(request):
   id = request.POST.get('id')
   Amount_From = int(float(request.POST.get("Amount_From")))
   Amount_To = int(float(request.POST.get("Amount_To")))
   Family_Total_Income = FamilyTotalIncome.objects.get(id=id)
   Family_Total_Income.Amount_From = Amount_From
   Family_Total_Income.Amount_To = Amount_To
</code>```

this is my models.py

```<code>class FamilyTotalIncome(models.Model):
    Description = models.CharField(max_length=500,null=True,blank=True)
    Amount_From=models.FloatField()
    Amount_To = models.FloatField()
    Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True)
</code>```

this is my error

答:
The comma is the source of the error.
You should first replace the comma with a point.</p>

```<code>value = "10,000"
floating_value = float(value.replace(',', '.'))
</code>```

Body:
How do i convert string to float in django?

this is my views.py

def UpdateFamilyIncomes(request):
   id = request.POST.get('id')
   Amount_From = int(float(request.POST.get("Amount_From")))
   Amount_To = int(float(request.POST.get("Amount_To")))
   Family_Total_Income = FamilyTotalIncome.objects.get(id=id)
   Family_Total_Income.Amount_From = Amount_From
   Family_Total_Income.Amount_To = Amount_To

this is my models.py

class FamilyTotalIncome(models.Model):
    Description = models.CharField(max_length=500,null=True,blank=True)
    Amount_From=models.FloatField()
    Amount_To = models.FloatField()
    Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True)

this is my error

Body:
The comma is the source of the error.
You should first replace the comma with a point.

value = "10,000"
floating_value = float(value.replace(',', '.'))


问:
Datagrid horizontal scrolling hides the content in WPF
I've tried to implement Zoom functionality in WPF application. While zooming, it should not affect default scrollviewer DataGrid. So, i used LayoutTransform in DataGridRow.

```<code>    <DataGrid Grid.Row="0" HeadersVisibility="None" SelectionMode="Extended" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Loaded="DataGrid_Loaded">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="LayoutTransform">
                    <Setter.Value>
                        <ScaleTransform ScaleX="{Binding ElementName=slider, Path=Value}" ScaleY="{Binding ElementName=slider, Path=Value}"/>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
    <Slider Grid.Row="1" Minimum="0.5" Maximum="4" Value="1" Name="slider"/>
</code>```

But, this code hides the DataGrid content after zoom and used Horizontal scrollviewer.

Before/After Zoom and scroll the Horizontal Scroll

And then, tried with Style for DataGridCell but the issue not resolved.

```<code>    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="LayoutTransform">
                <Setter.Value>
                    <ScaleTransform ScaleX="{Binding ElementName=slider, Path=Value}" ScaleY="{Binding ElementName=slider, Path=Value}"/>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.CellStyle>
</code>```

Did I missed any handling for this row elements hiding? Anyone please guide with this issue.

Updated for Full Code:

MainWindow.XAML:

```<code><Window x:Class="DatagridSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        <DataGrid Grid.Row="0" HeadersVisibility="None" SelectionMode="Extended" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Loaded="DataGrid_Loaded">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="{Binding ElementName=slider, Path=Value}" ScaleY="{Binding ElementName=slider, Path=Value}"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGrid.RowStyle>
        </DataGrid>
        <Slider Grid.Row="1" Minimum="0.5" Maximum="4" Value="1" Name="slider"/>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs:

```<code>using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace DatagridSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void DataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            var items = new List<Dog>();
            items.Add(new Dog("Fido", 10));
            int count = 25;

            while(count != 0)
            {
                items.Add(new Dog("Spark", 20));
                count--;
            }
            (sender as DataGrid).ItemsSource = items;
        }
    }

    class Dog
    {
        public string Name { get; set; }
        public string Name1 { get { return Name; } }
        public string Name2 { get { return Name; } }
        public string Name3 { get { return Name; } }
        public string Name4 { get { return Name; } }
        public string Name5 { get { return Name; } }
        public string Name6 { get { return Name; } }
        public string Name7 { get { return Name; } }
        public string Name8 { get { return Name; } }
        public string Name9 { get { return Name; } }
        public string Name10 { get { return Name; } }
        public string Name11 { get { return Name; } }
        public int Size { get; set; }

        public Dog(string name, int size)
        {
            this.Name = name;
            this.Size = size;
        }
    }
}
</code>```

答: Add the ScaleTransform to the parent of the DataGrid i.e. Grid. The best solution would be to add the transform on the MainWindow, since you want to zoom in the whole application and not just the DataGrid</p>

Body:
I've tried to implement Zoom functionality in WPF application. While zooming, it should not affect default scrollviewer DataGrid. So, i used LayoutTransform in DataGridRow.

    <DataGrid Grid.Row="0" HeadersVisibility="None" SelectionMode="Extended" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Loaded="DataGrid_Loaded">
        <DataGrid.RowStyle>

        </DataGrid.RowStyle>
    </DataGrid>
    <Slider Grid.Row="1" Minimum="0.5" Maximum="4" Value="1" Name="slider"/>

But, this code hides the DataGrid content after zoom and used Horizontal scrollviewer.

Before/After Zoom and scroll the Horizontal Scroll

And then, tried with Style for DataGridCell but the issue not resolved.

    <DataGrid.CellStyle>

    </DataGrid.CellStyle>

Did I missed any handling for this row elements hiding? Anyone please guide with this issue.

Updated for Full Code:

MainWindow.XAML:

<Window x:Class="DatagridSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        <DataGrid Grid.Row="0" HeadersVisibility="None" SelectionMode="Extended" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Loaded="DataGrid_Loaded">
            <DataGrid.RowStyle>

            </DataGrid.RowStyle>
        </DataGrid>
        <Slider Grid.Row="1" Minimum="0.5" Maximum="4" Value="1" Name="slider"/>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace DatagridSample
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void DataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            var items = new List<Dog>();
            items.Add(new Dog("Fido", 10));
            int count = 25;

            while(count != 0)
            {
                items.Add(new Dog("Spark", 20));
                count--;
            }
            (sender as DataGrid).ItemsSource = items;
        }
    }

    class Dog
    {
        public string Name { get; set; }
        public string Name1 { get { return Name; } }
        public string Name2 { get { return Name; } }
        public string Name3 { get { return Name; } }
        public string Name4 { get { return Name; } }
        public string Name5 { get { return Name; } }
        public string Name6 { get { return Name; } }
        public string Name7 { get { return Name; } }
        public string Name8 { get { return Name; } }
        public string Name9 { get { return Name; } }
        public string Name10 { get { return Name; } }
        public string Name11 { get { return Name; } }
        public int Size { get; set; }

        public Dog(string name, int size)
        {
            this.Name = name;
            this.Size = size;
        }
    }
}


问:
How to intercept specific request
I'm using NestJS and Angular 2, both have similar (close) approach to work with Interceptors. I would like to find best practice to identify some specific request to do some additional work.

To declare Interceptor who will listen some Controller (in NestJS) I should use this logic:

```<code>@UseInterceptors(ObjectsInterceptor)
@Controller('objects')
export class ObjectsController {

  @Get()
  async findAll(): Promise<ObjectDto[]> {
    // Request which should be intercepted
    ...
  }

  @Get(':slug')
  async findOne(@Params('slug') slug: string): Promise<ObjectDto> {
    // Request which shouldn't be intercepted
    ...
  }
}
</code>```

In Interceptor:

```<code>@Injectable()
export class ObjectsInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
    // Some logic to detect specific request
    return next.handle();
  }
}
</code>```

Probably I use wrong way to solve my problem

答:
just put decorator above method instead of class </p>

<pre class="lang-js prettyprint-override"><code>  @Get()
  @UseInterceptors(ObjectsInterceptor)
  async findAll(): Promise<ObjectDto[]> {
    // Request which should be intercepted
    ...
  }
</code>```

Title: How to intercept specific request

Body:
I'm using NestJS and Angular 2, both have similar (close) approach to work with Interceptors. I would like to find best practice to identify some specific request to do some additional work.

To declare Interceptor who will listen some Controller (in NestJS) I should use this logic:

@UseInterceptors(ObjectsInterceptor)
@Controller('objects')
export class ObjectsController {

  @Get()
  async findAll(): Promise<ObjectDto[]> {
    // Request which should be intercepted
    ...
  }

  @Get(':slug')
  async findOne(@Params('slug') slug: string): Promise<ObjectDto> {
    // Request which shouldn't be intercepted
    ...
  }
}

In Interceptor:

@Injectable()
export class ObjectsInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
    // Some logic to detect specific request
    return next.handle();
  }
}

Probably I use wrong way to solve my problem

Body:
just put decorator above method instead of class

  @Get()
  @UseInterceptors(ObjectsInterceptor)
  async findAll(): Promise<ObjectDto[]> {
    // Request which should be intercepted
    ...
  }


问:
Ag-Grid: lock a column's position to the last column
I am wondering if there is a way to effectively lock a column in Ag-Grid so that the column is always the very last column no matter what.

Background

What I am ultimately looking for is to avoid the blank space after the last column if the grid size is wider than all column width combined. This is to give the grid a consistent, professional look especially considering even/odd rows are rendered usually in different color. I would prefer the blank space also has that alternating background color.

Given there seems to be no grid property that forces the grid to render the blank space at the end as a pseudo column, I am therefore considering to add a pseudo column manually in such a way that:

the pseudo column has no header

the pseudo column has no data

the pseudo column is not sortable (achieved via sortable: false)

the pseudo column is not manually resizable (achieved via resizable: false)

the pseudo column is the only column which has suppressSizeToFit: false

lock the pseudo column to always be the last column so that user cannot drag a column to the right side of it

I've found a way to achieve everything apart from the last item in the above list. I know I can suppressMovable: true but that only ensures the column itself is not draggable, it does not prevent user from dragging a column to the right side of it.

Effectively, I am looking for something similar to lockPosition but instead of locking the column to the front I want to lock the column to the end.

答:
Keep an eye on currently open AG-3326 issue in ag-grid backlog https://www.ag-grid.com/ag-grid-pipeline/ </p>

<p>"Allow locking ( lockPosition ) a column to always be either the first or last columns (currently only the first column is supported)"</p>

Body:
Keep an eye on currently open AG-3326 issue in ag-grid backlog https://www.ag-grid.com/ag-grid-pipeline/

"Allow locking ( lockPosition ) a column to always be either the first or last columns (currently only the first column is supported)"


问:
LGBMClassifier in RandomizedSearchCV: best_params_ using eval_metric or scoring?
I'm running a grid search with the LGBMClassifier:

```<code>fit_params={"early_stopping_rounds":30,
            "eval_metric" : 'auc',
            "eval_set" : [(X_test_,y_test_)],
            'eval_names': ['valid'],
            'verbose': 100}

param_test ={'num_leaves': sp_randint(6, 50),
             'min_child_samples': sp_randint(100, 500),
             'min_child_weight': [1e-5, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4],
             'subsample': sp_uniform(loc=0.2, scale=0.8),
             'colsample_bytree': sp_uniform(loc=0.4, scale=0.6),
             'reg_alpha': [0, 1e-1, 1, 2, 5, 7, 10, 50, 100],
             'reg_lambda': [0, 1e-1, 1, 5, 10, 20, 50, 100],
             'scale_pos_weight':[1,2,6,12]}

n_HP_points_to_test = 100

#n_estimators is set to a "large value".
# The actual number of trees build will depend on early stopping and 5000 define only the absolute maximum
clf = lgb.LGBMClassifier(max_depth=-1, random_state=314, silent=False, metric='None', n_jobs=-1, n_estimators=5000)

gs = RandomizedSearchCV(
    estimator = clf,
    param_distributions = param_test,
    n_iter = n_HP_points_to_test,
    scoring = 'balanced_accuracy',
    cv = 3,
    refit = False,
    random_state = 314,
    verbose = 10)

gs.fit(X_train_, y_train_, **fit_params)
print('Best score reached: {} with params: {} '.format(gs.best_score_, gs.best_params_))
</code>```

I would like to optmize in terms of best balanced_accuracy, however, I don't understand if the "eval_metric" : 'auc' is taken into account in the grid search.

In other words, could you tell me if the gs.best_params_ will be those best in relation to the "eval_metric" : 'auc' or in relation to scoring = 'balanced_accuracy'?

答:
I think I understood the answer to my question.

If I dump the results of RandomizedSearchCV in a pandas dataframe:

pd.DataFrame(gs.cv_results_)

I get the best solution for the best mean value (calculated over the 3 splits of the CV) of the balanced_accuracy.

I believe eval_metric would only be used if validation data are provided and is, however, not used in RandomizedSearchCV.

Would be good anyway if anybody could confirm my interpretation.

Body:
I'm running a grid search with the LGBMClassifier:

fit_params={"early_stopping_rounds":30,
            "eval_metric" : 'auc',
            "eval_set" : [(X_test_,y_test_)],
            'eval_names': ['valid'],
            'verbose': 100}

param_test ={'num_leaves': sp_randint(6, 50),
             'min_child_samples': sp_randint(100, 500),
             'min_child_weight': [1e-5, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4],
             'subsample': sp_uniform(loc=0.2, scale=0.8),
             'colsample_bytree': sp_uniform(loc=0.4, scale=0.6),
             'reg_alpha': [0, 1e-1, 1, 2, 5, 7, 10, 50, 100],
             'reg_lambda': [0, 1e-1, 1, 5, 10, 20, 50, 100],
             'scale_pos_weight':[1,2,6,12]}

n_HP_points_to_test = 100

#n_estimators is set to a "large value".
# The actual number of trees build will depend on early stopping and 5000 define only the absolute maximum
clf = lgb.LGBMClassifier(max_depth=-1, random_state=314, silent=False, metric='None', n_jobs=-1, n_estimators=5000)

gs = RandomizedSearchCV(
    estimator = clf,
    param_distributions = param_test,
    n_iter = n_HP_points_to_test,
    scoring = 'balanced_accuracy',
    cv = 3,
    refit = False,
    random_state = 314,
    verbose = 10)

gs.fit(X_train_, y_train_, **fit_params)
print('Best score reached: {} with params: {} '.format(gs.best_score_, gs.best_params_))

I would like to optmize in terms of best balanced_accuracy, however, I don't understand if the "eval_metric" : 'auc' is taken into account in the grid search.

In other words, could you tell me if the gs.best_params_ will be those best in relation to the "eval_metric" : 'auc' or in relation to scoring = 'balanced_accuracy'?


问:
Discover a new camera was connected with EDSKD
There's an event for camera being disconnected, but is there a way to detect that a new camera was connected to the system?

Or repeatedly asking for camera list is my best bet?

答:
Read the EDSDK documentation...

See EdsSetCameraAddedHandler

I can't give any examples as you have not provided any info about which language you are using.


问:
ProviderData empty when using Anonymous Login with Firebase
As the title says, ProviderData turns out empty when using Anonymous Login with Firebase (Unity SDK 6.14.1).

First off, I'm using this to create/login with an anon user:

```<code> Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
 auth.SignInAnonymouslyAsync().ContinueWith(task =>
 {
     //this succeeds

     [insert Code1 you see below here]
 }
</code>```

Then, I linked this account with Facebook using (Code1):

```<code>var credential = Firebase.Auth.FacebookAuthProvider.GetCredential(AccessToken.CurrentAccessToken.TokenString);
auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task2 =>
{
   //this succeeds as well
}
</code>```

However, task2.Result (which is a FirebaseUser-object) does for example not contain DisplayName and other info. Also now to the actual question:

When I now restart the app and invoke auth.SignInAnonymouslyAsync() again, should I expect the response (task.Result) to contain ProviderData field to know what providers this user has linked? Because right now, if I login the user upon startup as I just described, the ProviderData is empty in Unity Editor and only returns Firebase on Android device.

I'm having a hard time understanding if this is intended behaviour and I should try to login using Facebook instead of keep login in anonymously? But if that's the case, I have to manually save if user connected to Facebook which seems very wrong.

I found this bug report which seems to be same/similar issue, but was resolved long time ago: https://github.com/firebase/quickstart-unity/issues/467

Can someone tell me if I'm taking the wrong approach here or if this is indeed a bug?

答:
It would seem that once you've called:

```<code>auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task2 =>
{
   //Insert Code 2. here
}
</code>```

You would also need to call (Code 2.):

```<code> auth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread((task) =>
 {
     //succeed
 });
</code>```

Simply linking does not actually log you in, it only links you on the backend. This makes sense when you consider having multiple providers, but since I only had one it felt logical that one would auto-login together with the linking-process.

Body:
As the title says, ProviderData turns out empty when using Anonymous Login with Firebase (Unity SDK 6.14.1).

First off, I'm using this to create/login with an anon user:

 Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
 auth.SignInAnonymouslyAsync().ContinueWith(task =>
 {
     //this succeeds

     [insert Code1 you see below here]
 }

Then, I linked this account with Facebook using (Code1):

var credential = Firebase.Auth.FacebookAuthProvider.GetCredential(AccessToken.CurrentAccessToken.TokenString);
auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task2 =>
{
   //this succeeds as well
}

However, task2.Result (which is a FirebaseUser-object) does for example not contain DisplayName and other info. Also now to the actual question:

When I now restart the app and invoke auth.SignInAnonymouslyAsync() again, should I expect the response (task.Result) to contain ProviderData field to know what providers this user has linked? Because right now, if I login the user upon startup as I just described, the ProviderData is empty in Unity Editor and only returns Firebase on Android device.

I'm having a hard time understanding if this is intended behaviour and I should try to login using Facebook instead of keep login in anonymously? But if that's the case, I have to manually save if user connected to Facebook which seems very wrong.

I found this bug report which seems to be same/similar issue, but was resolved long time ago: https://github.com/firebase/quickstart-unity/issues/467

Can someone tell me if I'm taking the wrong approach here or if this is indeed a bug?

Body:
It would seem that once you've called:

auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task2 =>
{
   //Insert Code 2. here
}

You would also need to call (Code 2.):

 auth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread((task) =>
 {
     //succeed
 });

Simply linking does not actually log you in, it only links you on the backend. This makes sense when you consider having multiple providers, but since I only had one it felt logical that one would auto-login together with the linking-process.


问:
Codeigniter create thumb image by custom dimensions, how?
I have Codeigniter custom system, need upload image standard dimensions + create _thumb into same folder without duplicate. This is working code without thumb image creator... Can you help me?</p>
```<code>    public function image($var, $id) {
    $config['upload_path'] = './cdn/' . $this->module;
    $config['allowed_types'] = 'gif|jpg|png|jpeg|webp';
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('featured_image')) {

    } else {
        $data = $this->upload->data();
        if ($data['file_name'])
            $this->{$this->model}->featured_image = $data['file_name'];
    }
    return true;
}

public function image_upload() {
    $config['upload_path'] = './cdn/' . $this->module;
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $this->load->library('upload', $config);
    $errors = 0;
    $error_message = '';
    $passed_files = [];
    $var = 'file';
    $files = $this->reArrayFiles(@$_FILES[$var]);
    foreach ($files as $idx => $file) {
        $_FILES[$var] = $files[$idx];
        if ($this->upload->do_upload($var)) {
            $data = $this->upload->data();
            if ($data['file_name']) {
                $ext = pathinfo($data['file_name'], PATHINFO_EXTENSION);
                $file_name = "IRecipes_" . str_replace([".", " "], "", microtime()) . rand(0, 100) . "_orig." . $ext;
                rename($data["full_path"], $data["file_path"] . $file_name);
                $passed_files[] = $file_name;
            }
        } else {
            $errors++;
            $error_message .= strip_tags($this->upload->display_errors());
        }
    }
    if ($passed_files && count($passed_files))
        $this->uploadFile[$var] = ($passed_files);

    if ($errors == count($files))
        die(json_encode(["error" => true, "message" => $error_message]));
    else
        die(json_encode(["error" => false, "files" => $passed_files]));
}
</code>```

答:
You can use CodeIgniter's built-in image_lib library which supports all three major image libraries: GD/GD2, NetPBM, and ImageMagick

Here is official documentation and here is a similar question addressing your issue. Hope this helps you.

Body:
I have Codeigniter custom system, need upload image standard dimensions + create _thumb into same folder without duplicate. This is working code without thumb image creator... Can you help me?

    public function image($var, $id) {
    $config['upload_path'] = './cdn/' . $this->module;
    $config['allowed_types'] = 'gif|jpg|png|jpeg|webp';
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('featured_image')) {

    } else {
        $data = $this->upload->data();
        if ($data['file_name'])
            $this->{$this->model}->featured_image = $data['file_name'];
    }
    return true;
}

public function image_upload() {
    $config['upload_path'] = './cdn/' . $this->module;
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $this->load->library('upload', $config);
    $errors = 0;
    $error_message = '';
    $passed_files = [];
    $var = 'file';
    $files = $this->reArrayFiles(@$_FILES[$var]);
    foreach ($files as $idx => $file) {
        $_FILES[$var] = $files[$idx];
        if ($this->upload->do_upload($var)) {
            $data = $this->upload->data();
            if ($data['file_name']) {
                $ext = pathinfo($data['file_name'], PATHINFO_EXTENSION);
                $file_name = "IRecipes_" . str_replace([".", " "], "", microtime()) . rand(0, 100) . "_orig." . $ext;
                rename($data["full_path"], $data["file_path"] . $file_name);
                $passed_files[] = $file_name;
            }
        } else {
            $errors++;
            $error_message .= strip_tags($this->upload->display_errors());
        }
    }
    if ($passed_files && count($passed_files))
        $this->uploadFile[$var] = ($passed_files);

    if ($errors == count($files))
        die(json_encode(["error" => true, "message" => $error_message]));
    else
        die(json_encode(["error" => false, "files" => $passed_files]));
}