问:
"No appropriate default constructor available" error in Visual C++
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

```<code>    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);
</code>```

This is how I implement the constructor:

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}
</code>```

This is how i use it in my main function.

```<code>TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);
</code>```

I know my argument list is pretty long, there's a reason for that.
Thanks.

答:
A default ctor is one that can be called with no arguments.  At least with this code, you don't have one: a default ctor either has the signature

```<code>ClassName::ClassName();
</code>```

or every argument must have a default.

That said, Dirk's point about the syntax is correct; if you want to invoke the parent classes ctor, you should do it after that colon.

@dirkgently's answer shows the right syntax, but let's expand it a little bit.  You've got two classes

```<code>public class Package {
    // ...
    Package( /* that horrible ctor arg list */){/*...*/}
    // ...
}

public class TwoDayPackage : public Package {
    // ...
    TwoDayPackage(/* another horrible ctor */);  // declaration only
    // ...
}
</code>```

and then you come along to define it

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress,
                             string sState, string sCountry,
                             int sZIP, string rName,
                             string rAddress, string rState,
                             string rCountry, int rZIP,
                             float weight, float cost, float flat)
{

     Package::Package(sName, sAddress, sState, sCountry, sZIP,
                      rName, rAddress, rState, rCountry, rZIP,
                      weight, cost);
     flatRate = flat;
}
</code>```

... but that doesn't work?  Why?  Basically, because what you're telling C++ doesn't make sense: the Package::Package is just naming the superclass's ctor and not doing anything with it.  You could create a new object of class Package by using the new operator,

```<code>     Package foo = new
         Package::Package(sName, sAddress, sState, sCountry, sZIP,
                          rName, rAddress, rState, rCountry, rZIP,
                          weight, cost);
</code>```

but that's still not what you want to do; what you want is to tell C++ to contruct the Package parts of TwoDayPackage using that arg list.  You don't need to have the fully-qualified name, because the compiler already knows what the parent class is.

You could also just assign values in the child ctor, but that's inefficient, as it makes the compiler generate code for "multiple trips to the well".  So C++ has a special syntax where initializers are put after a colon, as Dirk showed.

One more thing: since you're just assigning a parameter to flat anyway, you can say

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress,
                             string sState, string sCountry,
                             int sZIP, string rName,
                             string rAddress, string rState,
                             string rCountry, int rZIP,
                             float weight, float cost, float flat) :
    Package(sName, sAddress, sState, sCountry, sZIP,
            rName, rAddress, rState, rCountry, rZIP, weight, cost),
    flatRate(flat)
{
}
</code>```

Check this section of the C++ FAQ Lite for more.

OwnerDisplayName: chustar

ContentLicense: CC BY-SA 2.5

Body:
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);

This is how I implement the constructor:

TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}

This is how i use it in my main function.

TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);

I know my argument list is pretty long, there's a reason for that.
Thanks.

Body:
A default ctor is one that can be called with no arguments.  At least with this code, you don't have one: a default ctor either has the signature

ClassName::ClassName();

or every argument must have a default.

That said, Dirk's point about the syntax is correct; if you want to invoke the parent classes ctor, you should do it after that colon.

@dirkgently's answer shows the right syntax, but let's expand it a little bit.  You've got two classes

public class Package {
    // ...
    Package( /* that horrible ctor arg list */){/*...*/}
    // ...
}

public class TwoDayPackage : public Package {
    // ...
    TwoDayPackage(/* another horrible ctor */);  // declaration only
    // ...
}

and then you come along to define it

TwoDayPackage::TwoDayPackage(string sName, string sAddress,
                             string sState, string sCountry,
                             int sZIP, string rName,
                             string rAddress, string rState,
                             string rCountry, int rZIP,
                             float weight, float cost, float flat)
{

     Package::Package(sName, sAddress, sState, sCountry, sZIP,
                      rName, rAddress, rState, rCountry, rZIP,
                      weight, cost);
     flatRate = flat;
}

... but that doesn't work?  Why?  Basically, because what you're telling C++ doesn't make sense: the Package::Package is just naming the superclass's ctor and not doing anything with it.  You could create a new object of class Package by using the new operator,

     Package foo = new
         Package::Package(sName, sAddress, sState, sCountry, sZIP,
                          rName, rAddress, rState, rCountry, rZIP,
                          weight, cost);

but that's still not what you want to do; what you want is to tell C++ to contruct the Package parts of TwoDayPackage using that arg list.  You don't need to have the fully-qualified name, because the compiler already knows what the parent class is.

You could also just assign values in the child ctor, but that's inefficient, as it makes the compiler generate code for "multiple trips to the well".  So C++ has a special syntax where initializers are put after a colon, as Dirk showed.

One more thing: since you're just assigning a parameter to flat anyway, you can say

TwoDayPackage::TwoDayPackage(string sName, string sAddress,
                             string sState, string sCountry,
                             int sZIP, string rName,
                             string rAddress, string rState,
                             string rCountry, int rZIP,
                             float weight, float cost, float flat) :
    Package(sName, sAddress, sState, sCountry, sZIP,
            rName, rAddress, rState, rCountry, rZIP, weight, cost),
    flatRate(flat)
{
}

Check this section of the C++ FAQ Lite for more.

OwnerDisplayName: Charlie Martin

LastEditorDisplayName: Charlie Martin


来源: stackexchange

问:
hashtable values reordered
I have a hashtable, which contains strings for example, when I use put method as below

```<code> hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");
</code>```

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

```<code> Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());
</code>```

Thanks
Max

答: HashTable doesnot keep order.It will print randomly.You should go for LinkedHashMap.You can use LinkedHashMap in the same manner as you did for HashMap.Just put LinkedHashMap in place of HashMap.LinkedHashMap keeps the order of data in which you enter into it.</p>

ContentLicense: CC BY-SA 3.0

Title: hashtable values reordered

Body:
I have a hashtable, which contains strings for example, when I use put method as below

 hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

 Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());

Thanks
Max


问:
How should I do exception handling in my database python code for no data fetched from server or connection time out
psycopg2.DatabaseError: could not receive data from server: Connection timed out</p>

答:
Wrap it inside try/except block.
like:</p>
```<code>try:
   conn = conn = dbapi.connect(user=<>,password=<>,host=<>,database=<>)
except psycopg2.DatabaseError:
   <whatever code>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Wrap it inside try/except block.
like:

try:
   conn = conn = dbapi.connect(user=<>,password=<>,host=<>,database=<>)
except psycopg2.DatabaseError:
   <whatever code>


问:
Get a list of numbers that adds up to a number "n" (using repetition of number) - how would one consider the case of using same number multiple times?
```<code>def getList(n, input_list, caching_list):
</code>```

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

```<code>def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []
</code>```

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

答:
These 3 lines of code should raise some red flags:

if find_sum(n-i,p,p_list,sum_list) == sum_list:
    sum_list.append(i)
    return sum_list
```
<p>You have a recursive function storing its results in <code>sum_list</code>, modifying it, and also depending on its values for equality checks. This makes your program extremely difficult to reason about. Does the behavior change if you swap the arguments around the equality sign? I have no idea.</p>
<p>In general, your recursive programs should try to avoid passing their result as a parameter. Since that <code>if</code> statement is really asking whether we can make a certain sum, why not break that into a separate function?</p>
<pre class="lang-py prettyprint-override"><code>def can_sum(n, p_list, cache={}):
    if n in cache:
        return cache[n]
    if n == 0:
        return True
    if n < 0:
        return False
    return any(can_sum(n-p, p_list) for p in p_list)
</code>```

You want to use some kind of caching (otherwise, your program is exponential-time), and functools.cache is preferable if you can use outside libraries, but this will do the job.

How should your find_sum function return results without passing the result as a parameter? Just add your value to the end, exactly like your code did:

def find_sum(n, p_list):
    for p in p_list:
        if can_sum(n-p, p_list):
            return find_sum(n-p, p_list) + [p]
    return []
```

Body:
def getList(n, input_list, caching_list):

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

Body:
These 3 lines of code should raise some red flags:

if find_sum(n-i,p,p_list,sum_list) == sum_list:
    sum_list.append(i)
    return sum_list

You have a recursive function storing its results in sum_list, modifying it, and also depending on its values for equality checks. This makes your program extremely difficult to reason about. Does the behavior change if you swap the arguments around the equality sign? I have no idea.

In general, your recursive programs should try to avoid passing their result as a parameter. Since that if statement is really asking whether we can make a certain sum, why not break that into a separate function?

def can_sum(n, p_list, cache={}):
    if n in cache:
        return cache[n]
    if n == 0:
        return True
    if n < 0:
        return False
    return any(can_sum(n-p, p_list) for p in p_list)

You want to use some kind of caching (otherwise, your program is exponential-time), and functools.cache is preferable if you can use outside libraries, but this will do the job.

How should your find_sum function return results without passing the result as a parameter? Just add your value to the end, exactly like your code did:

def find_sum(n, p_list):
    for p in p_list:
        if can_sum(n-p, p_list):
            return find_sum(n-p, p_list) + [p]
    return []


问:
Solving system of equations in python
How do I solve simple system of equation like the following in python?

x = (2/3)*y + (1/3)*0

y = (2/3)*1 + (1/3)*x

I tried SymPy but couldn't figure it out.

solved the equation part

```<code>from sympy import *
from sympy.solvers.solveset import linsolve
x, y = symbols('x, y')
linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))
</code>```

Output: {(0.571428571428571, 0.857142857142857)}

Type is 'sympy.sets.sets.FiniteSet'

How do I extract just the x value to set as a variable?

Got it.

```<code>z = linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))

