问:
DASK: Typerrror: Column assignment doesn't support type numpy.ndarray whereas Pandas works fine
I'm using Dask to read in a 10m row csv+ and perform some calculations. So far it's proving to be 10x faster than Pandas.

I have a piece of code, below, that when used with pandas works fine, but with dask throws a type error. I am unsure of how to overcome the typerror. It seems like an array is being handed back to the dataframe/column by the select function when using dask, but not when using pandas? But I don't want to switch the whole thing back to pandas and lose the 10x performance benefit.

This answer is the result of some help of some others on Stack Overflow, however I think that question has deviated far enough from the initial question that this is altogether different. Code below.

PANDAS: Works
Time Taken excluding AndHeathSolRadFact: 40 seconds

```<code>import pandas as pd
import numpy as np

from timeit import default_timer as timer
start = timer()
df = pd.read_csv(r'C:\Users\i5-Desktop\Downloads\Weathergrids.csv')
df['DateTime'] = pd.to_datetime(df['Date'], format='%Y-%d-%m %H:%M')
df['Month'] = df['DateTime'].dt.month
df['Grass_FMC'] = (97.7+4.06*df['RH'])/(df['Temperature']+6)-0.00854*df['RH']+3000/df['Curing']-30

df["AndHeathSolRadFact"] = np.select(
    [
    (df['Month'].between(8,12)),
    (df['Month'].between(1,2) & df['CloudCover']>30)
    ],  #list of conditions
    [1, 1],     #list of results
    default=0)    #default if no match

print(df.head())
#print(ddf.tail())
end = timer()
print(end - start)

</code>```

DASK: BROKEN
Time Taken excluding AndHeathSolRadFact: 4 seconds

```<code>import dask.dataframe as dd
import dask.multiprocessing
import dask.threaded
import pandas as pd
import numpy as np

# Dataframes implement the Pandas API
import dask.dataframe as dd

from timeit import default_timer as timer
start = timer()
ddf = dd.read_csv(r'C:\Users\i5-Desktop\Downloads\Weathergrids.csv')
ddf['DateTime'] = dd.to_datetime(ddf['Date'], format='%Y-%d-%m %H:%M')
ddf['Month'] = ddf['DateTime'].dt.month
ddf['Grass_FMC'] = (97.7+4.06*ddf['RH'])/(ddf['Temperature']+6)-0.00854*ddf['RH']+3000/ddf['Curing']-30

ddf["AndHeathSolRadFact"] = np.select(
    [
    (ddf['Month'].between(8,12)),
    (ddf['Month'].between(1,2) & ddf['CloudCover']>30)
    ],  #list of conditions
    [1, 1],     #list of results
    default=0)    #default if no match

print(ddf.head())
#print(ddf.tail())
end = timer()
print(end - start)

</code>```

Error

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-86c08f38bce6> in <module>
     29     ],  #list of conditions
     30     [1, 1],     #list of results
---> 31     default=0)    #default if no match
     32
     33

~\Anaconda3\lib\site-packages\dask\dataframe\core.py in __setitem__(self, key, value)
   3276             df = self.assign(**{k: value for k in key})
   3277         else:
-> 3278             df = self.assign(**{key: value})
   3279
   3280         self.dask = df.dask

~\Anaconda3\lib\site-packages\dask\dataframe\core.py in assign(self, **kwargs)
   3510                 raise TypeError(
   3511                     "Column assignment doesn't support type "
-> 3512                     "{0}".format(typename(type(v)))
   3513                 )
   3514             if callable(v):

TypeError: Column assignment doesn't support type numpy.ndarray
</code>```

Sample Weathegrids CSV

```<code>Location,Date,Temperature,RH,WindDir,WindSpeed,DroughtFactor,Curing,CloudCover
1075,2019-20-09 04:00,6.8,99.3,143.9,5.6,10.0,93.0,1.0
1075,2019-20-09 05:00,6.4,100.0,93.6,7.2,10.0,93.0,1.0
1075,2019-20-09 06:00,6.7,99.3,130.3,6.9,10.0,93.0,1.0
1075,2019-20-09 07:00,8.6,95.4,68.5,6.3,10.0,93.0,1.0
1075,2019-20-09 08:00,12.2,76.0,86.4,6.1,10.0,93.0,1.0
</code>```

答: I just had a similar problem, and I was able to get it to work by converting the ndarray into a Dask array.  I also had to ensure the number of partitions matched between the ndarray and the Dask DataFrame.

Body:
I'm using Dask to read in a 10m row csv+ and perform some calculations. So far it's proving to be 10x faster than Pandas.

I have a piece of code, below, that when used with pandas works fine, but with dask throws a type error. I am unsure of how to overcome the typerror. It seems like an array is being handed back to the dataframe/column by the select function when using dask, but not when using pandas? But I don't want to switch the whole thing back to pandas and lose the 10x performance benefit.

This answer is the result of some help of some others on Stack Overflow, however I think that question has deviated far enough from the initial question that this is altogether different. Code below.

PANDAS: Works
Time Taken excluding AndHeathSolRadFact: 40 seconds

import pandas as pd
import numpy as np

from timeit import default_timer as timer
start = timer()
df = pd.read_csv(r'C:\Users\i5-Desktop\Downloads\Weathergrids.csv')
df['DateTime'] = pd.to_datetime(df['Date'], format='%Y-%d-%m %H:%M')
df['Month'] = df['DateTime'].dt.month
df['Grass_FMC'] = (97.7+4.06*df['RH'])/(df['Temperature']+6)-0.00854*df['RH']+3000/df['Curing']-30

df["AndHeathSolRadFact"] = np.select(
    [
    (df['Month'].between(8,12)),
    (df['Month'].between(1,2) & df['CloudCover']>30)
    ],  #list of conditions
    [1, 1],     #list of results
    default=0)    #default if no match

print(df.head())
#print(ddf.tail())
end = timer()
print(end - start)

DASK: BROKEN
Time Taken excluding AndHeathSolRadFact: 4 seconds

import dask.dataframe as dd
import dask.multiprocessing
import dask.threaded
import pandas as pd
import numpy as np

# Dataframes implement the Pandas API
import dask.dataframe as dd

from timeit import default_timer as timer
start = timer()
ddf = dd.read_csv(r'C:\Users\i5-Desktop\Downloads\Weathergrids.csv')
ddf['DateTime'] = dd.to_datetime(ddf['Date'], format='%Y-%d-%m %H:%M')
ddf['Month'] = ddf['DateTime'].dt.month
ddf['Grass_FMC'] = (97.7+4.06*ddf['RH'])/(ddf['Temperature']+6)-0.00854*ddf['RH']+3000/ddf['Curing']-30

ddf["AndHeathSolRadFact"] = np.select(
    [
    (ddf['Month'].between(8,12)),
    (ddf['Month'].between(1,2) & ddf['CloudCover']>30)
    ],  #list of conditions
    [1, 1],     #list of results
    default=0)    #default if no match

print(ddf.head())
#print(ddf.tail())
end = timer()
print(end - start)

Error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-86c08f38bce6> in <module>
     29     ],  #list of conditions
     30     [1, 1],     #list of results
---> 31     default=0)    #default if no match
     32
     33

~\Anaconda3\lib\site-packages\dask\dataframe\core.py in __setitem__(self, key, value)
   3276             df = self.assign(**{k: value for k in key})
   3277         else:
-> 3278             df = self.assign(**{key: value})
   3279
   3280         self.dask = df.dask

~\Anaconda3\lib\site-packages\dask\dataframe\core.py in assign(self, **kwargs)
   3510                 raise TypeError(
   3511                     "Column assignment doesn't support type "
-> 3512                     "{0}".format(typename(type(v)))
   3513                 )
   3514             if callable(v):

TypeError: Column assignment doesn't support type numpy.ndarray

Sample Weathegrids CSV

Location,Date,Temperature,RH,WindDir,WindSpeed,DroughtFactor,Curing,CloudCover
1075,2019-20-09 04:00,6.8,99.3,143.9,5.6,10.0,93.0,1.0
1075,2019-20-09 05:00,6.4,100.0,93.6,7.2,10.0,93.0,1.0
1075,2019-20-09 06:00,6.7,99.3,130.3,6.9,10.0,93.0,1.0
1075,2019-20-09 07:00,8.6,95.4,68.5,6.3,10.0,93.0,1.0
1075,2019-20-09 08:00,12.2,76.0,86.4,6.1,10.0,93.0,1.0


来源: stackexchange

问:
Mongoose populate not working upto 3 levels
I am trying to populate a fields that is nested inside my model but it is not populating.

This is a field inside my model.

```<code>pendingChanges: {
credentials: {
  university: {
    name: { type: String },
    major: { type: String },
    majorGpa: { type: Number },
  },
  school: {
    name: { type: String },
    degreeType: { type: String },
    degree: { type: String },
  },
  subjects: [{ type: mongoose.Schema.Types.ObjectId, ref: 'subject' }],
  workExperience: {
    type: { type: String },
    from: { type: Date },
    to: { type: Date },
  },
 },
},
</code>```

I am trying to populate subjects key nested inside.

This is what I have done so far.

```<code>const teacher = (await this.findById(id))
    .populate({
      path: 'pendingChanges',
      populate: {
        path: 'credentials',
        populate: {
          path: 'subjects',
        },
      },
    });