print(z.args[0][0])
</code>```

答:
sympy has updated to  solve() for solving the System of linear Equations. first create equations with Eq() method. and then solve those equations with solve(). linsolve() also still works.

import sympy as sp
from sympy.solvers import solve
eq1= sp.Eq(x-2/3*y-1/3*0)
eq2 = sp.Eq(1/3*x-y+2/3)
output = solve([eq1,eq2],dict=True)
```
<p>your equations are like this</p>
<pre class="lang-py prettyprint-override"><code>x−0.666666666666667y=0
0.333333333333333x−y+0.666666666666667=0
</code>```

output:

[{x:0.571428571428571, y:0.857142857142857}]
```
<p>once you get the output. <code>output</code> variable type is <code>list</code>. then take the first index <code>0</code>which is dictionary. then convert it into <code>list</code> type.</p>
<pre class="lang-py prettyprint-override"><code>values = list(output[0].values())
</code>```

will give your output like this.

[0.571428571428571, 0.857142857142857]
```
<p>then</p>
<pre class="lang-py prettyprint-override"><code>x = values[0] #0.571428571428571
y = values[1] # 0.857142857142857
</code>```

Title: Solving system of equations in python

Body:
How do I solve simple system of equation like the following in python?

x = (2/3)*y + (1/3)*0

y = (2/3)*1 + (1/3)*x

I tried SymPy but couldn't figure it out.

solved the equation part

from sympy import *
from sympy.solvers.solveset import linsolve
x, y = symbols('x, y')
linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))

Output: {(0.571428571428571, 0.857142857142857)}

Type is 'sympy.sets.sets.FiniteSet'

How do I extract just the x value to set as a variable?

Got it.

z = linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))

print(z.args[0][0])

Body:
sympy has updated to  solve() for solving the System of linear Equations. first create equations with Eq() method. and then solve those equations with solve(). linsolve() also still works.

import sympy as sp
from sympy.solvers import solve
eq1= sp.Eq(x-2/3*y-1/3*0)
eq2 = sp.Eq(1/3*x-y+2/3)
output = solve([eq1,eq2],dict=True)

your equations are like this

x−0.666666666666667y=0
0.333333333333333x−y+0.666666666666667=0

output:

[{x:0.571428571428571, y:0.857142857142857}]

once you get the output. output variable type is list. then take the first index 0which is dictionary. then convert it into list type.

values = list(output[0].values())

will give your output like this.

[0.571428571428571, 0.857142857142857]

then

x = values[0] #0.571428571428571
y = values[1] # 0.857142857142857


问:
Find closest elements of two lists - the best way
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

```<code>L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]
</code>```

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

```<code>for el1 in L1:
  for el2 in L2:
    ....
</code>```

But I'd to like to see more correct solution

答:
I don't see how an answer could be 'more correct', but this is how I'd do it. I like it more than a cramped one liner because it's still readable.

```<code>L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

def find_closest(x):
    l2_diffs = [abs(x - y) for y in L2]
    return l2_diffs.index(min(l2_diffs))

res = [(i, find_closest(x)) for i, x in enumerate(L1)]

print(res)

</code>```

Output:

```<code>[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]
</code>```

Body:
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

for el1 in L1:
  for el2 in L2:
    ....

But I'd to like to see more correct solution

Body:
I don't see how an answer could be 'more correct', but this is how I'd do it. I like it more than a cramped one liner because it's still readable.

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

def find_closest(x):
    l2_diffs = [abs(x - y) for y in L2]
    return l2_diffs.index(min(l2_diffs))

res = [(i, find_closest(x)) for i, x in enumerate(L1)]

print(res)

Output:

[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]


问:
Merge array of dynamically generated objects into single object
I'm struggling to convert the below JSON into expected JSON format using JavaScript.

Current JSON :

```<code>    {
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}
</code>```

expected JSON:

```<code>{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}
</code>```

Note: furniture in above code is only static. Apart from that all keys and values are dynamically generated.

答:
try this</p>
```<code>var furniture = {};
for (const property in jsonOrig.furniture) {
  var newObj = {};
  jsonOrig.furniture[property].forEach((value) => {
    for (const prop in value) {
      newObj[prop] = value[prop];
    }
    furniture[property] = newObj;
  });
}

var newJson = { furniture: furniture };
</code>```

Body:
I'm struggling to convert the below JSON into expected JSON format using JavaScript.

Current JSON :

    {
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}

expected JSON:

{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}

Note: furniture in above code is only static. Apart from that all keys and values are dynamically generated.

Body:
try this

var furniture = {};
for (const property in jsonOrig.furniture) {
  var newObj = {};
  jsonOrig.furniture[property].forEach((value) => {
    for (const prop in value) {
      newObj[prop] = value[prop];
    }
    furniture[property] = newObj;
  });
}

var newJson = { furniture: furniture };


问:
I need to get dynamic dependent variable value that increases when the other variable increases in PHP
Like this when x is 1000 and y becomes 0.1 and when x is 2000 and y becomes 0.2 like that in php.
Please help me if you are a good at it.you can see in here as an example </p>

答:
It seems clear that one variable depends on the other.

Maybe your best course of action would be to encapsulate that logic in a class; something as follows (please keep in mind I did not work on PHP since long time ago so the syntax might be wrong):

```<code>class MyX() {
  private $value: int = 0;

  public function setValue($value: int) : void {
    $this->value = $value;
  }

  public function getY(): float {
    return round($this->value / 10000, 10);
  }
}

$x = new MyX();
$x->setValue(1000);
print($x->getY());
</code>```

By leveraging magic methods you might get something easier to use. But the main idea is still to keep all logic in a single place.

Body:
It seems clear that one variable depends on the other.

Maybe your best course of action would be to encapsulate that logic in a class; something as follows (please keep in mind I did not work on PHP since long time ago so the syntax might be wrong):

class MyX() {
  private $value: int = 0;

  public function setValue($value: int) : void {
    $this->value = $value;
  }

  public function getY(): float {
    return round($this->value / 10000, 10);
  }
}

$x = new MyX();
$x->setValue(1000);
print($x->getY());

By leveraging magic methods you might get something easier to use. But the main idea is still to keep all logic in a single place.


问:
How to use Dataframe data in python script?
Hello everyone I'm trying to figure out how to pull data from a data frame using pandas inside my new script?

So I've got excel data saved and I use pandas to pull the data into python but how do I use that data pulled to reference?

For example :

'start': {
'date': '2022-02-22'

with date 11/17/2022 from the excel sheet.

UPDATE: the event data needs to be JSON string so if I turn the data frame into JSON how would I call this in place?

```<code>data = df.to_json(orient='columns')
print(data)
</code>```

I hope that makes sense? any help would be greatly appreciated!

[![enter image description here][1]][1]

```<code>from google_apis import create_service
from pprint import pprint
import pandas as pd
import openpyxl

service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

calendar_id_jameson = 'primary'

""""
Create an event
"""
event = {
  'summary': 'Test',
  'description': 'Date 11/17/2022',
</code>```

答:
You have a couple different methods from the Pandas data frame to retrieve the information you want. Here you can find a comprehensive guide, but if we use df.iat[x,y] as an example you can do like this:

```<code>...
df = pd.read_excel (r'C:\Users\phlfo\calendar\Case_Files.xlsx')
...
event = {
  'summary': 'Test',
  'description': f'{df.iat[5,2]}',
...
</code>```

I omitted parts of your code for clarity, but notice that you must give a string to the dictionary under 'description': 'this has to be string'. Here I used an f-string, it will replace the result from what is between curly brackets into your string.

Body:
Hello everyone I'm trying to figure out how to pull data from a data frame using pandas inside my new script?

So I've got excel data saved and I use pandas to pull the data into python but how do I use that data pulled to reference?

For example :

'start': {
'date': '2022-02-22'

with date 11/17/2022 from the excel sheet.

UPDATE: the event data needs to be JSON string so if I turn the data frame into JSON how would I call this in place?

data = df.to_json(orient='columns')
print(data)

I hope that makes sense? any help would be greatly appreciated!

[![enter image description here][1]][1]

from google_apis import create_service
from pprint import pprint
import pandas as pd
import openpyxl

service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

calendar_id_jameson = 'primary'

""""
Create an event
"""
event = {
  'summary': 'Test',
  'description': 'Date 11/17/2022',

Body:
You have a couple different methods from the Pandas data frame to retrieve the information you want. Here you can find a comprehensive guide, but if we use df.iat[x,y] as an example you can do like this:

...
df = pd.read_excel (r'C:\Users\phlfo\calendar\Case_Files.xlsx')
...
event = {
  'summary': 'Test',
  'description': f'{df.iat[5,2]}',
...

I omitted parts of your code for clarity, but notice that you must give a string to the dictionary under 'description': 'this has to be string'. Here I used an f-string, it will replace the result from what is between curly brackets into your string.


问:
How to add new references to a yaml-loaded dict?
I'm loading a yaml dictionary and would like to use some of the existing anchors to extend the dictionary before writing it out again. Is this possible?

Example, let's say I have a yaml file:

```<code>a: &a 1
b: &b 2
</code>```

With ruamel, how would I add a new value c that refereces a. In other words, how do I write:

```<code>a: &a 1
b: &b 2
c: *a
</code>```

答:
The anchored scalar 1 is loaded in ruamel.yaml as a ScalarInt and not as an integer, as on the
integer there would be no place to attach the actual anchor name, and more importantly because dumping
the same integer will not result in an anchored scalar and aliases. However when the same ScalarInt instance
is dumped you'll get an anchor for the first and aliases for all other occurences.

(ScalarInt will behave like normal integers for all common purposes, if you just need to use the loaded data.)

To get the output you want, you need to have the value that is associated with key c to be the same
as the value for a. You can just do that simply by assigning:

```<code>import sys
import ruamel.yaml

yaml_str = """\
a: &a 1
b: &b 2
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['c'] = data['a']
yaml.dump(data, sys.stdout)
</code>```

which gives:

```<code>a: &a 1
b: &b 2
c: *a
</code>```

If you want to start from Python code instead of loading some YAML with anchors,
you'll need to create the ScalarInts yourself:

```<code>import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
a_val = ruamel.yaml.scalarint.ScalarInt(1, anchor='a')
data = dict(a=a_val, b=ruamel.yaml.scalarint.ScalarInt(2, anchor='b'), c=a_val)
yaml.dump(data, sys.stdout)
</code>```

this also gives:

```<code>a: &a 1
b: &b 2
c: *a
</code>```

Body:
I'm loading a yaml dictionary and would like to use some of the existing anchors to extend the dictionary before writing it out again. Is this possible?

Example, let's say I have a yaml file:

a: &a 1
b: &b 2

With ruamel, how would I add a new value c that refereces a. In other words, how do I write:

a: &a 1
b: &b 2
c: *a

Body:
The anchored scalar 1 is loaded in ruamel.yaml as a ScalarInt and not as an integer, as on the
integer there would be no place to attach the actual anchor name, and more importantly because dumping
the same integer will not result in an anchored scalar and aliases. However when the same ScalarInt instance
is dumped you'll get an anchor for the first and aliases for all other occurences.

(ScalarInt will behave like normal integers for all common purposes, if you just need to use the loaded data.)

To get the output you want, you need to have the value that is associated with key c to be the same
as the value for a. You can just do that simply by assigning:

import sys
import ruamel.yaml

yaml_str = """\
a: &a 1
b: &b 2
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['c'] = data['a']
yaml.dump(data, sys.stdout)

which gives:

a: &a 1
b: &b 2
c: *a

If you want to start from Python code instead of loading some YAML with anchors,
you'll need to create the ScalarInts yourself:

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
a_val = ruamel.yaml.scalarint.ScalarInt(1, anchor='a')
data = dict(a=a_val, b=ruamel.yaml.scalarint.ScalarInt(2, anchor='b'), c=a_val)
yaml.dump(data, sys.stdout)

this also gives:

a: &a 1
b: &b 2
c: *a


答:
you can use this code in your :</p>
```<code> def retrieve_data(db, table_name):
    try:
        comm ="SELECT * FROM {};".format(table_name)
        with db.connect() as conn:
            column_of_sql_table = conn.execute(comm).fetchall()
        return pd.DataFrame(column_of_sql_table)

    except Exception as e:
        print(e)
        return pd.DataFrame()

df = retrieve_data(db, table_name)
if not df.empty :
    < do what ever you want>
else:
    < rise error>
</code>```

Title: How should I do exception handling in my database python code for no data fetched from server or connection time out

Body: psycopg2.DatabaseError: could not receive data from server: Connection timed out

Body:
you can use this code in your :

 def retrieve_data(db, table_name):
    try:
        comm ="SELECT * FROM {};".format(table_name)
        with db.connect() as conn:
            column_of_sql_table = conn.execute(comm).fetchall()
        return pd.DataFrame(column_of_sql_table)

    except Exception as e:
        print(e)
        return pd.DataFrame()

df = retrieve_data(db, table_name)
if not df.empty :
    < do what ever you want>
else:
    < rise error>


问:
SQL JOIN one-to-many but don't repeat previous joins
I need to create a join between two tables of companies on the COMPANY_NAME column (as there are no other common keys to join on). Subsidiary companies with the same name can exist in the tables.

The tables with the relevant data look like this:

Table A

```<code>ROW_ID | COMPANY_NAME        | REG_ID  ...
-------+---------------------+--------
1      | ABC UK LTD          | 992
2      | ABC UK LTD          | 221
3      | BOBS BAKERS PLC     | 109
4      | BOBS BAKERS PLC     | 234
5      | BOBS BAKERS PLC     | 677
6      | ADAMS ESTATE AGENTS | 309
</code>```

Table B

```<code>ROW_ID | COMPANY_NAME        | CH_REF  ...
-------+---------------------+--------
4656   | ABC UK LTD          | AE/002
7986   | ABC UK LTD          | X0294
8748   | BOBS BAKERS PLC     | F9998
9820   | BOBS BAKERS PLC     | P2944
10233  | BOBS BAKERS PLC     | L00091
14346  | ADAMS ESTATE AGENTS | XM/122
</code>```

I would like to end up with a query result that matches one-to-one on the COMPANY_NAME but doesn't duplicate the join on rows already matched. It doesn't matter about the sequence of the join, as long as all joins are unique. For example:

Ideal query result

```<code>A.ROW_ID | B.ROW_ID | A.COMPANY_NAME      | B.COMPANY_NAME      | REG_ID | CH_REF
---------+----------+---------------------+---------------------+--------+--------
1        | 4656     | ABC UK LTD          | ABC UK LTD          | 992    | AE/002
2        | 7986     | ABC UK LTD          | ABC UK LTD          | 221    | X0294
3        | 8748     | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 109    | F9998
4        | 9820     | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 234    | P2944
5        | 10233    | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 677    | L00091
6        | 14346    | ADAMS ESTATE AGENTS | ADAMS ESTATE AGENTS | 309    | XM/122
</code>```

Can this be achieved in one SQL query? I would like to try to avoid having to keep iterating on the same dataset to achieve all the matches if possible.

答:
With your sameple data each table has a given order from Row_Id so you can create a surrogate key for each using row_number() and use that for joining:

The following is compatible with most modern RDBMS.

```<code>with A as (
    select *, Row_Number() over(order by row_id) rn
    from tA
), B as (
    select *, Row_Number() over(order by row_id) rn
    from tB
)
select
  a.ROW_ID "A.Row_Id", b.ROW_ID "B.Row_Id",
  a.COMPANY_NAME "A.COMPANY_NAME",
  b.COMPANY_NAME "B.COMPANY_NAME",
  a.REG_ID, b.CH_REF
from A join B on A.rn = B.rn;
</code>```

Body:
I need to create a join between two tables of companies on the COMPANY_NAME column (as there are no other common keys to join on). Subsidiary companies with the same name can exist in the tables.

The tables with the relevant data look like this:

Table A

ROW_ID | COMPANY_NAME        | REG_ID  ...
-------+---------------------+--------
1      | ABC UK LTD          | 992
2      | ABC UK LTD          | 221
3      | BOBS BAKERS PLC     | 109
4      | BOBS BAKERS PLC     | 234
5      | BOBS BAKERS PLC     | 677
6      | ADAMS ESTATE AGENTS | 309

Table B

ROW_ID | COMPANY_NAME        | CH_REF  ...
-------+---------------------+--------
4656   | ABC UK LTD          | AE/002
7986   | ABC UK LTD          | X0294
8748   | BOBS BAKERS PLC     | F9998
9820   | BOBS BAKERS PLC     | P2944
10233  | BOBS BAKERS PLC     | L00091
14346  | ADAMS ESTATE AGENTS | XM/122

I would like to end up with a query result that matches one-to-one on the COMPANY_NAME but doesn't duplicate the join on rows already matched. It doesn't matter about the sequence of the join, as long as all joins are unique. For example:

Ideal query result

A.ROW_ID | B.ROW_ID | A.COMPANY_NAME      | B.COMPANY_NAME      | REG_ID | CH_REF
---------+----------+---------------------+---------------------+--------+--------
1        | 4656     | ABC UK LTD          | ABC UK LTD          | 992    | AE/002
2        | 7986     | ABC UK LTD          | ABC UK LTD          | 221    | X0294
3        | 8748     | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 109    | F9998
4        | 9820     | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 234    | P2944
5        | 10233    | BOBS BAKERS PLC     | BOBS BAKERS PLC     | 677    | L00091
6        | 14346    | ADAMS ESTATE AGENTS | ADAMS ESTATE AGENTS | 309    | XM/122

Can this be achieved in one SQL query? I would like to try to avoid having to keep iterating on the same dataset to achieve all the matches if possible.

Body:
With your sameple data each table has a given order from Row_Id so you can create a surrogate key for each using row_number() and use that for joining:

The following is compatible with most modern RDBMS.

with A as (
    select *, Row_Number() over(order by row_id) rn
    from tA
), B as (
    select *, Row_Number() over(order by row_id) rn
    from tB
)
select
  a.ROW_ID "A.Row_Id", b.ROW_ID "B.Row_Id",
  a.COMPANY_NAME "A.COMPANY_NAME",
  b.COMPANY_NAME "B.COMPANY_NAME",
  a.REG_ID, b.CH_REF
from A join B on A.rn = B.rn;


问:
Why use traits?
What typical scenario would traits be used for in a Rust program? I have tried to wrap my head around them, but I still don't have a clear concept as to why one would decide to use them. I understand the syntax from reading about them from here.

How would one explain them to someone as if they were 5?

答:
One way to conceptualize traits is to think of them as 'behaviors you want available to, and to operate over, a particular chunk of state'. So, if you have some struct that contains state, and you want to do something with it, you would write a trait for it.

There are two primary usages:

You are dealing with a struct in your code, and you would like that struct to know how perform some behavior. You can call the trait-defined behavior on the struct.

You would like to pass the struct to some other code (yours or a third party) that might not know anything about the struct itself, but want to perform some set of functions on it, trusting that the struct knows what to do in those cases.

In the first case, it allows you to do things like this:

```<code>struct Article {
  body: String
}

trait Saveable {
  fn save(&self) -> ();
}

impl Saveable for Article {
  fn save(&self) -> () {
    ...  // All the code you need to run to save the Article object
  }
}

// A function called by your UX
fn handle_article_update(article: Article) -> () {
  ...
  article.save()  // Call the save functionality
}
</code>```

The second case is arguably more interesting, though. Let's say you - or more probably a third party - has a function defined like this:

```<code>fn save_object(obj: Saveable) -> () {
  ...
  obj.save()
}

struct Person {
  name: String
}

impl Saveable for Person {
  fn save(&self) -> () {
    ... // Code needed to save a Person object, could be different from that needed for an Article object
  }
}

...
// Note that we are using the same function to save both of these, despite being different underlying Structs
save_object(article)
save_object(person)
</code>```

What this means is that the save_object function does not need to know anything about your custom Article struct in order to call save on it. It can simply refer to your implementation of that method in order to do so. In this way you can write custom objects that third party or generic library functions are able to act upon, because the Trait has defined a set of behaviors with a contract that the code can rely on safely.

Then the question of, 'when do you want to use a Trait' can be answered by saying: whenever you want to use behavior defined on a struct without needing to know everything about the struct - just that it has that behavior. So, in the above, you might also have an 'edit' functionality attached to Article, but not to Person. You don't want to have to change save_object to account for this, or to even care. All save_object needs to know is that the functions defined in the Saveable trait are implemented - it doesn't need to know anything else about the object to function equally well.

Another way to phrase this is to say, 'Use a trait when you want to pass an object based on what it can do, not what it is.'

Title: Why use traits?

Body:
One way to conceptualize traits is to think of them as 'behaviors you want available to, and to operate over, a particular chunk of state'. So, if you have some struct that contains state, and you want to do something with it, you would write a trait for it.

There are two primary usages:

You are dealing with a struct in your code, and you would like that struct to know how perform some behavior. You can call the trait-defined behavior on the struct.

You would like to pass the struct to some other code (yours or a third party) that might not know anything about the struct itself, but want to perform some set of functions on it, trusting that the struct knows what to do in those cases.

In the first case, it allows you to do things like this:

struct Article {
  body: String
}

trait Saveable {
  fn save(&self) -> ();
}

impl Saveable for Article {
  fn save(&self) -> () {
    ...  // All the code you need to run to save the Article object
  }
}

// A function called by your UX
fn handle_article_update(article: Article) -> () {
  ...
  article.save()  // Call the save functionality
}

The second case is arguably more interesting, though. Let's say you - or more probably a third party - has a function defined like this:

fn save_object(obj: Saveable) -> () {
  ...
  obj.save()
}

struct Person {
  name: String
}

impl Saveable for Person {
  fn save(&self) -> () {
    ... // Code needed to save a Person object, could be different from that needed for an Article object
  }
}

...
// Note that we are using the same function to save both of these, despite being different underlying Structs
save_object(article)
save_object(person)

What this means is that the save_object function does not need to know anything about your custom Article struct in order to call save on it. It can simply refer to your implementation of that method in order to do so. In this way you can write custom objects that third party or generic library functions are able to act upon, because the Trait has defined a set of behaviors with a contract that the code can rely on safely.

Then the question of, 'when do you want to use a Trait' can be answered by saying: whenever you want to use behavior defined on a struct without needing to know everything about the struct - just that it has that behavior. So, in the above, you might also have an 'edit' functionality attached to Article, but not to Person. You don't want to have to change save_object to account for this, or to even care. All save_object needs to know is that the functions defined in the Saveable trait are implemented - it doesn't need to know anything else about the object to function equally well.

Another way to phrase this is to say, 'Use a trait when you want to pass an object based on what it can do, not what it is.'


问:
python - Django built in login view not redirecting to next
I am using django auth views for authentication but after successful login it should try to redirect the user to the next GET param but it is redirecting to LOGIN_REDIRECT_URL only!
here is my url

```<code>    url(r'^login/$', auth_views.login, {'template_name': 'accounts/registered/login.html',}, name='login'),
</code>```

in my setting.py

```<code>LOGIN_REDIRECT_URL = '/'
</code>```

when a unauthenticated user wants to visit dashboard it automatically redirected to login page with next param

```<code>http://127.0.0.1:8000/accounts/login/?next=/accounts/dashboard/
</code>```

but after successful login it redirects it to

```<code>http://127.0.0.1:8000/
</code>```

it should redirect it according to next param.

答:
Link to be redirected

template.html

```<code><a href="{% url 'login_url_name' %}?next={% url 'url_name_to_be_redirected' parameter=some_pk %}">click me</a>
</code>```

urls.py

```<code>url(r'^login/$', CustomLoginView.as_view(template_name='html/custom_login.html', extra_context={'key': 'value'}, authentication_form=CustomAuthenticationForm), name='login_url_name'),
</code>```

some_login_view_file.py

```<code>from django.contrib.auth.views import LoginView
class CustomLoginView(LoginView):
    def get_success_url(self):
        try:
            next_page = self.request.POST['next']
        except:
            next_page = "/"
        return next_page
</code>```

custom_login.html

```<code><form method="post" action="{% url 'login_url_name' %}">
   {% csrf_token %}
   <input type="hidden" name="next" value="{{ request.GET.next }}">
   <div>
       {{ form.username }}
       {{ form.username.errors }}
   </div>
   <div>
        {{ form.password }}
        {{ form.password.errors }}
   </div>
   <button type="submit">Login</button>
</form>
</code>```

Body:
I am using django auth views for authentication but after successful login it should try to redirect the user to the next GET param but it is redirecting to LOGIN_REDIRECT_URL only!
here is my url

    url(r'^login/$', auth_views.login, {'template_name': 'accounts/registered/login.html',}, name='login'),

in my setting.py

LOGIN_REDIRECT_URL = '/'

when a unauthenticated user wants to visit dashboard it automatically redirected to login page with next param

http://127.0.0.1:8000/accounts/login/?next=/accounts/dashboard/

but after successful login it redirects it to

http://127.0.0.1:8000/

it should redirect it according to next param.

Body:
Link to be redirected

template.html

<a href="{% url 'login_url_name' %}?next={% url 'url_name_to_be_redirected' parameter=some_pk %}">click me</a>

urls.py

url(r'^login/$', CustomLoginView.as_view(template_name='html/custom_login.html', extra_context={'key': 'value'}, authentication_form=CustomAuthenticationForm), name='login_url_name'),

some_login_view_file.py

from django.contrib.auth.views import LoginView
class CustomLoginView(LoginView):
    def get_success_url(self):
        try:
            next_page = self.request.POST['next']
        except:
            next_page = "/"
        return next_page

custom_login.html

<form method="post" action="{% url 'login_url_name' %}">
   {% csrf_token %}
   <input type="hidden" name="next" value="{{ request.GET.next }}">
   <div>
       {{ form.username }}
       {{ form.username.errors }}
   </div>
   <div>
        {{ form.password }}
        {{ form.password.errors }}
   </div>
   <button type="submit">Login</button>
</form>


问:
SQLite importing CSV with Japanese text
I created a table in OpenOffice spreadsheet, saved it as a CSV file. It had one column in English and the others in Japanese.
I imported it into SQLite but no matter how I encode it (there are lots of options), for example UTF-8, 日本語　Windows, etc., when the table is imported the Japanese columns are all mixed up symbols and gibberish. At the point of madness I even went for ASCII encoding, but nothing worked.

I can manually input the fields and the Japanese shows up great. But I would literally need to do this a thousand times by hand if I OPenOffice and SQLite don't play nice.

Please help.

答: As a dead-sure way you can convert it to HTML with PHPs Multibyte functions and transfer it as ASCII.</p>

Title: SQLite importing CSV with Japanese text


问:
Powershell Datetime::Parseexact with multiple formats
I am trying to use parseexact , however the dates that I have are in multiple formats. I tried

```<code>$format =@('yyMMddHHmm')
[System.DateTime]::ParseExact('1605221412',$format,$null)
</code>```

and everything is fine
When I try to add another format I get an exception

```<code>$format =@('yyMMddHHmm', 'yyyyMMddHHmm')
[System.DateTime]::ParseExact('1605221412',$format,$null,[System.Globalization.DateTimeStyles]::None)
</code>```

I tried double quotes, writing inline , various ways of trying to pass an array as the second argument.

```<code>[System.DateTime]::ParseExact('1605221412','yyMMddHHmm, yyyyMMddHHmm',$null,[System.Globalization.DateTimeStyles]::None)
</code>```

What am I missing ?
Is it possible to use ParseExact for multiple formats without doing a bunch of if, then , else statements ?

答:
You are doing it just fine, the only problem is that @(..) is object[] not string[]:

$datesToTest = '1605221412', '09/02/2022', '02-09-2022'
$formats = 'yyMMddHHmm', 'yyyyMMddHHmm', 'dd/MM/yyyy', 'dd-MM-yyyy'
$datesToTest | ForEach-Object {
    [datetime]::ParseExact($_, [string[]] $formats, [cultureinfo]::InvariantCulture)
}
```

See ParseExact(String, String[], IFormatProvider, DateTimeStyles)

Body:
I am trying to use parseexact , however the dates that I have are in multiple formats. I tried

$format =@('yyMMddHHmm')
[System.DateTime]::ParseExact('1605221412',$format,$null)

and everything is fine
When I try to add another format I get an exception

$format =@('yyMMddHHmm', 'yyyyMMddHHmm')
[System.DateTime]::ParseExact('1605221412',$format,$null,[System.Globalization.DateTimeStyles]::None)

I tried double quotes, writing inline , various ways of trying to pass an array as the second argument.

[System.DateTime]::ParseExact('1605221412','yyMMddHHmm, yyyyMMddHHmm',$null,[System.Globalization.DateTimeStyles]::None)

What am I missing ?
Is it possible to use ParseExact for multiple formats without doing a bunch of if, then , else statements ?

Body:
You are doing it just fine, the only problem is that @(..) is object[] not string[]:

$datesToTest = '1605221412', '09/02/2022', '02-09-2022'
$formats = 'yyMMddHHmm', 'yyyyMMddHHmm', 'dd/MM/yyyy', 'dd-MM-yyyy'
$datesToTest | ForEach-Object {
    [datetime]::ParseExact($_, [string[]] $formats, [cultureinfo]::InvariantCulture)
}

See ParseExact(String, String[], IFormatProvider, DateTimeStyles)


问:
How to display items aligned?
this is for sure a common question but text-align and display properties are not solving it, so i must have some mistake.
What should i do to display the 3 items in the same horizontal line?

.contact__information {
  vertical-align: middle;
  margin-bottom: var(--mb-1);
  padding-right: var(--mb-.75);
  align-items: right;
  text-align: center;
  display: inline-flex;
  margin-left: auto;
  margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section></code>```

答:
Feels like an opportunity for flex.  I added borders and padding just to make it obvious what was where and did some alignment you can customize as needed

.contact.section {
  display: flex;
  flex-direction: row;/* or column if you want the first two on top */
  justify-content: flex-start;
  align-items: center;
}

 .contact__information,
 .contact__information div { /*probably need a class for the div */
  display: flex;
  flex-direction: row;
  justify-content: center;
  border: solid 1px lime;
padding:0.25rem;
}

.contact__information div {
  display: flex;
  flex-direction: column;/* or row if titles are in line with data */
  border: solid 1px pink;
}

.contact__title {
  border: solid blue 1px;
  padding: 0.5rem;
  align-self: center;
}

.contact__subtitle {
  border: solid #8d8dff 1px;
  padding: 0.5rem;
  align-self: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section></code>```

Title: How to display items aligned?

Body:
this is for sure a common question but text-align and display properties are not solving it, so i must have some mistake.
What should i do to display the 3 items in the same horizontal line?

.contact__information {
  vertical-align: middle;
  margin-bottom: var(--mb-1);
  padding-right: var(--mb-.75);
  align-items: right;
  text-align: center;
  display: inline-flex;
  margin-left: auto;
  margin-right: auto;
}

Contacte

  Contacte para mais informações

Telemóvel

      999-777-666

Email

      email.com

Morada

      Portugal

Body:
Feels like an opportunity for flex.  I added borders and padding just to make it obvious what was where and did some alignment you can customize as needed

.contact.section {
  display: flex;
  flex-direction: row;/* or column if you want the first two on top */
  justify-content: flex-start;
  align-items: center;
}

 .contact__information,
 .contact__information div { /*probably need a class for the div */
  display: flex;
  flex-direction: row;
  justify-content: center;
  border: solid 1px lime;
padding:0.25rem;
}

.contact__information div {
  display: flex;
  flex-direction: column;/* or row if titles are in line with data */
  border: solid 1px pink;
}

.contact__title {
  border: solid blue 1px;
  padding: 0.5rem;
  align-self: center;
}

.contact__subtitle {
  border: solid #8d8dff 1px;
  padding: 0.5rem;
  align-self: center;
}

<section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section>


答:
taken from another answer; though I do not know how to flag for such:

Find nearest value in numpy array

```<code>import numpy as np

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

for el1 in L1:
     print(find_nearest(L2, el1))
</code>```

Title: Find closest elements of two lists - the best way

Body:
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

for el1 in L1:
  for el2 in L2:
    ....

But I'd to like to see more correct solution

Body:
taken from another answer; though I do not know how to flag for such:

Find nearest value in numpy array

import numpy as np

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

for el1 in L1:
     print(find_nearest(L2, el1))


问:
How does one stretch an image to the shape of a polygon in Pygame?
Alternatively, how does one fill a polygon in Pygame with an image?

I've tried searching documentation but didn't turn up much, so I'm asking here to see if I missed out anything. I can use transformation matrices if needed.

Here's an example of what I want to achieve:

答:
You might be looking for pygame's alternative drawing functions from pygame.gfxdraw, what your looking is textured polygon

Note: You need to import it separately as gfxdraw doesn't import as default so you need to import it separately e.g.

```<code>import pygame
import pygame.gfxdraw
</code>```

Body:
You might be looking for pygame's alternative drawing functions from pygame.gfxdraw, what your looking is textured polygon

Note: You need to import it separately as gfxdraw doesn't import as default so you need to import it separately e.g.

import pygame
import pygame.gfxdraw


问:
ansible.inventory.Inventory class replacement from Ansible 2.4+ onwards
I'm currently using ansible 2.3.3 and trying to upgrade it to a newever version but since 2.4+ the ansible.inventory.Inventory class has been removed.

Does anybody know what is the equivalent recommended replacement of ansible.inventory.Inventory in Ansible 2.4+?

```<code>from ansible.inventory import Inventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager

inv = Inventory(
        loader = DataLoader(),
        variable_manager = VariableManager(),
        host_list = my_path,
)
</code>```

答:
There isn't a one to one replacement in the newer code but the following code can be used but note that the inventory now has a different data structure</p>
```<code>from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader

m = InventoryManager(loader=DataLoader(), sources='/path/to/inventory')

m.hosts
m.groups
</code>```

Body:
I'm currently using ansible 2.3.3 and trying to upgrade it to a newever version but since 2.4+ the ansible.inventory.Inventory class has been removed.

Does anybody know what is the equivalent recommended replacement of ansible.inventory.Inventory in Ansible 2.4+?

from ansible.inventory import Inventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager

inv = Inventory(
        loader = DataLoader(),
        variable_manager = VariableManager(),
        host_list = my_path,
)

Body:
There isn't a one to one replacement in the newer code but the following code can be used but note that the inventory now has a different data structure

from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader

m = InventoryManager(loader=DataLoader(), sources='/path/to/inventory')

m.hosts
m.groups


问:
GLIBC_2.33 not found in raspberry pi python
Error Trace:

ImportError: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.33' not found (required by /home/pi/.local/lib/python3.7/site-packages/grpc/_cython/cygrpc.cpython-37m-arm-linux-gnueabihf.so)

Scenario:

I'm using google cloud vision api to detect text in images. The program works fine on laptop but gives the above mentioned error when ran in raspberry pi. I've searched a lot but couldn't find any working solution. I'd really appreciate if any one could let me know how to solve this.

答:
GLIBC and the kernel of the OS go hand-in-hand; you basically need a newer version of your OS, if you need a more recent GLIBC

the version of the GLIBC can be quickly found out with the following command:
ldd --version


问:
Spotipy's requests keep running forever
until 2 days ago everything was working fine but lately spotipy is not working for me anymore. Even if I try something simple like this

```<code>import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="******", client_secret="******"))

print(spotify.artist("5K4W6rqBFWDnAN6FQUkS6x")['popularity'])
</code>```

it does not output any result and keeps running "forever". What can cause the problem ? Until now I tried changing the client ids and also using the authorization code flow explained here : https://spotipy.readthedocs.io/en/2.19.0/

As I have already said it was working correctly before, I have no idea what happened

Thanks

答: I found a way to partially solve the problem : get a new token from the spotify for developers website and substitute it in the .cache file. The problem will be solved but the process might need to be done again.</p>

Title: Spotipy's requests keep running forever

Body:
until 2 days ago everything was working fine but lately spotipy is not working for me anymore. Even if I try something simple like this

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="******", client_secret="******"))

print(spotify.artist("5K4W6rqBFWDnAN6FQUkS6x")['popularity'])

it does not output any result and keeps running "forever". What can cause the problem ? Until now I tried changing the client ids and also using the authorization code flow explained here : https://spotipy.readthedocs.io/en/2.19.0/

As I have already said it was working correctly before, I have no idea what happened

Thanks


问:
hashtable values reordered
I have a hashtable, which contains strings for example, when I use put method as below

```<code> hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");
</code>```

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

```<code> Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());
</code>```

Thanks
Max

答:
A Hashtable does not guarantee any kind of ordering.

If you want to preserve insertion order, use a LinkedHashMap. However, the contract is slightly different than a Hashtable in that it allows null elements.

Title: hashtable values reordered

Body:
I have a hashtable, which contains strings for example, when I use put method as below

 hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

 Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());

Thanks
Max


问:
Blazor WebAssembly: Update single row in Data Grid / Table
I would like to use Data Grid/Table with Virtualize to display list of items. When one user edits data in single row, it should notify others about changes and UI should be updated for every user. Is any way to update only single row without refresh all the list for others client?

Page

答:
The simple answer in NO you can't update just a row, and a comprehensive answer that details how to build the infrastructure to do this is beyond the scope of a StackOverflow answer.

Here's a short precis:

You need your data in view services.

Your UI components need to subscribe to events in these view services whenever something in a list is updated and needs refreshing.

You need to call the RefreshDataAsync method on the visualize component from your page to update the row in the component.

You should probably be using ItemProvider in the Visualize component to minimize list paging.

Ask if you want help on specifics.


问:
Plot a vector of colors in R
I have this vector of colours in R:

```<code>"#88FF00" "#54FF00" "#FFFF00" "#13FF00" "#50FF00" "#87FF00" "#FDFB02" "#B8FF00" "#6DFF00"
"#ECFF00" "#CBFF00" "#EDFF00" "#39FF00" "#B7FF00" "#75FF00" "#65FF00" "#C2FF00" "#25FF00"
"#9AFF00" "#E6FF00" "#58FF00" "#E5CA1A" "#DEFF00" "#9AFF00" "#21FF00" "#35FF00" "#3AFF00"
"#D0912F" "#FF0000" "#F7EF08" "#40FF00" "#DA7325" "#D8B027" "#DAFF00" "#55FF00" "#F8F007"
"#46FF00" "#69FF00" "#B8FF00" "#37FF00" "#32FF00" "#60FF00" "#7CFF00" "#00FF00" "#50FF00"
"#F3E60C" "#DFBE20" "#7FFF00" "#F7EF08" "#99FF00" "#13FF00" "#DA7325" "#13FF00"
</code>```

And I want to plot them in this order, something such as a heatmap. I had been toying with the image function but the colours are reordered and even modified by the image function.

The code that I tried is the following, when cols is the vector of colors mentioned above:

```<code>  image(1:nrow(expressionOrdered), 1:ncol(expressionOrdered), as.matrix(expressionOrdered), col= cols,xlab="",ylab="")
</code>```

Title: Plot a vector of colors in R

Body:
I have this vector of colours in R:

"#88FF00" "#54FF00" "#FFFF00" "#13FF00" "#50FF00" "#87FF00" "#FDFB02" "#B8FF00" "#6DFF00"
"#ECFF00" "#CBFF00" "#EDFF00" "#39FF00" "#B7FF00" "#75FF00" "#65FF00" "#C2FF00" "#25FF00"
"#9AFF00" "#E6FF00" "#58FF00" "#E5CA1A" "#DEFF00" "#9AFF00" "#21FF00" "#35FF00" "#3AFF00"
"#D0912F" "#FF0000" "#F7EF08" "#40FF00" "#DA7325" "#D8B027" "#DAFF00" "#55FF00" "#F8F007"
"#46FF00" "#69FF00" "#B8FF00" "#37FF00" "#32FF00" "#60FF00" "#7CFF00" "#00FF00" "#50FF00"
"#F3E60C" "#DFBE20" "#7FFF00" "#F7EF08" "#99FF00" "#13FF00" "#DA7325" "#13FF00"

And I want to plot them in this order, something such as a heatmap. I had been toying with the image function but the colours are reordered and even modified by the image function.

The code that I tried is the following, when cols is the vector of colors mentioned above:

  image(1:nrow(expressionOrdered), 1:ncol(expressionOrdered), as.matrix(expressionOrdered), col= cols,xlab="",ylab="")

Body:
The contributed R package hues has a function named swatch that can generate the output shown here from a vector of colors.

x <- c("#88FF00", "#54FF00", "#FFFF00", "#13FF00",
       "#50FF00", "#87FF00", "#FDFB02", "#B8FF00", "#6DFF00",
       "#ECFF00", "#CBFF00", "#EDFF00", "#39FF00", "#B7FF00",
       "#75FF00", "#65FF00", "#C2FF00", "#25FF00", "#9AFF00",
       "#E6FF00", "#58FF00", "#E5CA1A", "#DEFF00", "#9AFF00",
       "#21FF00", "#35FF00", "#3AFF00", "#D0912F", "#FF0000",
       "#F7EF08", "#40FF00", "#DA7325", "#D8B027", "#DAFF00",
       "#55FF00", "#F8F007", "#46FF00", "#69FF00", "#B8FF00",
       "#37FF00", "#32FF00", "#60FF00", "#7CFF00", "#00FF00",
       "#50FF00", "#F3E60C", "#DFBE20", "#7FFF00", "#F7EF08",
       "#99FF00", "#13FF00", "#DA7325", "#13FF00")
hues::swatch(x)


问:
Remove empty cells and move content to the left Python
I have an Excel file which contains the following structure with no header or index - I've added just the column header from Excel without existing in my table:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
NaN
NaN
...
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
NaN
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
NaN
NaN
...
asdasdq2ew12332

I would need that all the cells that contains NaN to be removed and while NaN, move the cells to the left.

Output should look like:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
asdasdq2ew12332

I have found this similar question dropped on Stackoverflow, but the answer is not doing any change:

```<code>import pandas as pd