</code>```

答:
I found the solution. Here's what I did to make it work.</p>

```<code>const data = await this.findOne(query)
    .populate({
      path: 'pendingChanges.credentials.subjects',
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to populate a fields that is nested inside my model but it is not populating.

This is a field inside my model.

pendingChanges: {
credentials: {
  university: {
    name: { type: String },
    major: { type: String },
    majorGpa: { type: Number },
  },
  school: {
    name: { type: String },
    degreeType: { type: String },
    degree: { type: String },
  },
  subjects: [{ type: mongoose.Schema.Types.ObjectId, ref: 'subject' }],
  workExperience: {
    type: { type: String },
    from: { type: Date },
    to: { type: Date },
  },
 },
},

I am trying to populate subjects key nested inside.

This is what I have done so far.

const teacher = (await this.findById(id))
    .populate({
      path: 'pendingChanges',
      populate: {
        path: 'credentials',
        populate: {
          path: 'subjects',
        },
      },
    });

Body:
I found the solution. Here's what I did to make it work.

const data = await this.findOne(query)
    .populate({
      path: 'pendingChanges.credentials.subjects',
    });


问:
C How to capture closing a Terminal
Any idea on how to capture closing the terminal window that my program is running in?
While I'm at it, any way to capture when the computer is shutting down but the program is still running, or if the user logs off?</p>

答:
You could try the atexit() function ? (see comments)

Or look at this post here: Signals received by bash when terminal is closed

ContentLicense: CC BY-SA 3.0

Title: C How to capture closing a Terminal


问:
Autosys Dependent jobs of ON ICE running immediately after box start
Lets say I have a box with 4 jobs. There is some issue with job2, so I want to skip it and go to Job3 after Job1 is completed. Till I fix and test the issue for Job2.

I thought ON ICE job2 will work. But when I do it, as soon as box_a is RU, job1 and job3 are starting same time. But I want job3 to run only after Job1 is SU. What has to be done ?

For now, Im holding the job2 everyday, and next day Im marking it to SU, when job1 is SU and holding again. But for this i have to monitor everyday.

box_a
job1
job2
job3
job4

答:
A would suggest to remove the Job2 from the box assuming its testing is not dependent on the other jobs in the box and update the condition of Job3.

Save a copy of Job2 and Job3 JIL's.

Update Job2 JIL:

```<code>update_job: Job2
box_name:
</code>```

this would remove the job from the box and keep it as in independent job

Next update Job3 JIL:

```<code>update_job: Job3
condition: success(Job1)
</code>```

Job3 would run after the completion of Job1.

After, the Job2 issue is resolved, update back the Job2 and Job3 JIL with the backup to revert back the temporary changes.

Hope this helps, if any queries do ask.

Body:
A would suggest to remove the Job2 from the box assuming its testing is not dependent on the other jobs in the box and update the condition of Job3.

Save a copy of Job2 and Job3 JIL's.

Update Job2 JIL:

update_job: Job2
box_name:

this would remove the job from the box and keep it as in independent job

Next update Job3 JIL:

update_job: Job3
condition: success(Job1)

Job3 would run after the completion of Job1.

After, the Job2 issue is resolved, update back the Job2 and Job3 JIL with the backup to revert back the temporary changes.

Hope this helps, if any queries do ask.


问:
scroll down to document height but + 100
I got this script

```<code>$("body, html").animate({scrollTop: $(document).height()}, 1000)
</code>```

As seen above it will make so the the page is scrolled down to the documents height: aka the bottom.
However in my case its too far down, I would like to scroll down to bottom:100px; or bottom:10%;
Is this possible? I found examples but they didn't work for me.
What am I missing to make it work?:)

答:
Sure, you can set the value of scrollTop to any value you can mathematically calculate:

```<code>// Top is 100 px short of bottom
$("body, html").animate({scrollTop: $(document).height() - 100}, 1000)
</code>```

```<code>// 90% scroll down
$("body, html").animate({scrollTop: $(document).height() * 0.9}, 1000)
</code>```

Note that for all these, 100px is very small. Your browser window would have to be <100px tall for it to NOT scroll all the way to the bottom.

You can use the visible height of the browser window in your equation too:

```<code>$(window).height()
</code>```

Body:
I got this script

$("body, html").animate({scrollTop: $(document).height()}, 1000)

As seen above it will make so the the page is scrolled down to the documents height: aka the bottom.
However in my case its too far down, I would like to scroll down to bottom:100px; or bottom:10%;
Is this possible? I found examples but they didn't work for me.
What am I missing to make it work?:)

Body:
Sure, you can set the value of scrollTop to any value you can mathematically calculate:

// Top is 100 px short of bottom
$("body, html").animate({scrollTop: $(document).height() - 100}, 1000)

// 90% scroll down
$("body, html").animate({scrollTop: $(document).height() * 0.9}, 1000)

Note that for all these, 100px is very small. Your browser window would have to be <100px tall for it to NOT scroll all the way to the bottom.

You can use the visible height of the browser window in your equation too:

$(window).height()


问:
Why does the recommended dispose pattern adds a disposed field at each level of the hierarchy?
The Dispose pattern is notoriously complicated to get right, especially when we have a hierarchy of classes that needs to dispose things at different levels. The recommended implementation is as follow, took from Implement a Dispose method - Microsoft Docs.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass() => Dispose(false);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        _disposed = true;
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // To detect redundant calls
    private bool _disposed = false;

    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        _disposed = true;

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
```

<p>What I don't get in this implementation is what advantage we have in adding a <code>_disposed</code> field at each level of the hierarchy? Instead, we could take care of the <code>_disposed</code> only in the top level of the hierarchy (the one implementing directly <code>IDisposable</code> and not care about it in the derived classes.</p>

<p>Something like this:</p>

<pre class="lang-cs prettyprint-override"><code>using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass()
    {
       if (_disposed)
       {
          return;
       }

       Dispose(false);
       _disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        _disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
</code>```

This is such a widely used code sample that there must certainly be a good reason for it to be implemented with the repeated _disposed at each level, but I just can't find any.

It's a tiny bit more code in the base class, but less to worry about in the derived class, and some repeated information removed.

What else am I missing?

Edit:

As @InBetween correctly says that one drawback of my implementation is that if you'd need to check if your object is disposed in one method of the derived class you won't be able to check it. Let's correct that issue by making it a protected property with a private set.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    protected bool Disposed { get; private set; } = false;

    ~BaseClass()
    {
       if (Disposed)
       {
          return;
       }

       Dispose(false);
       Disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (Disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        Disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    public void DoSomething()
    {
       if(Disposed)
       {
           throw new ObjectDisposedException("Cannot access disposed resource");
       }
    }

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
```

答:
The reason is simple. In your implementation you cant use _disposed in the derived type to check if any method is invoked when the object is already disposed and take the necessary actions. In your implementation you'd need to create your own redundant flag isDisposed which defeats the purpose; you already have one "for free" from the pattern itself following the guidelines.

A case could be made though about making _disposed protected.

Body:
The Dispose pattern is notoriously complicated to get right, especially when we have a hierarchy of classes that needs to dispose things at different levels. The recommended implementation is as follow, took from Implement a Dispose method - Microsoft Docs.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass() => Dispose(false);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        _disposed = true;
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // To detect redundant calls
    private bool _disposed = false;

    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        _disposed = true;

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

What I don't get in this implementation is what advantage we have in adding a _disposed field at each level of the hierarchy? Instead, we could take care of the _disposed only in the top level of the hierarchy (the one implementing directly IDisposable and not care about it in the derived classes.

Something like this:

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass()
    {
       if (_disposed)
       {
          return;
       }

       Dispose(false);
       _disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        _disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

This is such a widely used code sample that there must certainly be a good reason for it to be implemented with the repeated _disposed at each level, but I just can't find any.

It's a tiny bit more code in the base class, but less to worry about in the derived class, and some repeated information removed.

What else am I missing?

Edit:

As @InBetween correctly says that one drawback of my implementation is that if you'd need to check if your object is disposed in one method of the derived class you won't be able to check it. Let's correct that issue by making it a protected property with a private set.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    protected bool Disposed { get; private set; } = false;

    ~BaseClass()
    {
       if (Disposed)
       {
          return;
       }

       Dispose(false);
       Disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (Disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        Disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    public void DoSomething()
    {
       if(Disposed)
       {
           throw new ObjectDisposedException("Cannot access disposed resource");
       }
    }

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}


问:
How to detect straight lines in absolutely grayscale image, but not throught binary image?
Rencently I'm trying to search for some ways to detect lines in CT scans.I found that all the Hough Transform family and some other algorithms are required to deal with contours born after edge detector.I found the contours are not what I want and a lot of short lines created by these 2 steps.I get perplexed by this.Can any handsome tell me what to do with this？Some methods or algorithms used in grayscale-image straightly but not in binary-image? using opencv or numpy is perfect! Many thanks!
Below is the test picture.I'm working to detect left-top straight lines and filter out the others.

答:
You have pretty consistent background so I would:

detect contours

as any pixel with not background color that is neighboring background color.

Segmentate/label the contour points to form ordered "polylines"

create ID buffer and set ID=0 (background or object pixels)

find any yet not processed contour pixel
if none found stop

flood fill the contour in ID buffer by ID

increment ID

go to 2

now ID buffer contains your labeled contours

for each contour create ordered list of pixels forming contour "polyline"

to  speed this up you can remember each contour start point from #2 or even do this step directly in step #2.

detect straight lines in contour "polylines".

that is simple straight lines have similar slope angle between neighboring point. You can also apply regression or whatever ... the slope or unit direction vectors must be computed on pixels that are at least  5 pixels distant to each other otherwise rasterization pixelation will corrupt the results.

see some related stuff:

Efficiently calculating a segmented regression on a large dataset

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line


问:
creating django model for review gives this msg
When i try to create the reviews table, i get the the following error message. The models.py and error message in the terminal is mentioned below.

models.py

```<code>class reviews(models.Model):
    reviewee = models.ForeignKey('Person', on_delete=models.CASCADE)
    reviewer = models.ForeignKey('Person', on_delete=models.CASCADE)
    review = models.TextField()
    rating = models.FloatField()

class Person(models.Model):
    email = models.CharField(max_length=30)
    pwd = models.CharField(max_length=30)
    type = models.CharField(max_length=30)
</code>```

terminal output

```<code>SystemCheckError: System check identified some issues:

ERRORS:
pfapp.reviews.reviewee: (fields.E304) Reverse accessor for 'reviews.reviewee' clashes with reverse accessor for 'reviews.reviewer'.
        HINT: Add or change a related_name argument to the definition for 'reviews.reviewee' or 'reviews.reviewer'.
pfapp.reviews.reviewer: (fields.E304) Reverse accessor for 'reviews.reviewer' clashes with reverse accessor for 'reviews.reviewee'.
        HINT: Add or change a related_name argument to the definition for 'reviews.reviewer' or 'reviews.reviewee'.

System check identified 2 issues (0 silenced).
</code>```

The logic behind my models is that on person can review another person. Also, when either reviewer or reviewee is deleted from the table, the review should also be deleted.

i hope you got my idea.

答:
You can do and then migrate:

```<code>reviewee = models.ForeignKey('Person', on_delete=models.CASCADE)
reviewer = models.ForeignKey('Person', on_delete=models.CASCADE, related_name="reviewer", null=True)
</code>```

Now, on reverse you can get reviewee from person.reviews which is by default. And, get reviewer from person.reviewer. Have a look at this SO question for greater understanding.

Body:
When i try to create the reviews table, i get the the following error message. The models.py and error message in the terminal is mentioned below.

models.py

class reviews(models.Model):
    reviewee = models.ForeignKey('Person', on_delete=models.CASCADE)
    reviewer = models.ForeignKey('Person', on_delete=models.CASCADE)
    review = models.TextField()
    rating = models.FloatField()

class Person(models.Model):
    email = models.CharField(max_length=30)
    pwd = models.CharField(max_length=30)
    type = models.CharField(max_length=30)

terminal output

SystemCheckError: System check identified some issues:

ERRORS:
pfapp.reviews.reviewee: (fields.E304) Reverse accessor for 'reviews.reviewee' clashes with reverse accessor for 'reviews.reviewer'.
        HINT: Add or change a related_name argument to the definition for 'reviews.reviewee' or 'reviews.reviewer'.
pfapp.reviews.reviewer: (fields.E304) Reverse accessor for 'reviews.reviewer' clashes with reverse accessor for 'reviews.reviewee'.
        HINT: Add or change a related_name argument to the definition for 'reviews.reviewer' or 'reviews.reviewee'.

System check identified 2 issues (0 silenced).

The logic behind my models is that on person can review another person. Also, when either reviewer or reviewee is deleted from the table, the review should also be deleted.

i hope you got my idea.

Body:
You can do and then migrate:

reviewee = models.ForeignKey('Person', on_delete=models.CASCADE)
reviewer = models.ForeignKey('Person', on_delete=models.CASCADE, related_name="reviewer", null=True)

Now, on reverse you can get reviewee from person.reviews which is by default. And, get reviewer from person.reviewer. Have a look at this SO question for greater understanding.


问:
How to enable Aura for this class
```<code> public List<SelectOption> getYearList(){

    Integer year =  Date.Today().year();
    String s1=string.valueof(year).right(2);
    Integer Year1= Integer.valueof(s1);
    List<SelectOption> YearListOptions = new List<SelectOption>();
    YearListOptions .add(new SelectOption('','YY'));
    for(Integer i=Year1;i<=Year1+8;i++)
    {
       string j=string.valueof(i);

        YearListOptions .add(new SelectOption(j,j));

    }
    return YearListOptions ;
}
</code>```

I tried but Getting error like AuraEnabled methods do not support return type of List

答:
I have Changed this but anyone have any suggestion or comments please feel free to add</p>

```<code>@AuraEnabled
public List<String> getYearList(){
    Integer year =  Date.Today().year();
    String s1=string.valueof(year).right(2);
    Integer Year1= Integer.valueof(s1);
    List<SelectOption> YearListOptions = new List<SelectOption>();
    List<String> yearValueList = new List<String>();
    YearListOptions .add(new SelectOption('','YY'));
    for(Integer i=Year1;i<=Year1+8;i++)
    {
        string j=string.valueof(i);
        YearListOptions .add(new SelectOption(j,j));
    }
    for (SelectOption sO : YearListOptions){
        yearValueList.add(sO.getValue());
    }
    return yearValueList ;
}
</code>```

Title: How to enable Aura for this class

Body:
 public List<SelectOption> getYearList(){

    Integer year =  Date.Today().year();
    String s1=string.valueof(year).right(2);
    Integer Year1= Integer.valueof(s1);
    List<SelectOption> YearListOptions = new List<SelectOption>();
    YearListOptions .add(new SelectOption('','YY'));
    for(Integer i=Year1;i<=Year1+8;i++)
    {
       string j=string.valueof(i);

        YearListOptions .add(new SelectOption(j,j));

    }
    return YearListOptions ;
}

I tried but Getting error like AuraEnabled methods do not support return type of List

Body:
I have Changed this but anyone have any suggestion or comments please feel free to add

@AuraEnabled
public List<String> getYearList(){
    Integer year =  Date.Today().year();
    String s1=string.valueof(year).right(2);
    Integer Year1= Integer.valueof(s1);
    List<SelectOption> YearListOptions = new List<SelectOption>();
    List<String> yearValueList = new List<String>();
    YearListOptions .add(new SelectOption('','YY'));
    for(Integer i=Year1;i<=Year1+8;i++)
    {
        string j=string.valueof(i);
        YearListOptions .add(new SelectOption(j,j));
    }
    for (SelectOption sO : YearListOptions){
        yearValueList.add(sO.getValue());
    }
    return yearValueList ;
}


问:
How to check if consecutive digits in a number are even or odd?
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

```<code>def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))
</code>```

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

```<code>>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
</code>```

答:
mine solution is very simple. just change a bit your code and avoiding using indexes just looping through all digits in cifre and handling boolean flags:

```<code>def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    even = True
    odd = True
    output = "The number complies to the needed terms"

    for broj in cifre:
        if broj % 2 == 0 and odd:
            even = True
            odd = False
        elif broj % 2 != 0 and even:
            odd = True
            even = False
        else:
            return "The number doesn't comply to the needed terms."
    return output
n = int(input("Unesite broj n: "))
print(par_nepar(n))
</code>```

outputs:

```<code>Unesite broj n: 33890
The number doesn't comply to the needed terms.