df = pd.read_excel('test.xlsx')
df = df.apply(lambda x: pd.Series(x.dropna().values))
df = df.fillna('')

df.to_excel("test_modified.xlsx", index=False, header=False)
</code>```

Any ideas how can achieve this?

Thank you.

答:
One solution I thought of would be to for each row, sort the row with a custom sorting function that returned 0 for NaN and 1 for non-NaN, effectively moving (but without changing the order of) all non-NaN values to be consecutive, and leaving the NaNs at the end:

```<code>new_df = df.apply(lambda row: pd.Series(sorted(row.tolist(), key=lambda x: np.isnan(x) if isinstance(x, float) else 0), index=row.index), axis=1)
</code>```

Output:

```<code>>>> new_df
     A    B           C                D                E                J   K
0  ABC  XLS  1231341231  123123asdad1923  123123asdad1923              NaN NaN
1  DEF  XLS  1231231231  1231823asda9123         askda213  123123asdad1923 NaN
2  XYZ  XLS  1231231233  2138820394832sd  asdasdq2ew12332              NaN NaN
</code>```

Body:
I have an Excel file which contains the following structure with no header or index - I've added just the column header from Excel without existing in my table:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
NaN
NaN
...
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
NaN
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
NaN
NaN
...
asdasdq2ew12332

I would need that all the cells that contains NaN to be removed and while NaN, move the cells to the left.

Output should look like:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
asdasdq2ew12332

I have found this similar question dropped on Stackoverflow, but the answer is not doing any change:

import pandas as pd

df = pd.read_excel('test.xlsx')
df = df.apply(lambda x: pd.Series(x.dropna().values))
df = df.fillna('')

df.to_excel("test_modified.xlsx", index=False, header=False)

Any ideas how can achieve this?

Thank you.

Body:
One solution I thought of would be to for each row, sort the row with a custom sorting function that returned 0 for NaN and 1 for non-NaN, effectively moving (but without changing the order of) all non-NaN values to be consecutive, and leaving the NaNs at the end:

new_df = df.apply(lambda row: pd.Series(sorted(row.tolist(), key=lambda x: np.isnan(x) if isinstance(x, float) else 0), index=row.index), axis=1)

Output:

>>> new_df
     A    B           C                D                E                J   K
0  ABC  XLS  1231341231  123123asdad1923  123123asdad1923              NaN NaN
1  DEF  XLS  1231231231  1231823asda9123         askda213  123123asdad1923 NaN
2  XYZ  XLS  1231231233  2138820394832sd  asdasdq2ew12332              NaN NaN


问:
pandas multiply using dictionary values across several columns
Given the following dataframe:

```<code>import pandas as pd
df = pd.DataFrame({
    'a': [1,2,3,4,5],
    'b': [5,4,3,3,4],
    'c': [3,2,4,3,10],
    'd': [3, 2, 1, 1, 1]
})
</code>```

And the following list of parameters:

```<code>params = {'a': 2.5, 'b': 3.0, 'c': 1.3, 'd': 0.9}
</code>```

Produce the following desired output:

```<code>   a  b   c  d  output
0  1  5   3  3    24.1
1  2  4   2  2    21.4
2  3  3   4  1    22.6
3  4  3   3  1    23.8
4  5  4  10  1    38.4
</code>```

I have been using this to produce the result:

```<code>df['output'] = [np.sum(params[col] * df.loc[idx, col] for col in df)
                 for idx in df.index]
</code>```

However, this is a very slow approach and I'm thinking there has to be a better way using built-in pandas functionality.

I also thought of this:

```<code># Line up the parameters
col_sort_key = list(df)
params_sorted = sorted(params.items(), key=lambda k: col_sort_key.index(k[0]))

# Repeat the parameters *n* number of times
values = [v for k, v in params_sorted]
values = np.array([values] * df.shape[0])

values
array([[ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9]])

# Multiply and add
product = df[col_sort_key].values * values
product
array([[  2.5,  15. ,   3.9,   2.7],
       [  5. ,  12. ,   2.6,   1.8],
       [  7.5,   9. ,   5.2,   0.9],
       [ 10. ,   9. ,   3.9,   0.9],
       [ 12.5,  12. ,  13. ,   0.9]])

np.sum(product, axis=1)
array([ 24.1,  21.4,  22.6,  23.8,  38.4])
</code>```

But that seems a bit convoluted! Any thoughts on a native pandas try?

答:
You can do

```<code>(df*params).sum(axis=1)
</code>```

Tested on pandas 1.2.4.

Body:
Given the following dataframe:

import pandas as pd
df = pd.DataFrame({
    'a': [1,2,3,4,5],
    'b': [5,4,3,3,4],
    'c': [3,2,4,3,10],
    'd': [3, 2, 1, 1, 1]
})

And the following list of parameters:

params = {'a': 2.5, 'b': 3.0, 'c': 1.3, 'd': 0.9}

Produce the following desired output:

   a  b   c  d  output
0  1  5   3  3    24.1
1  2  4   2  2    21.4
2  3  3   4  1    22.6
3  4  3   3  1    23.8
4  5  4  10  1    38.4

I have been using this to produce the result:

df['output'] = [np.sum(params[col] * df.loc[idx, col] for col in df)
                 for idx in df.index]

However, this is a very slow approach and I'm thinking there has to be a better way using built-in pandas functionality.

I also thought of this:

# Line up the parameters
col_sort_key = list(df)
params_sorted = sorted(params.items(), key=lambda k: col_sort_key.index(k[0]))

# Repeat the parameters *n* number of times
values = [v for k, v in params_sorted]
values = np.array([values] * df.shape[0])

values
array([[ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9]])

# Multiply and add
product = df[col_sort_key].values * values
product
array([[  2.5,  15. ,   3.9,   2.7],
       [  5. ,  12. ,   2.6,   1.8],
       [  7.5,   9. ,   5.2,   0.9],
       [ 10. ,   9. ,   3.9,   0.9],
       [ 12.5,  12. ,  13. ,   0.9]])

np.sum(product, axis=1)
array([ 24.1,  21.4,  22.6,  23.8,  38.4])

But that seems a bit convoluted! Any thoughts on a native pandas try?

Body:
You can do

(df*params).sum(axis=1)

Tested on pandas 1.2.4.


问:
How to query distinct count distibution in elasticsearch
Cardinality aggregation query calculates an approximate count of distinct values. How we can calculate the cardinality distribution of documents?

For example suppose we have:

```<code>a,a,a,b,b,b,c,c,d,d,e
</code>```

and distinct count distribution is:

```<code>3: 2 # count of distint element that have 3 occurnes (a, b)
2: 2 # c, d
1: 1 # e
</code>```

答:
Actually you cannot do aggregations like this.

But, using transform API (https://www.elastic.co/guide/en/elasticsearch/reference/current/transform-examples.html) you could create a new index to do a simple terms aggregation:

```<code>PUT _transform/so
{
  "dest" : {
   "index" : "my-so"
  },
  "source": {
    "index": "my-index"
  },
  "pivot": {
    "group_by": {
      "country": {
        "terms": {
          "field": "letter"
        }
      }
    },
    "aggregations": {
      "cardinality": {
        "value_count": {
          "field" : "letter"
        }
      }
    }
  }
}
</code>```

This will give you:

```<code>[
    {
      "country" : "a",
      "cardinality" : 22
    },
    {
      "country" : "b",
      "cardinality" : 4
    },
    {
      "country" : "c",
      "cardinality" : 5049
    }...
</code>```

Then, you can use simple terms or histogram aggregation:

```<code>GET /my-so/_search
{
  "size" : 0,
  "aggs": {
    "cc": {
      "terms": {
        "field": "cardinality"
      }
    }
  }
}
</code>```

Body:
Cardinality aggregation query calculates an approximate count of distinct values. How we can calculate the cardinality distribution of documents?

For example suppose we have:

a,a,a,b,b,b,c,c,d,d,e

and distinct count distribution is:

3: 2 # count of distint element that have 3 occurnes (a, b)
2: 2 # c, d
1: 1 # e

Body:
Actually you cannot do aggregations like this.

But, using transform API (https://www.elastic.co/guide/en/elasticsearch/reference/current/transform-examples.html) you could create a new index to do a simple terms aggregation:

PUT _transform/so
{
  "dest" : {
   "index" : "my-so"
  },
  "source": {
    "index": "my-index"
  },
  "pivot": {
    "group_by": {
      "country": {
        "terms": {
          "field": "letter"
        }
      }
    },
    "aggregations": {
      "cardinality": {
        "value_count": {
          "field" : "letter"
        }
      }
    }
  }
}

This will give you:

[
    {
      "country" : "a",
      "cardinality" : 22
    },
    {
      "country" : "b",
      "cardinality" : 4
    },
    {
      "country" : "c",
      "cardinality" : 5049
    }...

Then, you can use simple terms or histogram aggregation:

GET /my-so/_search
{
  "size" : 0,
  "aggs": {
    "cc": {
      "terms": {
        "field": "cardinality"
      }
    }
  }
}


问:
Change font size in WPF compatible with Ease of Access functions
I am working on a simple WPF app that needs to be accessible for people with impaired vision.

I am testing my app with the Windows 10 -> Settings -> Ease of Access -> Display -> Make text Bigger slider setting.

I have some section titles (TextBlock) that I want to have a bigger font than the rest of the labels and text in the window. However, if I use the FontSize attribute to make it bigger it is no longer affected by changes to the system text size. Thus, while all other text that hasn't FontSize set gets bigger, the ones that do remain at their fixed size.

Is there a simple way to make some text relatively bigger than the rest while not setting a specific font size value?

答:
Is there a simple way to make some text relatively bigger than the rest while not setting a specific font size value?

I am afraid there is no support for relative font sizes in WPF but you could try to apply a ScaleTransform:

```<code><TextBlock Text="Bigger">
    <TextBlock.RenderTransform>
        <ScaleTransform ScaleX="1.2" ScaleY="1.2" />
    </TextBlock.RenderTransform>
</TextBlock>
</code>```

Body:
Is there a simple way to make some text relatively bigger than the rest while not setting a specific font size value?

I am afraid there is no support for relative font sizes in WPF but you could try to apply a ScaleTransform:

<TextBlock Text="Bigger">
    <TextBlock.RenderTransform>
        <ScaleTransform ScaleX="1.2" ScaleY="1.2" />
    </TextBlock.RenderTransform>
</TextBlock>


问:
FAILURE: Build failed with an exception. * What went wrong: Unable to start the daemon process
FAILURE: Build failed with an exception.

What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/6.7/userguide/gradle_daemon.html
Process command line: C:\Program Files\Android\Android Studio\jre\bin\java.exe -Xmx512M -Dfile.encoding=windows-1252 -Duser.country=IN -Duser.language=en -Duser.variant -cp C:\Users\user.gradle\wrapper\dists\gradle-6.7-all\cuy9mc7upwgwgeb72wkcrupxe\gradle-6.7\lib\gradle-launcher-6.7.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.7
Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for object heap

答:
Turn Off The Mobile Hotspot Of Your Computer

If you're running into this problem, chances are high that your laptop's mobile hotspot is turned on. Switch off your hotspot and try rebuilding again. It works like magic.


问:
A generic error occurred in GDI+
I loaded an image into a Picture Box using:

```<code>picturebox1.Image = Image.FromFile()
</code>```

and I save it by using:

```<code>Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);
</code>```

It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:

A generic error occurred in GDI+

So what can I do to solve this problem??

答:
That because the image file is used by your picturebox1.Image, try to save it to different file path instead:

```<code>picturebox1.Image = Image.FromFile(FileName);
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(@"New File Name", ImageFormat.Bmp);
</code>```

Edit: You could also add a copy from the image at the first place like:

```<code>picturebox1.Image = new Bitmap(Image.FromFile(FileName));
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);//no error will occurs here.
</code>```

Title: A generic error occurred in GDI+

Body:
I loaded an image into a Picture Box using:

picturebox1.Image = Image.FromFile()

and I save it by using:

Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);

It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:

A generic error occurred in GDI+

So what can I do to solve this problem??

Body:
That because the image file is used by your picturebox1.Image, try to save it to different file path instead:

picturebox1.Image = Image.FromFile(FileName);
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(@"New File Name", ImageFormat.Bmp);

Edit: You could also add a copy from the image at the first place like:

picturebox1.Image = new Bitmap(Image.FromFile(FileName));
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);//no error will occurs here.


问:
Message object .edit() stops working after some time
First I create an object

```<code>var queue = {1:{},2:{},3:{}};
</code>```

And then I store the message based on QueueKey, or edit if it's already created

```<code>        if (typeof queue[QueueKey].messageOBJ == 'undefined')
        {
            queue[QueueKey].messageOBJ = await configChannel.send({ embeds: [getEmbedFloor(QueueKey)] });
        }
        else
        {
            queue[QueueKey].messageOBJ = await queue[QueueKey].messageOBJ.edit({ embeds: [getEmbedFloor(QueueKey)] });
        }