Unesite broj n: 4963850
The number complies to the needed terms
</code>```

Body:
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False

Body:
mine solution is very simple. just change a bit your code and avoiding using indexes just looping through all digits in cifre and handling boolean flags:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    even = True
    odd = True
    output = "The number complies to the needed terms"

    for broj in cifre:
        if broj % 2 == 0 and odd:
            even = True
            odd = False
        elif broj % 2 != 0 and even:
            odd = True
            even = False
        else:
            return "The number doesn't comply to the needed terms."
    return output
n = int(input("Unesite broj n: "))
print(par_nepar(n))

outputs:

Unesite broj n: 33890
The number doesn't comply to the needed terms.

Unesite broj n: 4963850
The number complies to the needed terms


问:
Batch File Won't Jump to Label
I have an unfinished batch file that wont jump to the :TBS label. It will always go to the :BSO label no matter what you put in for the first question. "A" should go to :BSO and "B" should go to :TBS. I don't know how to fix this. I have tried everything I can think of. Any help appreciated.</p>
```<code>@echo off
echo ------------------------------------------Computer Optimization and Fixer 1.1-------------------------------------------
echo.
echo Welcome to Computer Optimization and Fixer 1.1 by Anston
echo.
echo Computer Optimization and Fixer 1.1 will do a basic optimization and fix issues on your computer. For example...
echo It can run sfc, chkdsk, Defrag or Optimize, Disk Cleanup, DISM, troubleshooters, and more.
echo.
set /p A="Would you like to do a basic optimization(A) or fix a certain issue(B)?"
IF %A% EQU A GOTO:BSO
IF %A% EQU B GOTO:TBS
:BSO
echo.
echo Running basic optimization...
pause
start "dfrgui.exe" /wait "C:\Windows\System32\dfrgui.exe"
sfc /scannow
chkdsk /r
start diskclean
GOTO:END
:TBS
echo.
set /p ch="What problem do you have?(Power[A], Internet[B], Performance[C], Files[D], Windows Apps[E], Windows Update[F], Devices[G], Audio[H], Search[I], or Printer[J])
IF %ch% EQU A GOTO:PWR
IF %ch% EQU B GOTO:INT
IF %ch% EQU C GOTO:PRF
IF %ch% EQU D GOTO:FLS
IF %ch% EQU E GOTO:WNA
IF %ch% EQU F GOTO:WNU
IF %ch% EQU G GOTO:DEV
IF %ch% EQU H GOTO:AUD
IF %ch% EQU I GOTO:SCH
IF %ch% EQU J GOTO:PRN
:PWR
echo.
echo Running Troubleshooter...
msdt.exe /id PowerDiagnostic
pause
GOTO:END
:END
cls
echo ------------------------------------------Computer Optimization and Fixer 1.1-------------------------------------------
echo.
echo Thank you for using Computer Optimization and Fixer 1.1
pause
</code>```

答:
There is a command available since Windows Vista and on Windows Server versions since Windows Server 2003 for choice menus: CHOICE

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ToolVersion=1.1"
cls
echo --------------------- Computer Optimization and Fixer %ToolVersion% ---------------------
echo/
echo Welcome to Computer Optimization and Fixer %ToolVersion% by Anston
echo/
echo Computer Optimization and Fixer %ToolVersion% will do a basic optimization
echo and fix issues on your computer. For example, it can run Check Disk
echo Utility, Disk Space Cleanup Manager for Windows, Disk System Integrity
echo Check and Repair, Disk Defragmenter, troubleshooters, and more.
echo/
echo What do you want to do?
echo/
echo    A ... do a basic optimization
echo    B ... fix a certain issue
echo    E ... do nothing and exit
echo/
%SystemRoot%\System32\choice.exe /C ABE /N /M "Your choice:"
if errorlevel 3 goto :EOF
if errorlevel 2 goto TBS

echo/
echo Running basic optimization...
%SystemRoot%\System32\chkdsk.exe /r
%SystemRoot%\System32\cleanmgr.exe
%SystemRoot%\System32\sfc.exe /scannow
%SystemRoot%\System32\dfrgui.exe
goto END

:TBS
echo/
echo What problem do you have?
echo/
echo    A ... Power
echo    B ... Internet
echo    C ... Performance
echo    D ... Files
echo    E ... Windows Apps
echo    F ... Windows Update
echo    G ... Devices
echo    H ... Audio
echo    I ... Search
echo    J ... Printer
echo    N ... None of above
echo/
%SystemRoot%\System32\choice.exe /C ABCDEFGHIJN /N /M "Your choice:"
echo/
goto Option%Errorlevel%

:Option1
echo Running diagnostics troubleshooting wizard ...
%SystemRoot%\System32\msdt.exe /id PowerDiagnostic
goto FINISH

:Option2
echo Check for Internet problems ...
goto FINISH

:Option3
echo Check for performance problems ...
goto FINISH

:Option4
echo Check for file problems ...
goto FINISH

:Option5
echo Check for problem with Windows Apps ...
goto FINISH

:Option6
echo Check for Windows update problems ...
goto FINISH

:Option7
echo Check for device problems ...
goto FINISH

:Option8
echo Check for audio problems ...
goto FINISH

:Option9
echo Check for search problems ...
goto FINISH

:Option10
echo Check for printer problems ...
goto FINISH

:Option11
echo Sorry, this tool cannot help you.

:FINISH
echo/
pause

:END
cls
echo --------------------- Computer Optimization and Fixer %ToolVersion% ---------------------
echo/
echo Thank you for using Computer Optimization and Fixer %ToolVersion%
echo/
endlocal
pause
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

chkdsk /?

choice /?

cleanmgr /?

cls /?

defrag /? ... console version of dfrgui.exe

dism /?

echo /?

endlocal /?

goto /?

if /?

pause /?

set /?

setlocal /?

sfc /?

Please read also:

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Where does GOTO :EOF return to?

Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files

Why is no string output with 'echo %var%' after using 'set var = text' on command line?

How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?

DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/

Note: The execution of disk defragmenter is not necessary on SSD hard disks. So the batch file should check of which type each local drive is before running disk defragmenter on a drive.

PS: The names of the executables used for basic optimizations can be read by clicking with secondary (usually right) mouse button on an executable like sfc.exe, clicking in opened context menu with primary (usually left) mouse button on last menu item Properties, selecting the tab Details and looking on item File description.

Title: Batch File Won't Jump to Label

Body:
I have an unfinished batch file that wont jump to the :TBS label. It will always go to the :BSO label no matter what you put in for the first question. "A" should go to :BSO and "B" should go to :TBS. I don't know how to fix this. I have tried everything I can think of. Any help appreciated.

@echo off
echo ------------------------------------------Computer Optimization and Fixer 1.1-------------------------------------------
echo.
echo Welcome to Computer Optimization and Fixer 1.1 by Anston
echo.
echo Computer Optimization and Fixer 1.1 will do a basic optimization and fix issues on your computer. For example...
echo It can run sfc, chkdsk, Defrag or Optimize, Disk Cleanup, DISM, troubleshooters, and more.
echo.
set /p A="Would you like to do a basic optimization(A) or fix a certain issue(B)?"
IF %A% EQU A GOTO:BSO
IF %A% EQU B GOTO:TBS
:BSO
echo.
echo Running basic optimization...
pause
start "dfrgui.exe" /wait "C:\Windows\System32\dfrgui.exe"
sfc /scannow
chkdsk /r
start diskclean
GOTO:END
:TBS
echo.
set /p ch="What problem do you have?(Power[A], Internet[B], Performance[C], Files[D], Windows Apps[E], Windows Update[F], Devices[G], Audio[H], Search[I], or Printer[J])
IF %ch% EQU A GOTO:PWR
IF %ch% EQU B GOTO:INT
IF %ch% EQU C GOTO:PRF
IF %ch% EQU D GOTO:FLS
IF %ch% EQU E GOTO:WNA
IF %ch% EQU F GOTO:WNU
IF %ch% EQU G GOTO:DEV
IF %ch% EQU H GOTO:AUD
IF %ch% EQU I GOTO:SCH
IF %ch% EQU J GOTO:PRN
:PWR
echo.
echo Running Troubleshooter...
msdt.exe /id PowerDiagnostic
pause
GOTO:END
:END
cls
echo ------------------------------------------Computer Optimization and Fixer 1.1-------------------------------------------
echo.
echo Thank you for using Computer Optimization and Fixer 1.1
pause

Body:
There is a command available since Windows Vista and on Windows Server versions since Windows Server 2003 for choice menus: CHOICE

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ToolVersion=1.1"
cls
echo --------------------- Computer Optimization and Fixer %ToolVersion% ---------------------
echo/
echo Welcome to Computer Optimization and Fixer %ToolVersion% by Anston
echo/
echo Computer Optimization and Fixer %ToolVersion% will do a basic optimization
echo and fix issues on your computer. For example, it can run Check Disk
echo Utility, Disk Space Cleanup Manager for Windows, Disk System Integrity
echo Check and Repair, Disk Defragmenter, troubleshooters, and more.
echo/
echo What do you want to do?
echo/
echo    A ... do a basic optimization
echo    B ... fix a certain issue
echo    E ... do nothing and exit
echo/
%SystemRoot%\System32\choice.exe /C ABE /N /M "Your choice:"
if errorlevel 3 goto :EOF
if errorlevel 2 goto TBS

echo/
echo Running basic optimization...
%SystemRoot%\System32\chkdsk.exe /r
%SystemRoot%\System32\cleanmgr.exe
%SystemRoot%\System32\sfc.exe /scannow
%SystemRoot%\System32\dfrgui.exe
goto END

:TBS
echo/
echo What problem do you have?
echo/
echo    A ... Power
echo    B ... Internet
echo    C ... Performance
echo    D ... Files
echo    E ... Windows Apps
echo    F ... Windows Update
echo    G ... Devices
echo    H ... Audio
echo    I ... Search
echo    J ... Printer
echo    N ... None of above
echo/
%SystemRoot%\System32\choice.exe /C ABCDEFGHIJN /N /M "Your choice:"
echo/
goto Option%Errorlevel%

:Option1
echo Running diagnostics troubleshooting wizard ...
%SystemRoot%\System32\msdt.exe /id PowerDiagnostic
goto FINISH

:Option2
echo Check for Internet problems ...
goto FINISH

:Option3
echo Check for performance problems ...
goto FINISH

:Option4
echo Check for file problems ...
goto FINISH

:Option5
echo Check for problem with Windows Apps ...
goto FINISH

:Option6
echo Check for Windows update problems ...
goto FINISH

:Option7
echo Check for device problems ...
goto FINISH

:Option8
echo Check for audio problems ...
goto FINISH

:Option9
echo Check for search problems ...
goto FINISH

:Option10
echo Check for printer problems ...
goto FINISH

:Option11
echo Sorry, this tool cannot help you.

:FINISH
echo/
pause

:END
cls
echo --------------------- Computer Optimization and Fixer %ToolVersion% ---------------------
echo/
echo Thank you for using Computer Optimization and Fixer %ToolVersion%
echo/
endlocal
pause

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

chkdsk /?

choice /?

cleanmgr /?

cls /?

defrag /? ... console version of dfrgui.exe

dism /?

echo /?

endlocal /?

goto /?

if /?

pause /?

set /?

setlocal /?

sfc /?

Please read also:

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Where does GOTO :EOF return to?

Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files

Why is no string output with 'echo %var%' after using 'set var = text' on command line?

How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?

DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/

Note: The execution of disk defragmenter is not necessary on SSD hard disks. So the batch file should check of which type each local drive is before running disk defragmenter on a drive.

PS: The names of the executables used for basic optimizations can be read by clicking with secondary (usually right) mouse button on an executable like sfc.exe, clicking in opened context menu with primary (usually left) mouse button on last menu item Properties, selecting the tab Details and looking on item File description.


问:
NiFi : Create file name using the field values from the csv flowfile
I have a csv flowfile with single record. I need to create its file name based on couple of column values in the csv file. Can you please let me know how we can do it by using the column name only not the position of the column as column position may change. Example

CSV File

Name , City, State, Country, Gender

John, Dallas, Texas, USA, M

File name should be John_USA.csv

I am trying extract text processor and pulling the first data row using -
row = ^.\r?\n(.)

And then updateattribute processor I am pulling the values from the columns using below expression

${row:getDelimitedField(1)}_${row:getDelimitedField(4)}.csv

But this use the position of the column not the column name. How can I build it using the column name not the position of columns

答:
The way I will do it (maybe be not the efficient one):

Convert the CSV to json

Pass content to attributes (so you can access the field you want like dictionnary (key-value))

Update Attributes

Convert it back to CSV (thus you can control the schema, and the position of the fields).


问:
Have anyone tried Microsoft Graph API to read One drive image EXIF Data like location
I am trying to read a exif data of an Image particularly Location from One Drive using Microsoft graph api. Did any one tried to read location (longitude and latitude)?</p>

答:
I checked some documents and learned that this feature seems to be disabled in 2019,but I learned from here that there is a third-party tool that can achieve this function here.

Hope it helps you!


问:
iPad Orientation issues when switching between two views and from portrait to landscape vice versa
I am building a simple app with two View Controllers, I am testing the code using the iPhone Simulator, everything seem to be working fine. The problem happens when I rotate from Portrait to Landscape or from Landscape to portrait. This is the logic of the app, the app always launched in Portrait, I have a button to on the first View to Switch from View1 to View2. On View2 I have another button to switch from View2 back to View1. Let say, I am in Portrait mode, I switch from View1 to View2, then rotate the iPad (in the simulator) from Portrait to Landscape, when I switch back from View2, i.e to go back to View1. View1 screen/view is displayed in Portrait with View2 screen displayed in the background, ie part of View2 is displayed in the background, I guess because View1 was originally in Portrait mode.

The question is.. Has anyone had this issue before, if so, any code to fix this issue, secondly, how can I identify in the code which orientation the device is and which orientation the view is in.

This method is to switch to View 2:

```<code>-(IBAction) switchToView2: (id) sender {

SecondViewController *myViewController = [[SecondViewController alloc]        initWithNibName:@"SecondViewController" bundle:nil];

[self.view addSubview: myViewController.view];
[UIView commitAnimations];
}
</code>```

This method is to switch back to View1:

```<code>-(IBAction) switchBackToView1:(id) sender {

[self.view removeFromSuperview];
[UIView commitAnimations];

}
</code>```

答:
From your code:

```<code>[self.view addSubview: myViewController.view];
</code>```

It makes me believe that your 2 views is a subview of myViewController.view. which explains why they're both showing at the same time. it would make sense to have seperate view controllers for different views.

ContentLicense: CC BY-SA 2.5

Body:
I am building a simple app with two View Controllers, I am testing the code using the iPhone Simulator, everything seem to be working fine. The problem happens when I rotate from Portrait to Landscape or from Landscape to portrait. This is the logic of the app, the app always launched in Portrait, I have a button to on the first View to Switch from View1 to View2. On View2 I have another button to switch from View2 back to View1. Let say, I am in Portrait mode, I switch from View1 to View2, then rotate the iPad (in the simulator) from Portrait to Landscape, when I switch back from View2, i.e to go back to View1. View1 screen/view is displayed in Portrait with View2 screen displayed in the background, ie part of View2 is displayed in the background, I guess because View1 was originally in Portrait mode.

The question is.. Has anyone had this issue before, if so, any code to fix this issue, secondly, how can I identify in the code which orientation the device is and which orientation the view is in.

This method is to switch to View 2:

-(IBAction) switchToView2: (id) sender {

SecondViewController *myViewController = [[SecondViewController alloc]        initWithNibName:@"SecondViewController" bundle:nil];

[self.view addSubview: myViewController.view];
[UIView commitAnimations];
}

This method is to switch back to View1:

-(IBAction) switchBackToView1:(id) sender {

[self.view removeFromSuperview];
[UIView commitAnimations];

}

Body:
From your code:

[self.view addSubview: myViewController.view];

It makes me believe that your 2 views is a subview of myViewController.view. which explains why they're both showing at the same time. it would make sense to have seperate view controllers for different views.


问:
How to delete the line which matches the string shared in array
I have a file which consist of text like below

```<code>compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX
</code>```

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

```<code>#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done
</code>```

答:
If your sed supports the \| (or) operator in regex, would you please try:

```<code>array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
pat="$(IFS='|'; echo "${array[*]}" | sed -e 's/|/\\|/g' -e 's/\./\\./g')"
sed "/\($pat\)\$/d" copyright
</code>```

It concatenates the array elements and generates a pattern string which looks like: \.a\|\.so\|\.bin\.ihex\|....

Then the line sed "/\($pat\)\$/d" text deletes the lines which match the pattern.

Please note that your array elements and your text "line which is having file extension .so , .dill ,.pg and .HEX" may disagree. I have used your array as is.

Body:
I have a file which consist of text like below

compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done

Body:
If your sed supports the \| (or) operator in regex, would you please try:

array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
pat="$(IFS='|'; echo "${array[*]}" | sed -e 's/|/\\|/g' -e 's/\./\\./g')"
sed "/\($pat\)\$/d" copyright

It concatenates the array elements and generates a pattern string which looks like: \.a\|\.so\|\.bin\.ihex\|....

Then the line sed "/\($pat\)\$/d" text deletes the lines which match the pattern.

Please note that your array elements and your text "line which is having file extension .so , .dill ,.pg and .HEX" may disagree. I have used your array as is.


问:
Pivot array of structs into columns using pyspark - not explode the array
I currently have a dataframe with an id and a column which is an array of structs:

```<code> root
 |-- id: string (nullable = true)
 |-- lists: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: string (nullable = true)
 |    |    |-- _2: string (nullable = true)