</code>```

everything starts working well but after sometime(1~2 hours) bot stops editing the already created message, looks like it lose object reference.
It not pops any error message or code break, seems like the message was edited sucessfully but the real message in discord still the same

I'm thinking in store the messageID instead the whole object and search for the message ID with .fetch() but this will lead to other problems

is there any way to store message Objects properly?

答:
I discovered my problem, actually bot was editing the message to frequently, so after some time discord "auto ban" my bot for some time, something like a cooldown, só it starts to get slower and slower, up to seems like it is stuck.

My solution was check message before edit, to compare if the changes in message are really necessary, before edit or not

Body:
First I create an object

var queue = {1:{},2:{},3:{}};

And then I store the message based on QueueKey, or edit if it's already created

        if (typeof queue[QueueKey].messageOBJ == 'undefined')
        {
            queue[QueueKey].messageOBJ = await configChannel.send({ embeds: [getEmbedFloor(QueueKey)] });
        }
        else
        {
            queue[QueueKey].messageOBJ = await queue[QueueKey].messageOBJ.edit({ embeds: [getEmbedFloor(QueueKey)] });
        }

everything starts working well but after sometime(1~2 hours) bot stops editing the already created message, looks like it lose object reference.
It not pops any error message or code break, seems like the message was edited sucessfully but the real message in discord still the same

I'm thinking in store the messageID instead the whole object and search for the message ID with .fetch() but this will lead to other problems

is there any way to store message Objects properly?


问:
java format string printing unable to print
I'm unable to run the code, it says it cannot resolve println with the parameters.</p>
```<code>public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }
</code>```

答:
System.out.println just prints, literally, a string, and then prints a newline.

You want System.out.printf, which prints 'format strings' as you're using here. Note that it does not print newlines. Just add \n, %n doesn't really do what you think it does (it would print e.g. \r\n on windows. This is unneccessary and sometimes even actively harmful, hence, don't do that unless you really know you need it. You need it if you're emitting text files that need to look good when opened with notepad.exe. That's... about the one and only thing on the planet that requires \r\n to function. Everything else either accepts both \r\n, or only accepts \n, hence, just.. write \n, not %n).

Thus:

```<code>System.out.printf("%s : %d\n", this.getName(), i);
</code>```

Body:
I'm unable to run the code, it says it cannot resolve println with the parameters.

public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }

Body:
System.out.println just prints, literally, a string, and then prints a newline.

You want System.out.printf, which prints 'format strings' as you're using here. Note that it does not print newlines. Just add \n, %n doesn't really do what you think it does (it would print e.g. \r\n on windows. This is unneccessary and sometimes even actively harmful, hence, don't do that unless you really know you need it. You need it if you're emitting text files that need to look good when opened with notepad.exe. That's... about the one and only thing on the planet that requires \r\n to function. Everything else either accepts both \r\n, or only accepts \n, hence, just.. write \n, not %n).

Thus:

System.out.printf("%s : %d\n", this.getName(), i);


问:
OnEdit Cell Index not working with multiple inputs
I'm trying to write a piece of code that whenever someone on our rosters is terminated it will capture their data, put them into a "termed associates" sheet and delete them from the roster.

The code I wrote works fine for single instances of the change (though it is a bit slow), but the main problem is if I change multiple people to "TERM" in quick succession, it breaks and sometimes will delete rows that aren't the row meant to be deleted.

Here's my code:

```<code>    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const termSheet = ss.getSheetByName('Term Tracker');
    const check = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();

    function deleteTerm() {
    if(check == 'TERM'){

    //grabs the cell that has just been edited, finds the index of the row
    let sheet = ss.getActiveSheet();
    let cell = ss.getActiveCell();
    let index = cell.getRowIndex();

    //grabs data and posts to new sheet
    //grabs values to inset into email
    let read = sheet.getRange(index,1,1,55).getValues();
    let name = sheet.getRange(index, 4).getValue();
    let shift = sheet.getRange(index,1).getValue();
    termSheet.insertRowBefore(2);
    termSheet.getRange(2,1,1,55).setValues(read);

    //deletes the index row
    sheet.deleteRow(index)

    //mails me a notification someone was termed
    MailApp.sendEmail({
    to: "{myemail}",
    subject: "New Term, " + name ,
    body: "There is a new term of " + name + ", please confirm the term reason and term date.
    They are on the " + shift + " roster"
    });

    }}

</code>```

Any ideas on exactly what I'm doing wrong? I'm still very new to coding, so I'm sure that the code isn't very great. Any feedback would be lovely as well. :)

答:
This should work faster

But any expectation of consistently fast response for an onEdit function is a hopeless wish that is not going to be fulfilled.  You must be patient and give it time to operate.

```<code>function onEdit(e) {
  const sh = e.range.getSheet();
  const tsh = e.source.getSheetByName('Term Tracker');
  if (e.value == 'TERM') {
    let vs = sh.getRange(e.range.rowStart, 1, 1, 55).getValues();
    let name = vs[0][3];
    let shift = vs[0][0];
    tsh.insertRowBefore(2);
    tsh.getRange(2, 1, 1, 55).setValues(vs);
    sh.deleteRow(e.range.rowStart);
    MailApp.sendEmail({to: "{myemail}",subject: "New Term, " + name,body: "There is a new term of " + name + ", please confirm the term reason and term date. They are on the " + shift + " roster"});
  }
}
</code>```

Body:
I'm trying to write a piece of code that whenever someone on our rosters is terminated it will capture their data, put them into a "termed associates" sheet and delete them from the roster.

The code I wrote works fine for single instances of the change (though it is a bit slow), but the main problem is if I change multiple people to "TERM" in quick succession, it breaks and sometimes will delete rows that aren't the row meant to be deleted.

Here's my code:

    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const termSheet = ss.getSheetByName('Term Tracker');
    const check = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();

    function deleteTerm() {
    if(check == 'TERM'){

    //grabs the cell that has just been edited, finds the index of the row
    let sheet = ss.getActiveSheet();
    let cell = ss.getActiveCell();
    let index = cell.getRowIndex();

    //grabs data and posts to new sheet
    //grabs values to inset into email
    let read = sheet.getRange(index,1,1,55).getValues();
    let name = sheet.getRange(index, 4).getValue();
    let shift = sheet.getRange(index,1).getValue();
    termSheet.insertRowBefore(2);
    termSheet.getRange(2,1,1,55).setValues(read);

    //deletes the index row
    sheet.deleteRow(index)

    //mails me a notification someone was termed
    MailApp.sendEmail({
    to: "{myemail}",
    subject: "New Term, " + name ,
    body: "There is a new term of " + name + ", please confirm the term reason and term date.
    They are on the " + shift + " roster"
    });

    }}

Any ideas on exactly what I'm doing wrong? I'm still very new to coding, so I'm sure that the code isn't very great. Any feedback would be lovely as well. :)

Body:
This should work faster

But any expectation of consistently fast response for an onEdit function is a hopeless wish that is not going to be fulfilled.  You must be patient and give it time to operate.

function onEdit(e) {
  const sh = e.range.getSheet();
  const tsh = e.source.getSheetByName('Term Tracker');
  if (e.value == 'TERM') {
    let vs = sh.getRange(e.range.rowStart, 1, 1, 55).getValues();
    let name = vs[0][3];
    let shift = vs[0][0];
    tsh.insertRowBefore(2);
    tsh.getRange(2, 1, 1, 55).setValues(vs);
    sh.deleteRow(e.range.rowStart);
    MailApp.sendEmail({to: "{myemail}",subject: "New Term, " + name,body: "There is a new term of " + name + ", please confirm the term reason and term date. They are on the " + shift + " roster"});
  }
}


问:
How to list last modified file in S3 using Python
I'm trying to get the last modified file in S3 using the following:

```<code>def lambda_handler(event, context):

    import boto3

    bucket_name = "arn:aws-us-gov:s3:::some_bucket_name/some_folder/"

    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))

    s3 = boto3.client('s3')
    objs = s3.list_objects_v2(Bucket=bucket_name)['Contents']
    last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0]