</code>```

Here is an example table with data:

```<code> id | list1             | list2
 ------------------------------------------
 1  | [[a, av], [b, bv]]| [[e, ev], [f,fv]]
 2  | [[c, cv]]         | [[g,gv]]
</code>```

How do I transform the above dataframe to the one below? I need to "explode" the array and add columns based on first value in the struct.

```<code> id | a   | b   | c   | d   | e  | f  | g
 ----------------------------------------
 1  | av  | bv  | null| null| ev | fv | null
 2  | null| null| cv  | null|null|null|gv
</code>```

A pyspark code to create the dataframe is as below:

```<code>d1 = spark.createDataFrame([("1", [("a","av"),("b","bv")], [("e", "ev"), ("f", "fv")]), \
                                    ("2", [("c", "cv")],  [("g", "gv")])], ["id","list1","list2"])
</code>```

Note: I have a spark version of 2.2.0 so some sql functions don't work such as concat_map, etc.

答:
UPD - For Spark 2.2.0

You can define similar functions in 2.2.0 using udfs. They will be much less efficient in terms of performance and you'll need a special function for each output value type (i.e. you won't be able to have one element_at function which could output value of any type from any map type), but they will work. The code below works for Spark 2.2.0:

```<code>from pyspark.sql.functions import udf
from pyspark.sql.types import MapType, ArrayType, StringType

@udf(MapType(StringType(), StringType()))
def map_from_entries(l):
    return {x:y for x,y in l}

@udf(MapType(StringType(), StringType()))
def map_concat(m1, m2):
    m1.update(m2)
    return m1

@udf(ArrayType(StringType()))
def map_keys(m):
    return list(m.keys())

def element_getter(k):
    @udf(StringType())
    def element_at(m):
        return m.get(k)
    return element_at

d2 = d1.select('id',
               map_concat(map_from_entries('list1'),
                          map_from_entries('list2')).alias('merged_map'))
map_keys = d2.select(f.explode(map_keys('merged_map')).alias('mk')) \
             .agg(f.collect_set('mk').alias('keys')) \
             .collect()[0].keys
map_keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
selects = [element_getter(k)('merged_map').alias(k) for k in sorted(map_keys)]
d = d2.select('id', *selects)
</code>```

ORIGINAL ANSWER (working for Spark 2.4.0+)

Not clear where d column came from in your example (d never appeared in the initial dataframe). If columns should be created based on the first elements in the array, then this should work (assuming total number of unique first values in the lists is small enough):

```<code>import pyspark.sql.functions as f
d2 = d1.select('id',
               f.map_concat(f.map_from_entries('list1'),
                            f.map_from_entries('list2')).alias('merged_map'))
map_keys = d2.select(f.explode(f.map_keys('merged_map')).alias('mk')) \
             .agg(f.collect_set('mk').alias('keys')) \
             .collect()[0].keys