</code>```

...and although things look correct, I keep getting the error:

```<code>"errorMessage": "Parameter validation failed:\nInvalid bucket name \"arn:aws-us-gov:s3:::some_bucket_name/some_folder/\": Bucket name must match the regex \"^[a-zA-Z0-9.\\-_]{1,255}$\" or be an ARN matching the regex \"^arn:(aws).*:(s3|s3-object-lambda):[a-z\\-0-9]*:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\\-.]{1,63}$|^arn:(aws).*:s3-outposts:[a-z\\-0-9]+:[0-9]{12}:outpost[/:][a-zA-Z0-9\\-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9\\-]{1,63}$\"",
</code>```

What am I missing in the bucket name? I copied the ARN from the console and still cannot seem to produce the expected result. I'm not a RegEx guru so it's hard for me to discern what could be missing from the arn. To test, I replaced the bucket name with some random name and got an error that the bucket does not exist; as expected. I'm slightly confused what the issue is. Any assistance would be greatly appreciated.

答:
OK. I've resolved the "issue" and now have what I need.

```<code>import boto3

bucket_name = "actual_bucket_name"
prefix = "path/to/files/"

get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))

s3 = boto3.client('s3')
objs = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix, Delimiter='/' ['Contents']
last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0]
</code>```

Thank you for the pointers. I was readin through the documentation, however, we know how it can be after staring at walls of text after a while. The "issue" was me not acutely comprehending.

Body:
I'm trying to get the last modified file in S3 using the following:

def lambda_handler(event, context):

    import boto3

    bucket_name = "arn:aws-us-gov:s3:::some_bucket_name/some_folder/"

    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))

    s3 = boto3.client('s3')
    objs = s3.list_objects_v2(Bucket=bucket_name)['Contents']
    last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0]

...and although things look correct, I keep getting the error:

"errorMessage": "Parameter validation failed:\nInvalid bucket name \"arn:aws-us-gov:s3:::some_bucket_name/some_folder/\": Bucket name must match the regex \"^[a-zA-Z0-9.\\-_]{1,255}$\" or be an ARN matching the regex \"^arn:(aws).*:(s3|s3-object-lambda):[a-z\\-0-9]*:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\\-.]{1,63}$|^arn:(aws).*:s3-outposts:[a-z\\-0-9]+:[0-9]{12}:outpost[/:][a-zA-Z0-9\\-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9\\-]{1,63}$\"",

What am I missing in the bucket name? I copied the ARN from the console and still cannot seem to produce the expected result. I'm not a RegEx guru so it's hard for me to discern what could be missing from the arn. To test, I replaced the bucket name with some random name and got an error that the bucket does not exist; as expected. I'm slightly confused what the issue is. Any assistance would be greatly appreciated.

Body:
OK. I've resolved the "issue" and now have what I need.

import boto3

bucket_name = "actual_bucket_name"
prefix = "path/to/files/"

get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))

s3 = boto3.client('s3')
objs = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix, Delimiter='/' ['Contents']
last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0]

Thank you for the pointers. I was readin through the documentation, however, we know how it can be after staring at walls of text after a while. The "issue" was me not acutely comprehending.