selects = [f.element_at('merged_map', k).alias(k) for k in sorted(map_keys)]
d = d2.select('id', *selects)
</code>```

Output (no column for d because it never mentioned in the initial DataFrame):

```<code>+---+----+----+----+----+----+----+
| id|   a|   b|   c|   e|   f|   g|
+---+----+----+----+----+----+----+
|  1|  av|  bv|null|  ev|  fv|null|
|  2|null|null|  cv|null|null|  gv|
+---+----+----+----+----+----+----+
</code>```

If you actually had in mind that list of the columns is fixed from the beginning (and they are not taken from the array), then you can just replace the definition of varaible map_keys with the fixed list of columns, e.g. map_keys=['a', 'b', 'c', 'd', 'e', 'f', 'g']. In that case you get the output you mention in the answer:

```<code>+---+----+----+----+----+----+----+----+
| id|   a|   b|   c|   d|   e|   f|   g|
+---+----+----+----+----+----+----+----+
|  1|  av|  bv|null|null|  ev|  fv|null|
|  2|null|null|  cv|null|null|null|  gv|
+---+----+----+----+----+----+----+----+
</code>```

By the way - what you want to do is not what is called explode in Spark. explode in Spark is for the situation when you create multiple rows from one. E.g. if you wanted to get from dataframe like this:

```<code>+---+---------+
| id|      arr|
+---+---------+
|  1|   [a, b]|
|  2|[c, d, e]|
+---+---------+
</code>```

to this:

```<code>+---+-------+
| id|element|
+---+-------+
|  1|      a|
|  1|      b|
|  2|      c|
|  2|      d|
|  2|      e|
+---+-------+
</code>```

Body:
I currently have a dataframe with an id and a column which is an array of structs:

 root
 |-- id: string (nullable = true)
 |-- lists: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: string (nullable = true)
 |    |    |-- _2: string (nullable = true)

Here is an example table with data:

 id | list1             | list2
 ------------------------------------------
 1  | [[a, av], [b, bv]]| [[e, ev], [f,fv]]
 2  | [[c, cv]]         | [[g,gv]]

How do I transform the above dataframe to the one below? I need to "explode" the array and add columns based on first value in the struct.

 id | a   | b   | c   | d   | e  | f  | g
 ----------------------------------------
 1  | av  | bv  | null| null| ev | fv | null
 2  | null| null| cv  | null|null|null|gv

A pyspark code to create the dataframe is as below:

d1 = spark.createDataFrame([("1", [("a","av"),("b","bv")], [("e", "ev"), ("f", "fv")]), \
                                    ("2", [("c", "cv")],  [("g", "gv")])], ["id","list1","list2"])

Note: I have a spark version of 2.2.0 so some sql functions don't work such as concat_map, etc.

Body:
UPD - For Spark 2.2.0

You can define similar functions in 2.2.0 using udfs. They will be much less efficient in terms of performance and you'll need a special function for each output value type (i.e. you won't be able to have one element_at function which could output value of any type from any map type), but they will work. The code below works for Spark 2.2.0:

from pyspark.sql.functions import udf
from pyspark.sql.types import MapType, ArrayType, StringType

@udf(MapType(StringType(), StringType()))
def map_from_entries(l):
    return {x:y for x,y in l}

@udf(MapType(StringType(), StringType()))
def map_concat(m1, m2):
    m1.update(m2)
    return m1

@udf(ArrayType(StringType()))
def map_keys(m):
    return list(m.keys())

def element_getter(k):
    @udf(StringType())
    def element_at(m):
        return m.get(k)
    return element_at

d2 = d1.select('id',
               map_concat(map_from_entries('list1'),
                          map_from_entries('list2')).alias('merged_map'))
map_keys = d2.select(f.explode(map_keys('merged_map')).alias('mk')) \
             .agg(f.collect_set('mk').alias('keys')) \
             .collect()[0].keys
map_keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
selects = [element_getter(k)('merged_map').alias(k) for k in sorted(map_keys)]
d = d2.select('id', *selects)

ORIGINAL ANSWER (working for Spark 2.4.0+)

Not clear where d column came from in your example (d never appeared in the initial dataframe). If columns should be created based on the first elements in the array, then this should work (assuming total number of unique first values in the lists is small enough):

import pyspark.sql.functions as f
d2 = d1.select('id',
               f.map_concat(f.map_from_entries('list1'),
                            f.map_from_entries('list2')).alias('merged_map'))
map_keys = d2.select(f.explode(f.map_keys('merged_map')).alias('mk')) \
             .agg(f.collect_set('mk').alias('keys')) \
             .collect()[0].keys
selects = [f.element_at('merged_map', k).alias(k) for k in sorted(map_keys)]
d = d2.select('id', *selects)

Output (no column for d because it never mentioned in the initial DataFrame):

+---+----+----+----+----+----+----+
| id|   a|   b|   c|   e|   f|   g|
+---+----+----+----+----+----+----+
|  1|  av|  bv|null|  ev|  fv|null|
|  2|null|null|  cv|null|null|  gv|
+---+----+----+----+----+----+----+

If you actually had in mind that list of the columns is fixed from the beginning (and they are not taken from the array), then you can just replace the definition of varaible map_keys with the fixed list of columns, e.g. map_keys=['a', 'b', 'c', 'd', 'e', 'f', 'g']. In that case you get the output you mention in the answer:

+---+----+----+----+----+----+----+----+
| id|   a|   b|   c|   d|   e|   f|   g|
+---+----+----+----+----+----+----+----+
|  1|  av|  bv|null|null|  ev|  fv|null|
|  2|null|null|  cv|null|null|null|  gv|
+---+----+----+----+----+----+----+----+

By the way - what you want to do is not what is called explode in Spark. explode in Spark is for the situation when you create multiple rows from one. E.g. if you wanted to get from dataframe like this:

+---+---------+
| id|      arr|
+---+---------+
|  1|   [a, b]|
|  2|[c, d, e]|
+---+---------+

to this:

+---+-------+
| id|element|
+---+-------+
|  1|      a|
|  1|      b|
|  2|      c|
|  2|      d|
|  2|      e|
+---+-------+


问:
How to keep child's stdout open after parent's termination in linux?
I am trying to run a child process from the parent app in Ubuntu. Both are C programs. The parent uses fork() with subsequent execl(), then waits for ~1 sec and terminates. The idea is to let parent terminate in a regular way, and keep child alive and running in the same console. So, the child begins to print some output with intervals of 300 ms, and I can see it for about the time while parent is alive. Then parent terminates, and further child output can not be seen in the console.

From what I have read to this moment, it seems that since the child shares all the handles, upon parent's exit stdout gets closed for both parent and child. So, I guess the child has to somehow preserve binding to the same console it was bound to upon its start. Please, advice how to achieve this.

答:
You don't have to do anything special if you want the child process to keep running and writing to the terminal, even after the parent has stopped. Try the program below. This BTW is super annoying as the child process will trash you current terminal session.

This works because:

The child process gets a copy of the parents open file descriptors, including stdout. This is AFAIK the same as what dup() does.

To actually close the file, you have to close all associated file descriptors.

See the man pages for fork() and dup() for more information.

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    pid_t pid = fork();
    int wstatus;
    switch (pid)
    {
        case -1:
            fprintf(stderr, "fork() failed\n");
            exit(EXIT_FAILURE);

        case 0:
            while (1)
            {
                printf("child working...\n");
                sleep(1);
            }
            break;

        default:
            printf("Press ENTER to exit parent...\n");
            getchar();
    }

    return EXIT_SUCCESS;
}
```


问:
using shopify api with .net post requests on a private app
has anybody got a . net example  of running a simple post to the shopify create order Ive seen some really old examples but they dont seem to work the ones that do answer have  no code examples im trying the following but just get bad request back, surely this should be simple?</p>

```<code>private static async Task runShopifyAsyncCreateOrderJsonTask()
    {
        using (var handler = new HttpClientHandler { Credentials = GetCredential() })
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

           string json = @"{'order': {'line_items': [{'variant_id': 720123393,'quantity': 1}]}}";

            // HTTP post
            HttpResponseMessage response = await     client.PostAsJsonAsync("admin/orders.json", test);
            if (response.IsSuccessStatusCode)
            {
                Uri uri = response.Headers.Location;
                var results = await response.Content.ReadAsStringAsync();

            }
        }
    }
</code>```

答:
After some playing around I found this works:

```<code>        string ShopPath = "/admin/api/2020-04/";
        string shopifyAddProduct = "products.json";
        string shopifyGetProductFmt = "products.json?title={0}";
        string URL = String.Format("https://{0}.myshopify.com{1}", ShopName, ShopPath);
        var clientHandler = new HttpClientHandler
        {
            Credentials = new NetworkCredential(APIkey/*username*/, APIpass/*Password*/),
            PreAuthenticate = true
        };
        HttpClient client = new HttpClient(clientHandler);
        client.BaseAddress = new Uri(URL);

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // need an access token...
        client.DefaultRequestHeaders.Add("X-Shopify-Access-Token", APIpass);

        var shopify = new
        {
            product = new
            {
                title = "Burton Custom Freestyle 151",
                body_html = "<strong>Good snowboard!</strong>",
                vendor = "Snowboard",
                product_type = "Snowboard",
                published = false
            }
        };

        // before we try and add a product, we should query if we already have it?
        string shopifyGetProduct = String.Format(shopifyGetProductFmt, Uri.EscapeUriString(shopify.product.title));
        HttpResponseMessage getResponse = client.GetAsync(shopifyGetProduct).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
        if (getResponse.IsSuccessStatusCode)
        {
            bool foundProduct;
            foundProduct = false;
            // Parse the response body.
            GetProducts curProduct = getResponse.Content.ReadAsAsync<GetProducts>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
            if (curProduct != null)
            {
                foreach (var cp in curProduct.products)
                {
                    Console.WriteLine("found id: {0}", cp.id);
                    foundProduct = true;
                }
            }
            if (!foundProduct)
            {

                HttpResponseMessage response = client.PostAsJsonAsync(shopifyAddProduct, shopify).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body.
                    AddProducts newProduct = response.Content.ReadAsAsync<AddProducts>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                    if ((newProduct != null) && (newProduct.product != null))
                    {
                        Console.WriteLine("new id: {0}", newProduct.product.id);
                    }
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)getResponse.StatusCode, getResponse.ReasonPhrase);
        }

        //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
        client.Dispose();
</code>```

No the code is not really asynchronous - I'll leave that to you to work out - I'm demonstrating how to use HttpClient with Shopify, not demonstrating how to write asynchronous code.

The AddProduct class can be generated by pasting the returned JSON into visual studio with 'paste special'.  However the 'Root' classes are a bit difficult, so I'll paste them here:

```<code>public class AddProducts
{
    public Product product { get; set; }
}

public class GetProducts
{
    public Product[] products { get; set; }
}
</code>```

Good luck!

Body:
has anybody got a . net example  of running a simple post to the shopify create order Ive seen some really old examples but they dont seem to work the ones that do answer have  no code examples im trying the following but just get bad request back, surely this should be simple?

private static async Task runShopifyAsyncCreateOrderJsonTask()
    {
        using (var handler = new HttpClientHandler { Credentials = GetCredential() })
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

           string json = @"{'order': {'line_items': [{'variant_id': 720123393,'quantity': 1}]}}";

            // HTTP post
            HttpResponseMessage response = await     client.PostAsJsonAsync("admin/orders.json", test);
            if (response.IsSuccessStatusCode)
            {
                Uri uri = response.Headers.Location;
                var results = await response.Content.ReadAsStringAsync();

            }
        }
    }

Body:
After some playing around I found this works:

        string ShopPath = "/admin/api/2020-04/";
        string shopifyAddProduct = "products.json";
        string shopifyGetProductFmt = "products.json?title={0}";
        string URL = String.Format("https://{0}.myshopify.com{1}", ShopName, ShopPath);
        var clientHandler = new HttpClientHandler
        {
            Credentials = new NetworkCredential(APIkey/*username*/, APIpass/*Password*/),
            PreAuthenticate = true
        };
        HttpClient client = new HttpClient(clientHandler);
        client.BaseAddress = new Uri(URL);

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // need an access token...
        client.DefaultRequestHeaders.Add("X-Shopify-Access-Token", APIpass);

        var shopify = new
        {
            product = new
            {
                title = "Burton Custom Freestyle 151",
                body_html = "<strong>Good snowboard!</strong>",
                vendor = "Snowboard",
                product_type = "Snowboard",
                published = false
            }
        };

        // before we try and add a product, we should query if we already have it?
        string shopifyGetProduct = String.Format(shopifyGetProductFmt, Uri.EscapeUriString(shopify.product.title));
        HttpResponseMessage getResponse = client.GetAsync(shopifyGetProduct).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
        if (getResponse.IsSuccessStatusCode)
        {
            bool foundProduct;
            foundProduct = false;
            // Parse the response body.
            GetProducts curProduct = getResponse.Content.ReadAsAsync<GetProducts>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
            if (curProduct != null)
            {
                foreach (var cp in curProduct.products)
                {
                    Console.WriteLine("found id: {0}", cp.id);
                    foundProduct = true;
                }
            }
            if (!foundProduct)
            {

                HttpResponseMessage response = client.PostAsJsonAsync(shopifyAddProduct, shopify).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body.
                    AddProducts newProduct = response.Content.ReadAsAsync<AddProducts>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                    if ((newProduct != null) && (newProduct.product != null))
                    {
                        Console.WriteLine("new id: {0}", newProduct.product.id);
                    }
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)getResponse.StatusCode, getResponse.ReasonPhrase);
        }

        //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
        client.Dispose();

No the code is not really asynchronous - I'll leave that to you to work out - I'm demonstrating how to use HttpClient with Shopify, not demonstrating how to write asynchronous code.

The AddProduct class can be generated by pasting the returned JSON into visual studio with 'paste special'.  However the 'Root' classes are a bit difficult, so I'll paste them here:

public class AddProducts
{
    public Product product { get; set; }
}

public class GetProducts
{
    public Product[] products { get; set; }
}

Good luck!


问:
How to sort list of string in ascending way?
I have a list of strings. They are actually files.

```<code>image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]
</code>```

I want to sort them like:

```<code>['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '9.jpg', '11.jpg', '20.jpg', '29.jpg']
</code>```

I tried with sorted(image_files, key = len) but failed.

答:
Sort by number:

```<code>import os

sorted_files = sorted(image_files, key=lambda x: int(os.path.splitext(x)[0]))
</code>```

You could also zero-pad your file names to help with sorting.

Body:
I have a list of strings. They are actually files.

image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]

I want to sort them like:

['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '9.jpg', '11.jpg', '20.jpg', '29.jpg']

I tried with sorted(image_files, key = len) but failed.

Body:
Sort by number:

import os

sorted_files = sorted(image_files, key=lambda x: int(os.path.splitext(x)[0]))

You could also zero-pad your file names to help with sorting.


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
The only reason for memory leak in .NET application is that objects are still being referenced although their life span has ended.  Hence, the garbage collector cannot collect them.  And they become long lived objects.

I find that it's very easy to cause leak by subscribing to events without unsubscribing it when the object's life ends.

OwnerDisplayName: Joan Venge

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: mqbt


问:
Possible improvements to Java's ArrayList/Scala's ArrayBuffer?
Currently, the "growing" algorithm figures out that the Array backing the ArrayList/ArrayBuffer is too small for the requested operation and copies the contents to the beginning of a larger array.

jsuereth explains it very well in the comments of this thread:

ArrayBuffer is great for append but
  not as good for prepend. Java's
  ArrayList will actually try to
  amortize costs to prepend as well,
  making it slightly better in my
  opinion. Yes ArrayBuffer is probably
  good enough if you're just appending
  on to a list and indexing elements.

Wouldn't it be a good enhancement to make the location of the old contents depend on the last operation, based on the assumption that this operation might be called more often in the future?

I. e.:

if append needs a larger array, copy the existing contents to the front of the new array:

```<code>[x|x|x|x|x|x]
       |
       v
[x|x|x|x|x|x| | | | | ]
</code>```

if prepend needs a larger array, copy the existing contents to the back of the new array:

```<code>[x|x|x|x|x|x]
       |
       v
[ | | | | |x|x|x|x|x|x]
</code>```

Will this solve the performance problems for prepend, while generally making the algorithm a bit more adaptive to usage patterns? (Worst case would be alternatively appending/prepending large stuff ...)

Are there any other data structures which already take the last operation into account when growing the underlying structure?

答: If you're not going to do a lot of lookups, and just be doing linear traversals, then go for the UnrolledBuffer - an unrolled linked list implementation. Otherwise, a Vector and its +: should be an efficient choice.

Body:
Currently, the "growing" algorithm figures out that the Array backing the ArrayList/ArrayBuffer is too small for the requested operation and copies the contents to the beginning of a larger array.

jsuereth explains it very well in the comments of this thread:

ArrayBuffer is great for append but
  not as good for prepend. Java's
  ArrayList will actually try to
  amortize costs to prepend as well,
  making it slightly better in my
  opinion. Yes ArrayBuffer is probably
  good enough if you're just appending
  on to a list and indexing elements.

Wouldn't it be a good enhancement to make the location of the old contents depend on the last operation, based on the assumption that this operation might be called more often in the future?

I. e.:

if append needs a larger array, copy the existing contents to the front of the new array:

[x|x|x|x|x|x]
       |
       v
[x|x|x|x|x|x| | | | | ]

if prepend needs a larger array, copy the existing contents to the back of the new array:

[x|x|x|x|x|x]
       |
       v
[ | | | | |x|x|x|x|x|x]

Will this solve the performance problems for prepend, while generally making the algorithm a bit more adaptive to usage patterns? (Worst case would be alternatively appending/prepending large stuff ...)

Are there any other data structures which already take the last operation into account when growing the underlying structure?


问:
Laravel Blade form money/currency format
I am building a form in Laravel (4.2) with Blade.

There are many options for input types. But, how do I set in input field set as an currency field? When I want to enter the money I paid for a product for example?

```<code>{{ Form::label('money', 'money:') }}
{{ Form::number('money') }}
</code>```

I wanted the input field to become a number with a comma for separation and two digits after it:

€ |input field here|,|inputfield for digits|

I want it to display like.
€ 150 , 54

Can you tell me what to do, please? An explanation with link to some docs would be great! The Laravel docs at http://laravel.com/docs/4.2/html#number aren't really helpfull

Thanks in advance!

答:
The correct way to from at a number or currency, is inside Laravel and PHP, JavaScript date and time formatting can change depending on the local settings.

You can create a Laravel Custom Blade Directives in your app/Providers/AppServiceProvider file.

Inside the boot function of your AppServiceProvider class add

```<code>\Blade::directive('convert', function ($value) {
    return "<?php echo number_format($value, 2); ?>";
});
</code>```

Then inside of your blade templates you will be able to use

```<code>@convert(293)
</code>```

Which returns 293.00

number_format

Laravel Custom Blade Directive

Body:
I am building a form in Laravel (4.2) with Blade.

There are many options for input types. But, how do I set in input field set as an currency field? When I want to enter the money I paid for a product for example?

{{ Form::label('money', 'money:') }}
{{ Form::number('money') }}

I wanted the input field to become a number with a comma for separation and two digits after it:

€ |input field here|,|inputfield for digits|

I want it to display like.
€ 150 , 54

Can you tell me what to do, please? An explanation with link to some docs would be great! The Laravel docs at http://laravel.com/docs/4.2/html#number aren't really helpfull

Thanks in advance!

Body:
The correct way to from at a number or currency, is inside Laravel and PHP, JavaScript date and time formatting can change depending on the local settings.

You can create a Laravel Custom Blade Directives in your app/Providers/AppServiceProvider file.

Inside the boot function of your AppServiceProvider class add

\Blade::directive('convert', function ($value) {
    return "<?php echo number_format($value, 2); ?>";
});

Then inside of your blade templates you will be able to use

@convert(293)

Which returns 293.00

number_format

Laravel Custom Blade Directive


问:
How to get timestamp of pushnotification in Swift?
I am trying to get pushnotification data. I am able to get title and body but i am also trying to get timestamp.

I am getting data like

```<code>   func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print full message.

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let body = alert["body"] as? String,
            let title = alert["title"] as? String
            else {
                // handle any error here
                return
            }

        print("Title: \(title) \nBody:\(body)")

        completionHandler()
    }
</code>```

is there any way to get timestamp in pushnotification payload itself or via any other way?

答:
You should add custom timestamp data into your Push Notification's payload.

Normally the payload looks like this;

```<code>{
    "aps":{
        "alert":{
            "title":"Hello",
            "body":"How are you?"
        },
        "badge":0,
        "sound":"default"
    }
}
</code>```

If you want to add custom fields into the payload it should be look like ->

```<code>{
    "aps":{
        "alert":{
            "title":"Hello",
            "body":"How are you?"
        },
        "badge":0,
        "sound":"default"
    },
    "timestamp": "1590736069"
}
</code>```

The custom fields are has to locate outside to aps object.

Please check this out -> Apple Documentation

Then you need to parse it

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo
    // Print full message.

    guard
        let aps = userInfo["aps"] as? NSDictionary,
        let alert = aps["alert"] as? NSDictionary,
        let body = alert["body"] as? String,
        let title = alert["title"] as? String,
        let timestamp = userInfo["timestamp"] as? String
            else {
                // handle any error here
                return
            }

    print("Title: \(title) \nBody:\(body)")
    print("Timestamp is: \(timestamp)")
    completionHandler()
}
```

<p><strong>Note:</strong> Don't need to use <code>AnyHashable</code> to use string as a key. Use like <code>userInfo["aps"]</code></p>

<hr>

<p><strong>Getting current date's timestamp</strong></p>

<p>If you need to know notification received date you can simply get current <code>Date</code>'s timestamp value like this -></p>

<pre class="lang-swift prettyprint-override"><code>// Declare this in `didReceive` method and now you know the timestamp of notification received date
let timestamp = Date().timeIntervalSince1970
</code>```

Body:
I am trying to get pushnotification data. I am able to get title and body but i am also trying to get timestamp.

I am getting data like

   func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print full message.

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let body = alert["body"] as? String,
            let title = alert["title"] as? String
            else {
                // handle any error here
                return
            }

        print("Title: \(title) \nBody:\(body)")

        completionHandler()
    }

is there any way to get timestamp in pushnotification payload itself or via any other way?

Body:
You should add custom timestamp data into your Push Notification's payload.

Normally the payload looks like this;

{
    "aps":{
        "alert":{
            "title":"Hello",
            "body":"How are you?"
        },
        "badge":0,
        "sound":"default"
    }
}

If you want to add custom fields into the payload it should be look like ->

{
    "aps":{
        "alert":{
            "title":"Hello",
            "body":"How are you?"
        },
        "badge":0,
        "sound":"default"
    },
    "timestamp": "1590736069"
}

The custom fields are has to locate outside to aps object.

Please check this out -> Apple Documentation

Then you need to parse it

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo
    // Print full message.

    guard
        let aps = userInfo["aps"] as? NSDictionary,
        let alert = aps["alert"] as? NSDictionary,
        let body = alert["body"] as? String,
        let title = alert["title"] as? String,
        let timestamp = userInfo["timestamp"] as? String
            else {
                // handle any error here
                return
            }

    print("Title: \(title) \nBody:\(body)")
    print("Timestamp is: \(timestamp)")
    completionHandler()
}

Note: Don't need to use AnyHashable to use string as a key. Use like userInfo["aps"]

Getting current date's timestamp

If you need to know notification received date you can simply get current Date's timestamp value like this ->

// Declare this in `didReceive` method and now you know the timestamp of notification received date
let timestamp = Date().timeIntervalSince1970


问:
jsPDF, insert image with customized styles
I need to make pdf with uploaded user avatar by using jsPDF. There is my code:

```<code>public openPDF(): void {
const elem = document.getElementById('AddNewBtn');
elem.parentNode.removeChild(elem);

let imgData = this.selectedFile.src;

const data = document.getElementById('htmlData');
html2canvas(data).then(canvas => {
  console.log(canvas);
  const imgWidth = 160;
  const heightLeft = canvas.height * imgWidth / canvas.width;
  const contentDataURL = canvas.toDataURL('image/png');
  const pdf = new jsPDF('p', 'mm', 'a4');
  pdf.addImage(imgData, 'JPEG', 160, 15, 50, 50);
  pdf.addImage(contentDataURL, 'PNG', 5, 25, 200, 210);
  pdf.save('invoice.pdf');
});}
</code>```

I got it like this:

instead of to be inside grey circle the image is placed behind the page layout! Could you please help me to fix this issue ? I need to get this result:

Thanks in advance!

答: This code is working fine with me after cleaning cash and restarting application! I just delete addImage and got my desired result!</p>

Body:
I need to make pdf with uploaded user avatar by using jsPDF. There is my code:

public openPDF(): void {
const elem = document.getElementById('AddNewBtn');
elem.parentNode.removeChild(elem);

let imgData = this.selectedFile.src;

const data = document.getElementById('htmlData');
html2canvas(data).then(canvas => {
  console.log(canvas);
  const imgWidth = 160;
  const heightLeft = canvas.height * imgWidth / canvas.width;
  const contentDataURL = canvas.toDataURL('image/png');
  const pdf = new jsPDF('p', 'mm', 'a4');
  pdf.addImage(imgData, 'JPEG', 160, 15, 50, 50);
  pdf.addImage(contentDataURL, 'PNG', 5, 25, 200, 210);
  pdf.save('invoice.pdf');
});}

I got it like this:

instead of to be inside grey circle the image is placed behind the page layout! Could you please help me to fix this issue ? I need to get this result:

Thanks in advance!


答:
try this,</p>

```<code>sorted(image_files, key=lambda x : int(x.split(".")[0]))

['1.jpg', '2.jpg', '3.jpg', '4.jpg', ..]
</code>```

Title: How to sort list of string in ascending way?

Body:
try this,

sorted(image_files, key=lambda x : int(x.split(".")[0]))

['1.jpg', '2.jpg', '3.jpg', '4.jpg', ..]


问:
Simulate slow typing in Protractor
sendKeys() method would send all the keys at once (actually, one at a time but very quickly):

```<code>var elm = element(by.id("myinput"));
elm.sendKeys("test");
</code>```

Is there a way to slow the typing down so that Protractor would send one character at a time with a small delay between each of the characters?

We can slow down Protractor entirely, but that does not change the way sendKeys() works and it would also slow everything down while we just need the "send keys" part and only in specific cases.

答:
I had my auto-completer producing inconsistent results if whole string is typed in input box at once (With protractor's speed), fixed it with the following solution.</p>

```<code>var elm = element(by.id("myinput"));
elm.sendKeys("tes");  // input all except last character
browser.sleep(1000);  // add delay of 1 second
elm.sendKeys("t");    // input last character
</code>```

Title: Simulate slow typing in Protractor

Body:
sendKeys() method would send all the keys at once (actually, one at a time but very quickly):

var elm = element(by.id("myinput"));
elm.sendKeys("test");

Is there a way to slow the typing down so that Protractor would send one character at a time with a small delay between each of the characters?

We can slow down Protractor entirely, but that does not change the way sendKeys() works and it would also slow everything down while we just need the "send keys" part and only in specific cases.

Body:
I had my auto-completer producing inconsistent results if whole string is typed in input box at once (With protractor's speed), fixed it with the following solution.

var elm = element(by.id("myinput"));
elm.sendKeys("tes");  // input all except last character
browser.sleep(1000);  // add delay of 1 second
elm.sendKeys("t");    // input last character


问:
Tracing UNIX signal origins?
If I have a process that receives signals from other processes, is there a way for me to somehow tell which process (if any) sent a signal?

strace lets me trace which signals a process has received, but doesn't allow me to trace who issued them.

答:
For Linux users, there is a very easy way to identify the source of a signal. For example, the following is to find which task sends SIGKILL to others.

```<code>cd /sys/kernel/debug/tracing
echo 'sig==9' > events/signal/signal_generate/filter
echo 1 > events/signal/signal_generate/enable
: > trace
echo 1 > tracing_on
tail -f trace
</code>```

One instance, when I used 'pkill -9 sleep'.

```<code># cat trace
[...]
       pkill-2982  [001] d... 750347.835838: signal_generate: sig=9 errno=0 code=0 comm=sleep pid=2981 grp=1 res=0
</code>```

Without above 'sig==9' filter, 'trace' will show all signals sent among tasks.

Title: Tracing UNIX signal origins?

Body:
For Linux users, there is a very easy way to identify the source of a signal. For example, the following is to find which task sends SIGKILL to others.

cd /sys/kernel/debug/tracing
echo 'sig==9' > events/signal/signal_generate/filter
echo 1 > events/signal/signal_generate/enable
: > trace
echo 1 > tracing_on
tail -f trace

One instance, when I used 'pkill -9 sleep'.

# cat trace
[...]
       pkill-2982  [001] d... 750347.835838: signal_generate: sig=9 errno=0 code=0 comm=sleep pid=2981 grp=1 res=0

Without above 'sig==9' filter, 'trace' will show all signals sent among tasks.