问:
A pythonic way to insert a space before capital letters but not insert space between an Abbreviation
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word" but I also have some abbreviations as well, Like in the text "General Manager or VP".

I found an answer from David Underhill in this post:

A pythonic way to insert a space before capital letters

While this answer helps me to not insert spaces between abbreviations inside the text like "DaveIsAFKRightNow!Cool"

But it sure inserts a space between V and P in "VP".

I only have 25 experience points and i am unable to comment on the existing post, i am left with no other choice than to create another post for this similar sort of problem.

I am not that good at RegEx and not able to figure how to handle this situation.

I have tried this:

```<code>re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')
re_outer.sub(r'\1 \2', re_inner.sub(r' \1\2', 'DaveIsAFKRightNow!Cool'))
</code>```

It gives me 'Dave Is AFK Right Now! Cool'

My text sample is this:

```<code>General Manager or VP Torrance, CARequired education
</code>```

I want the output as: General Manager or VP Torrance, CA Required education

The Output i am getting is: General Manager or V P Torrance, CA Required education

答:
As an alternative, you might use a single pattern with an alternation:

```<code>((?<=[^\W[A-Z])[A-Z]|(?<=\S)[A-Z](?=[a-z]))
</code>```

In the replacement use a space followed by group 1:

```<code> \1
</code>```

Explanation

( Capture group

(?<= Positive lookahead, assert what is on the right is

[^\W[A-Z] Match a word character except for A-Z

) Close positive lookahead

| Or

(?<=\S) Positive lookbehind, assert what is on the left is

[A-Z] Match A-Z

(?=[a-z]) Positive lookahead, assert what is on the right is a-z

) Close capture group

Regex demo | Python demo

For example

```<code>import re

strings = [
    "General Manager or VP Torrance, CARequired education",
    "WordWordWord",
    "DaveIsAFKRightNow!Cool"
]
pattern = re.compile(r'((?<=[^\W[A-Z])[A-Z]|(?<=\S)[A-Z](?=[a-z]))')

for str in strings:
    print(pattern.sub(r' \1', str))
</code>```

Result

```<code>General Manager or VP Torrance, CA Required education
Word Word Word
Dave Is AFK Right Now! Cool
</code>```

Body:
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word" but I also have some abbreviations as well, Like in the text "General Manager or VP".

I found an answer from David Underhill in this post:

A pythonic way to insert a space before capital letters

While this answer helps me to not insert spaces between abbreviations inside the text like "DaveIsAFKRightNow!Cool"

But it sure inserts a space between V and P in "VP".

I only have 25 experience points and i am unable to comment on the existing post, i am left with no other choice than to create another post for this similar sort of problem.

I am not that good at RegEx and not able to figure how to handle this situation.

I have tried this:

re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')
re_outer.sub(r'\1 \2', re_inner.sub(r' \1\2', 'DaveIsAFKRightNow!Cool'))

It gives me 'Dave Is AFK Right Now! Cool'

My text sample is this:

General Manager or VP Torrance, CARequired education

I want the output as: General Manager or VP Torrance, CA Required education

The Output i am getting is: General Manager or V P Torrance, CA Required education

Body:
As an alternative, you might use a single pattern with an alternation:

((?<=[^\W[A-Z])[A-Z]|(?<=\S)[A-Z](?=[a-z]))

In the replacement use a space followed by group 1:

 \1

Explanation

( Capture group

(?<= Positive lookahead, assert what is on the right is

[^\W[A-Z] Match a word character except for A-Z

) Close positive lookahead

| Or

(?<=\S) Positive lookbehind, assert what is on the left is

[A-Z] Match A-Z

(?=[a-z]) Positive lookahead, assert what is on the right is a-z

) Close capture group

Regex demo | Python demo

For example

import re

strings = [
    "General Manager or VP Torrance, CARequired education",
    "WordWordWord",
    "DaveIsAFKRightNow!Cool"
]
pattern = re.compile(r'((?<=[^\W[A-Z])[A-Z]|(?<=\S)[A-Z](?=[a-z]))')

for str in strings:
    print(pattern.sub(r' \1', str))

Result

General Manager or VP Torrance, CA Required education
Word Word Word
Dave Is AFK Right Now! Cool


来源: stackexchange

问:
Chaining promises but with different parameters
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

```<code>app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});
</code>```

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

答:
Start using async - await:

async function loadFiles() {
    const loadTextFilesTables = await loadTextFile('tables', measureList);
    const loadTextFilesRoles = await loadTextFile('roles', roleList);
    //...
}```

ContentLicense: CC BY-SA 4.0

Body:
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)


问:
concatenate several lines in one with a delimiter with pandas
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

```<code>val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1
</code>```

It works with loops.
i need this result,

```<code>val
Cat Tiger Ball
Bat bill
dog
</code>```

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

答:
Staying in pandas:

```<code>df['group'] = (df['id'] == 1).cumsum()
df.groupby('group')['val'].apply(' '.join).reset_index()
</code>```

```<code>   id             val
0   1  Cat Tiger Ball
1   2        Bat bill
2   3             dog
</code>```

The first line defines groups according to your definition. The second line is a standard groupby operation.

Body:
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1

It works with loops.
i need this result,

val
Cat Tiger Ball
Bat bill
dog

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

Body:
Staying in pandas:

df['group'] = (df['id'] == 1).cumsum()
df.groupby('group')['val'].apply(' '.join).reset_index()

   id             val
0   1  Cat Tiger Ball
1   2        Bat bill
2   3             dog

The first line defines groups according to your definition. The second line is a standard groupby operation.


问:
How to use ISNULL() function along with join
While using the ISNULL function along with aliases of column name that I have given to form a left join, I get an error.

The error is:

I am unable to understand what am I doing wrong. The data is stored in customers table:

The sql code that I am using is:

```<code>select ISNULL(c2.name,'N/A') as referredby , c1.name as name
from customers as c1
    left outer join customers as c2 on c1.referredby = c2.id
order by referredby;
</code>```

答:
Don't use isnull()!  The standard version is coalesce():

```<code>select coalesce(cref.name, 'N/A') as referredby_name, c.name as name
from customers c left outer join
     customers cref
     on c.referredby = cref.id
order by referredby_name;
</code>```

I made a two other changes.  First, the table aliases better describe the role of the tables.  I also changed the column alias to referredby_name, so it doesn't match a column in a table.  Neither of these are required; with them, I think the query reads more easily.

Body:
While using the ISNULL function along with aliases of column name that I have given to form a left join, I get an error.

The error is:

I am unable to understand what am I doing wrong. The data is stored in customers table:

The sql code that I am using is:

select ISNULL(c2.name,'N/A') as referredby , c1.name as name
from customers as c1
    left outer join customers as c2 on c1.referredby = c2.id
order by referredby;

Body:
Don't use isnull()!  The standard version is coalesce():

select coalesce(cref.name, 'N/A') as referredby_name, c.name as name
from customers c left outer join
     customers cref
     on c.referredby = cref.id
order by referredby_name;

I made a two other changes.  First, the table aliases better describe the role of the tables.  I also changed the column alias to referredby_name, so it doesn't match a column in a table.  Neither of these are required; with them, I think the query reads more easily.


问:
Can't close custom popup at fixed position
Here is a javascript beginners problem.
I created a custom popup at fixed position(leaflet). After clicking a marker that opens the popup I can't close it by clicking the close button. I can click a different marker though , but the popup wrapper remains open showing the content attached to each different marker. So the content of the popup changes by clicking the markers but can't close the popup by clicking the close button.

I tried an eventListener.
I need that piece of code that does the job.
Any help would be appreciated.

```<code>// Adds custom marker

var redFlag = L.icon({
    iconUrl: 'images/mapmarker2.png',
    iconSize: [34, 34],
    iconAnchor: [17,34]
});

// Adds markers and popup
// geoJSON file stored in 'art' variable

const myLayer = L.geoJSON(art, {
    pointToLayer: function (feature, latlng) {
          return L.marker(latlng, {icon: redFlag});

},
onEachFeature: function ( feature, layer) {
    layer.on('click', function(e){

// popup content

   var getWrap = document.getElementById('wrapper');
        var wrap = getWrap.appendChild(document.createElement('div'));
        wrap.className = 'wrapper';
        wrap.innerHTML =
           `<div class="close">X</div>`+
           `<div class="popUpContent" style="background-color:#e8f4ff">`+
           `<div class='pic'><img src =
            "images/${feature.properties.image}"></div>`+
           `<div class="puName"><span
            class="puName">${feature.properties.name}</span><br>`+
           `<span class="puTitle">"${feature.properties.title}"</span><br>`+
           `<div class="extra3">${feature.properties.extra}</div></div>`+
           `</div>`;

    if(!feature.properties.title){

        wrap.innerHTML =
            `<div class="close">X</div>`+
            `<div class="popUpContent" style="background-color:#e8f4ff">` +
             `<div class='pic'><img src =
             "images/${feature.properties.image}"></div>`+
             `<div class="puName"><span
             class="puName">${feature.properties.name}</span><br>`+
             `<div class="extra3">${feature.properties.extra}</div></div>`+
             `</div>`;
         }

// Add eventlistener to the close button

document.querySelector('.close').addEventListener( 'click', closePopup);
      function closePopup(e){

        if(event.target.matches('.close')){
            document.querySelector(".wrapper").style.display='none'
        }else if(document.querySelector(".wrapper").style.display='block'){
            document.querySelector(".wrapper").style.display='none';
           }
         }

       });
    }

});

mymap.addLayer(myLayer)
</code>```

答:
I found the answer. It is how you construct your dynamically generated DOM element,
    wich in this case is the popup. Create one empty div with id="popup" in the div with
    id="mapid" in your HTML file. The rest is generated dynamically. The if statement of
    the eventlistener only needs that block of code necessary when a condition is true.</p>

```<code>const element = document.getElementById('popup');

      element.innerHTML =
            `<div class= "wrapper" style="background-color:#fff">`+
            `<div class="close">X</div>`+
            `<div class="popUpContent" style="background-color:#e8f4ff">` +
            `<div class='pic'><img src = "images/${feature.properties.image}"></div>
             <p>`+
            `<div class="puName"><span class="puName">${feature.properties.name}
              </span><br>`+
            `<span class="puTitle">"${feature.properties.title}"</span><br><p>` +
            `<div class="extra3">${feature.properties.extra}</div></div>`+
            `</div></div>`;

  // the eventListener

            document.getElementById('popup').addEventListener( 'click', closePopup);
                    function closePopup(e){
                if(document.querySelector('.wrapper').style.display = 'block'){
                   document.querySelector('.wrapper').style.display='none';
                }
             }
</code>```

Body:
Here is a javascript beginners problem.
I created a custom popup at fixed position(leaflet). After clicking a marker that opens the popup I can't close it by clicking the close button. I can click a different marker though , but the popup wrapper remains open showing the content attached to each different marker. So the content of the popup changes by clicking the markers but can't close the popup by clicking the close button.

I tried an eventListener.
I need that piece of code that does the job.
Any help would be appreciated.

// Adds custom marker

var redFlag = L.icon({
    iconUrl: 'images/mapmarker2.png',
    iconSize: [34, 34],
    iconAnchor: [17,34]
});

// Adds markers and popup
// geoJSON file stored in 'art' variable

const myLayer = L.geoJSON(art, {
    pointToLayer: function (feature, latlng) {
          return L.marker(latlng, {icon: redFlag});

},
onEachFeature: function ( feature, layer) {
    layer.on('click', function(e){

// popup content

   var getWrap = document.getElementById('wrapper');
        var wrap = getWrap.appendChild(document.createElement('div'));
        wrap.className = 'wrapper';
        wrap.innerHTML =
           `<div class="close">X</div>`+
           `<div class="popUpContent" style="background-color:#e8f4ff">`+
           `

`+
           `
${feature.properties.name}
`+
           `<span class="puTitle">"${feature.properties.title}"</span><br>`+
           `<div class="extra3">${feature.properties.extra}</div></div>`+
           `</div>`;

    if(!feature.properties.title){

        wrap.innerHTML =
            `<div class="close">X</div>`+
            `<div class="popUpContent" style="background-color:#e8f4ff">` +
             `

`+
             `
${feature.properties.name}
`+
             `<div class="extra3">${feature.properties.extra}</div></div>`+
             `</div>`;
         }

// Add eventlistener to the close button

document.querySelector('.close').addEventListener( 'click', closePopup);
      function closePopup(e){

        if(event.target.matches('.close')){
            document.querySelector(".wrapper").style.display='none'
        }else if(document.querySelector(".wrapper").style.display='block'){
            document.querySelector(".wrapper").style.display='none';
           }
         }

       });
    }

});

mymap.addLayer(myLayer)

Body:
I found the answer. It is how you construct your dynamically generated DOM element,
    wich in this case is the popup. Create one empty div with id="popup" in the div with
    id="mapid" in your HTML file. The rest is generated dynamically. The if statement of
    the eventlistener only needs that block of code necessary when a condition is true.

const element = document.getElementById('popup');

      element.innerHTML =
            `<div class= "wrapper" style="background-color:#fff">`+
            `<div class="close">X</div>`+
            `<div class="popUpContent" style="background-color:#e8f4ff">` +
            `<div class='pic'><img src = "images/${feature.properties.image}"></div>
             <p>`+
            `<div class="puName"><span class="puName">${feature.properties.name}
              </span><br>`+
            `<span class="puTitle">"${feature.properties.title}"</span><br><p>` +
            `<div class="extra3">${feature.properties.extra}</div></div>`+
            `</div></div>`;

  // the eventListener

            document.getElementById('popup').addEventListener( 'click', closePopup);
                    function closePopup(e){
                if(document.querySelector('.wrapper').style.display = 'block'){
                   document.querySelector('.wrapper').style.display='none';
                }
             }


问:
Button disabling is not working on JavaScript section
On a RoR website home page I need to disable a button while a text blank is empty.

Here is the HAML code of the button :

https://image.noelshack.com/fichiers/2019/22/2/1559049919-btn.jpg

Here is my JavaScript code supposed to conditions the disabling :

https://image.noelshack.com/fichiers/2019/22/2/1559050733-disabled.jpg

Adding "disabled = true" in my HAML works but not in the JS (so the button stays disabled during all process which is -obviously- not what we want)

I already tried to use the disable command line out of if/else and it is still not working.

I'm a newbie in RoR so it is probably a grammatical mistake

Thanks for your help !

答:
Try to use:

```<code>$('.save_task_btn').attr("disabled", true);
$('.save_task_btn').attr("disabled", false);
</code>```

instead of

```<code>$('.save_task_btn').disabled = true;
</code>```

Body:
Try to use:

$('.save_task_btn').attr("disabled", true);
$('.save_task_btn').attr("disabled", false);

instead of

$('.save_task_btn').disabled = true;


问:
How do I use a case statement to loop through an array of objects and add a value to a key inside the array?
I would like to look through an array of objects using a case statement and add a new value to the key name. I am new to programming please use the most simple examples and explanations.

I've attempted to write a case statement as using the equals operator to add the new value to the key name.

beatles = [
    {
      name: nil,
      nickname: "The Smart One"
    },
    {
      name: nil,
      nickname: "The Funny One"
    },
    {
      name: nil,
      nickname: "The Cute One"
      },
    {
      name: nil,
      nickname: "The Quiet One"
    }
  ]

  i = 0
  while i < beatles.length
    case beatles
    when nickname == "The Smart One"
        name = "John"
    when nickname == "The Funny One"
        name = "Ringo"
    when nickname == "The Cute One"
        name = "Paul"
    when nickname == "The Quiet One"
        name = "George"
    end
    i += 1
  end

  i = 0
  while i < beatles.length
    puts "Hi, I'm #{beatles[i][:name]}.  I'm #{beatles[i][:nickname]}!"
    i += 1
  end
```

答:
Nobody uses while loop in Ruby (we use Enumerable#each, Enumerable#map and Enumerable#reduce instead,) but for the sake of the answering the question stated here is the requested version.

```<code>while i < beatles.length
  beatles[i][:name] =
    case beatles[i][:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
  i += 1
end
</code>```

case compares its argument against variants (using Object#=== method.) Also, you don’t want to assign name inside case, it’s better to assign it to the result of case instead.

The Ruby idiomatic version:

```<code>beatles.each do |beatle|
  beatle[:name] =
    case beatle[:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
end
</code>```

Body:
Nobody uses while loop in Ruby (we use Enumerable#each, Enumerable#map and Enumerable#reduce instead,) but for the sake of the answering the question stated here is the requested version.

while i < beatles.length
  beatles[i][:name] =
    case beatles[i][:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
  i += 1
end

case compares its argument against variants (using Object#=== method.) Also, you don’t want to assign name inside case, it’s better to assign it to the result of case instead.

The Ruby idiomatic version:

beatles.each do |beatle|
  beatle[:name] =
    case beatle[:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
end


问:
NSDate, NSCalendar and NSDateComponents timing
```<code>NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];

NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

 NSLog(@" %i %i %i ", day, month, year);
</code>```

That code show me "12 2147483647 2147483647"

How can I get the month and year (integer)

How can add/forward one day? (if we are the first of the month too!)

Thant you for your attention :-)

答:
```<code>NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

[calendar release];
</code>```

hope this helps

ContentLicense: CC BY-SA 3.0

Body:
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];

NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

 NSLog(@" %i %i %i ", day, month, year);

That code show me "12 2147483647 2147483647"

How can I get the month and year (integer)

How can add/forward one day? (if we are the first of the month too!)

Thant you for your attention :-)

Body:
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

[calendar release];

hope this helps


问:
sum set values in a Dataframe
Iam trying to sum a column inside a dataFrame that is a set of int.

something like : ['xxxx',{1,2,3}] and i need ['xxxx',6]

Thanks for your help.

 for index,row in df_clusters.iterrows():
        if isinstance(row['sum_coefs'],set):
            row.loc['sum_coefs']=sum(row['sum_coefs'])
```

I got at the output an unchanged Dataframe with a set in my sum_coefs column and not the sum.

答:
Could try using Series.apply:

```<code># Setup
df_clusters = pd.DataFrame(['xxxx',set([1,2,3])], columns=['sum_coefs'])

def sum_sets(val):
    if isinstance(val, set):
        return sum(val)
    return val

df_clusters['sum_coefs'] = df_clusters['sum_coefs'].apply(sum_sets)
</code>```

[out]

```<code>0    xxxx
1       6
dtype: object
</code>```

Or alternatively, using an inline lambda function to achieve the same result:

```<code>df_clusters['sum_coefs'] = df_clusters['sum_coefs'].apply(lambda x: sum(x) if isinstance(x, set) else x)
</code>```

Title: sum set values in a Dataframe

Body:
Iam trying to sum a column inside a dataFrame that is a set of int.

something like : ['xxxx',{1,2,3}] and i need ['xxxx',6]

Thanks for your help.

 for index,row in df_clusters.iterrows():
        if isinstance(row['sum_coefs'],set):
            row.loc['sum_coefs']=sum(row['sum_coefs'])

I got at the output an unchanged Dataframe with a set in my sum_coefs column and not the sum.

Body:
Could try using Series.apply:

# Setup
df_clusters = pd.DataFrame(['xxxx',set([1,2,3])], columns=['sum_coefs'])

def sum_sets(val):
    if isinstance(val, set):
        return sum(val)
    return val

df_clusters['sum_coefs'] = df_clusters['sum_coefs'].apply(sum_sets)

[out]

0    xxxx
1       6
dtype: object

Or alternatively, using an inline lambda function to achieve the same result:

df_clusters['sum_coefs'] = df_clusters['sum_coefs'].apply(lambda x: sum(x) if isinstance(x, set) else x)


问:
how can i populate a field with id while saving but id is not existing yet
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID.
Example:
The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021

my relevant code:
My Model:

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)
</code>```

I tried do populate the fields with a for loop in my views.py

```<code> def Index(request):
    ticket = Ticket.objects.all()
    for t in ticket:
      id = len(str(t.id))
      if id == 1:
        t.designation = "#" + str("0000") + str(t.id)
      elif id == 2:
        t.designation = "#" + str("000") + str(t.id)
      elif id == 3:
        t.designation = "#" + str("00") + str(t.id)
      elif id == 4:
        t.designation = "#" + str("0") + str(t.id)
      else:
        t.designation = "#" + str(t.id)
    context = {'ticket':ticket}
    return render(request, 'ticketsystem/index.html', context)
</code>```

and the output was correct, but I would like to have the population while creating the object

i tried the following, by adding it to my Ticket model:

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        id = len(str(id))
        if id == 1:
            designation = "#" + str("0000") + str(id)
        elif id == 2:
            designation = "#" + str("000") + str(id)
        elif id == 3:
            designation = "#" + str("00") + str(id)
        elif id == 4:
            designation = "#" + str("0") + str(id)
        else:
            designation = "#" + str(id)
        super().save()
</code>```

but following error comes up:

local variable 'id' referenced before assignment

答:
You've not overwritten the id field so it is going to be an integer and you want to let Django handle the autoincrement etc.

You would be better off (in my opinion) simply adding a new field which takes the id and converts it to a string

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    @property
    def ticketkennung(self):
        this_id = str(self.id)
        if len(this_id) = 1 : str_id = '0000' + this_id
        etc ...
        return this_id
</code>```

OR

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        this_id = len(str(self.id))
        if id == 1: self.designation = "#" + str("0000") + str(id)
        etc
        super().save(*args, **kwargs)
</code>```

Body:
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID.
Example:
The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021

my relevant code:
My Model:

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

I tried do populate the fields with a for loop in my views.py

 def Index(request):
    ticket = Ticket.objects.all()
    for t in ticket:
      id = len(str(t.id))
      if id == 1:
        t.designation = "#" + str("0000") + str(t.id)
      elif id == 2:
        t.designation = "#" + str("000") + str(t.id)
      elif id == 3:
        t.designation = "#" + str("00") + str(t.id)
      elif id == 4:
        t.designation = "#" + str("0") + str(t.id)
      else:
        t.designation = "#" + str(t.id)
    context = {'ticket':ticket}
    return render(request, 'ticketsystem/index.html', context)

and the output was correct, but I would like to have the population while creating the object

i tried the following, by adding it to my Ticket model:

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        id = len(str(id))
        if id == 1:
            designation = "#" + str("0000") + str(id)
        elif id == 2:
            designation = "#" + str("000") + str(id)
        elif id == 3:
            designation = "#" + str("00") + str(id)
        elif id == 4:
            designation = "#" + str("0") + str(id)
        else:
            designation = "#" + str(id)
        super().save()

but following error comes up:

local variable 'id' referenced before assignment

Body:
You've not overwritten the id field so it is going to be an integer and you want to let Django handle the autoincrement etc.

You would be better off (in my opinion) simply adding a new field which takes the id and converts it to a string

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    @property
    def ticketkennung(self):
        this_id = str(self.id)
        if len(this_id) = 1 : str_id = '0000' + this_id
        etc ...
        return this_id

OR

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        this_id = len(str(self.id))
        if id == 1: self.designation = "#" + str("0000") + str(id)
        etc
        super().save(*args, **kwargs)


问:
How to remove padding of List item in vuetify
When coding Vue project with vuetify, I found there are useless padding in <v-list> tag, in detail, it is about <v-list-tile> tag.

image: https://segmentfault.com/img/bVbtemC?w=890&h=1288

There are one parent list item and one child list item, and there are some padding space in left and right.

I have followed official methods to set class="pa-0", however, it does not work when I add this class to all the tags around.

And of course set CSS directly does not work too, the image above shows that the target tag is the one with class="v-list__tile", but CSS on this class still does not work.

```<code>  <v-navigation-drawer width="200px" stateless value="true"
    class="transparent">
    <v-list subheader dense expand>
      <v-list-group no-action>
        <template v-slot:activator>
          <v-list-tile class="pa-0">
            <v-icon left>home</v-icon>
            <v-list-tile-title>menu-name-m</v-list-tile-title>
          </v-list-tile>
        </template>

        <v-list-tile class="pa-0" @click="onMenuCliked">
          <v-list-tile-title>no child - menu-name</v-list-tile-title>
        </v-list-tile>

      </v-list-group>
    </v-list>
  </v-navigation-drawer>
</code>```

This is my code partly, it is in vue-cli.

I know remove no-action in <v-list-group> tag works on child list item, but it is not the way I want, and this does not work on the parent one.

I hope I can control the green padding in the image above, or juest remove it.

答:
v-list-item renders the following html

```<code><div role="listitem">
  <div class="v-list__tile theme--light">

  </div>
</div>
</code>```

So setting the class appends it to the parent div, instead of v-list__tile - which is the actually div with the padding.

Sometimes vuetify way around this is using the content-class prop instead, but this component does not seem to support it, so you gotta target it by css, for example

```<code>.v-list__tile {
  padding: 0
}
</code>```

You could still use class if you want more specificity:

```<code><v-list-tile class="my-tile">

.my-tile .v-list__tile {
  padding: 0
}
</code>```

If it's not working and you are using scoped styles, see more

Body:
When coding Vue project with vuetify, I found there are useless padding in <v-list> tag, in detail, it is about <v-list-tile> tag.

image: https://segmentfault.com/img/bVbtemC?w=890&h=1288

There are one parent list item and one child list item, and there are some padding space in left and right.

I have followed official methods to set class="pa-0", however, it does not work when I add this class to all the tags around.

And of course set CSS directly does not work too, the image above shows that the target tag is the one with class="v-list__tile", but CSS on this class still does not work.

  <v-navigation-drawer width="200px" stateless value="true"
    class="transparent">
    <v-list subheader dense expand>
      <v-list-group no-action>
        <template v-slot:activator>
          <v-list-tile class="pa-0">
            <v-icon left>home</v-icon>
            <v-list-tile-title>menu-name-m</v-list-tile-title>
          </v-list-tile>
        </template>

        <v-list-tile class="pa-0" @click="onMenuCliked">
          <v-list-tile-title>no child - menu-name</v-list-tile-title>
        </v-list-tile>

      </v-list-group>
    </v-list>
  </v-navigation-drawer>

This is my code partly, it is in vue-cli.

I know remove no-action in <v-list-group> tag works on child list item, but it is not the way I want, and this does not work on the parent one.

I hope I can control the green padding in the image above, or juest remove it.

Body:
v-list-item renders the following html

<div role="listitem">
  <div class="v-list__tile theme--light">

  </div>
</div>

So setting the class appends it to the parent div, instead of v-list__tile - which is the actually div with the padding.

Sometimes vuetify way around this is using the content-class prop instead, but this component does not seem to support it, so you gotta target it by css, for example

.v-list__tile {
  padding: 0
}

You could still use class if you want more specificity:

<v-list-tile class="my-tile">

.my-tile .v-list__tile {
  padding: 0
}

If it's not working and you are using scoped styles, see more


问:
Fetch two images from JSON
We are fetching 2 images using JSON - Mask image & Car

https://jsfiddle.net/x80rcwzj/1/

Due to some reasons, i changed some code in below functions in above fiddle:

```<code>container.scaleMask [ container.drawMask ]
function renderInnerImage [ container.drawImage ]
container.loadImage
container.loadMaskImage
</code>```

Issue :

Now Car image is not displaying :
https://jsfiddle.net/m0pfoa5L/1/

Here is CodePen: https://codepen.io/kidsdial/pen/RmBxZz

Below is Code Snippet :

var target;
        const imageUrl = "https://i.imgur.com/RzEm1WK.png";

        let jsonData = {
            "layers": [{
                "x": 0,
                "height": 612,
                "layers": [{
                    "x": 160,
                    "src": "ax0HVTs.png",
                    "y": 91,
                    "height": 296,
                    "width": 429,
                    "name": "mask_1"
                }, {
                    "x": 25,
                    "src": "iEA642D.jpg",
                    "height": 324,
                    "width": 471,
                    "y": 22,
                    "name": "car"
                }],
                "y": 0,
                "width": 612
            }]
        };

        const containerElement = $('#container');
        const fileUp = $('#fileup');
        let mask;

        $(function() {

            // Upload image onclick mask image

            containerElement.click(function(e) {
                var res = e.target;
                target = res.id;
                if (e.target.getContext) {
                    // click only inside Non Transparent part
                    var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
                    if (pixel[3] === 255) {
                        setTimeout(() => {
                            $('#fileup').click();
                        }, 20);
                    }
                }
            });

            // Fetch mask images from json file - IGNORE this code

            function getAllSrc(layers) {
                let arr = [];
                layers.forEach(layer => {
                    if (layer.src) {
                        arr.push({
                            src: layer.src,
                            x: layer.x,
                            y: layer.y,
                            height: layer.height,
                            width: layer.width,
                            name: layer.name
                        });
                    } else if (layer.layers) {
                        let newArr = getAllSrc(layer.layers);
                        if (newArr.length > 0) {
                            newArr.forEach(({
                                src,
                                x,
                                y,
                                height,
                                width,
                                name
                            }) => {
                                arr.push({
                                    src,
                                    x: (layer.x + x),
                                        y: (layer.y + y),
                                        height,
                                        width,
                                        name: (name)
                                });
                            });
                        }
                    }
                });
                return arr;
            }

            function json(data) {
                var width = 0;
                var height = 0;

                let arr = getAllSrc(data.layers);
                let layer1 = data.layers;
                width = layer1[0].width;
                height = layer1[0].height;
                let counter = 0;
                let table = [];

                // container dimensions
                containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
                //end

                for (let {
                        src,
                        x,
                        y,
                        name
                    }
                    of arr) {

                    //Get Height and width of mask image [ edit button ]
                    var ImagePosition = arr;
                    //code end

                    if(name.indexOf('mask_') !== -1){
                    var imageUrl1 = imageUrl;
                }else{
                    var imageUrl1 = '';
                }

                    var mask = $(".container").mask({
                        imageUrl: imageUrl1,

                        // Fetch Mask images
                        maskImageUrl: 'http://i.imgur.com/' + src,
                        // end

                        onMaskImageCreate: function(img) {
                            // Mask image positions
                            img.css({
                                "position": "absolute",
                                "left": x + "px",
                                "top": y + "px"
                            });
                            // end

                        },
                        id: counter
                    });
                    // here
                    table.push(mask);
                    fileup.onchange = function() {

                        let mask2 = table[target];
                        const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                        document.getElementById('fileup').value = "";

                    };
                    counter++;
                }
                return mask;
            }
            mask = json(jsonData);
        }); // end of function

        // Image code

        (function($) {
            window.JQmasks = [];
            $.fn.mask = function(options) {
                // This is the easiest way to have default options.
                var settings = $.extend({
                    // These are the defaults.
                    maskImageUrl: undefined,
                    imageUrl: undefined,
                    scale: 1,
                    id: new Date().getUTCMilliseconds().toString(),
                    x: 0, // image start position
                    y: 0, // image start position
                    onMaskImageCreate: function(div) {},
                }, options);

                // Create the image properties
                settings.maskImage = new Image
                settings.image  = new Image

                // set the cross-origin attributes
                settings.maskImage.setAttribute('crossOrigin', 'anonymous');
                settings.image.setAttribute('crossOrigin', 'anonymous');

                settings.maskImage.onload = function() {
                    // once the mask is loaded, load the image
                    container.loadImage(settings.imageUrl)
                }

                settings.image.onload = function() {
                    // once the image is loaded, render to canvas
                    container.drawMask()
                    container.drawImage()
                }

                var container = $(this);

                let prevX = 0,
                    prevY = 0,
                    draggable = false,
                    img,
                    canvas,
                    context,
                    image,
                    timeout,
                    initImage = false,
                    startX = settings.x,
                    startY = settings.y,
                    div;

                container.drawMask = function() {
                    canvas.width = settings.maskImage.width;
                    canvas.height = settings.maskImage.height;
                    context.save();
                    context.beginPath();
                    context.globalCompositeOperation = "source-over";
                    // draw the masked image after scaling
                    context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
                    context.restore()
                };

                container.drawImage = function() {

                    const img = settings.image

                    settings.x = (canvas.width - (img.width * settings.scale)) / 2
                    settings.y = (canvas.height - (img.height * settings.scale)) / 2

                    context.globalCompositeOperation = 'source-atop';
                    context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                    initImage = false;
                }

                // change the draggable image

                container.loadImage = function(imageUrl) {

                    settings.y = startY;
                    settings.x = startX;
                    prevX = prevY = 0;

                    initImage = true;

                    settings.image.src = imageUrl; // CHANGED

                    // sirpepole Add this
                    return settings.id;
                };

                container.loadMaskImage = function(imageUrl, from) {
                    canvas = document.createElement("canvas");
                    context = canvas.getContext('2d');
                    canvas.setAttribute("draggable", "true");
                    canvas.setAttribute("id", settings.id);
                    // settings.maskImageUrl = imageUrl;
                    settings.maskImage.src = imageUrl // CHANGED

                    div = $("
", {
                        "class": "masked-img"
                    }).append(canvas);

                    // div.find("canvas").on('touchstart mousedown', function(event)
                    div.find("canvas").on('dragstart', function(event) {
                        if (event.handled === false) return;
                        event.handled = true;
                        container.onDragStart(event);
                    });

                    div.find("canvas").on('touchend mouseup', function(event) {
                        if (event.handled === false) return;
                        event.handled = true;
                        container.selected(event);
                    });

                    div.find("canvas").bind("dragover", container.onDragOver);

                    container.append(div);
                    if (settings.onMaskImageCreate)
                        settings.onMaskImageCreate(div);

                    // container.loadImage(settings.imageUrl);
                    // Moved this to the settings.maskImage.onload
                };
                container.loadMaskImage(settings.maskImageUrl);
                JQmasks.push({
                        item: container,
                        id: settings.id
                    })
                    // Edit image
                div.addClass('masked-img' + settings.id);
                div.attr('data-id', settings.id);
                // ends
                return container;
            };
        }(jQuery));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
        background: silver;
        position: relative;
    }

    .container img {
        position: absolute;
        top: 0;
        bottom: 250px;
        left: 0;
        right: 0;
        margin: auto;
        z-index: 999;
    }

    .masked-img {
        overflow: hidden;
        position: relative;
    }</code>```

    <input id="fileup" name="fileup" type="file" style="display:none">

```

Hint :

if I replace "name": "car" by "name": "mask_something", then car image will display, but in that case, a small icon will display on the car, but I don't want that...

答:
You trie to mask an image, but you are not loading the image because of your name.indexOf('mask_') if condition.

Therefore the car is not shown, because its name is masknot_. Because the image has no url nothing is shown. If you remove that if condition both images (car and icon) are shown, because your code says mask image with image2. But that is exactly what the mask function is for. To mask an image with another image.

So you could apply the if condition to the image that will be shown above the car to not show it if masknot_ is in the name. That is an option, but it is not recommended because a masking function should mask something.

Write a new function to display an image without applying a mask would be the best option.

Below is a working example of your code.

```<code>var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 91,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "iEA642D.jpg",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "car"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                                y: (layer.y + y),
                                height,
                                width,
                                name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            }
            of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var imageUrl1 = imageUrl;

            var mask = $(".container").mask({
                imageUrl: name.indexOf('mask_') !== -1 ? imageUrl1 : undefined,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {

                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image  = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl)
          container.drawMask()
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas

            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;

        container.drawMask = function() {
            if (!settings.maskImage) return true;
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            if (settings.maskImage) context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
            context.restore()
        };

        container.drawImage = function() {

            const img = settings.image

            settings.x = (canvas.width - (img.width * settings.scale)) / 2
            settings.y = (canvas.height - (img.height * settings.scale)) / 2

            context.globalCompositeOperation = 'source-atop';
            if (img) context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
          context.restore()
            initImage = false;
        }

        // change the draggable image

        container.loadImage = function(imageUrl) {
            if (!imageUrl) return true;
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;

            initImage = true;

            settings.image.src = imageUrl; // CHANGED

            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {

            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            // settings.maskImageUrl = imageUrl;
            settings.maskImage.src = imageUrl // CHANGED

            div = $("<div/>", {
                "class": "masked-img"
            }).append(canvas);

            // div.find("canvas").on('touchstart mousedown', function(event)
            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);

            // container.loadImage(settings.imageUrl);
            // Moved this to the settings.maskImage.onload
        };
        if (settings.maskImageUrl) {
        container.loadMaskImage(settings.maskImageUrl);
        }
        JQmasks.push({
                item: container,
                id: settings.id
            })
            // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));
</code>```

Title: Fetch two images from JSON

Body:
We are fetching 2 images using JSON - Mask image & Car

https://jsfiddle.net/x80rcwzj/1/

Due to some reasons, i changed some code in below functions in above fiddle:

container.scaleMask [ container.drawMask ]
function renderInnerImage [ container.drawImage ]
container.loadImage
container.loadMaskImage

Issue :

Now Car image is not displaying :
https://jsfiddle.net/m0pfoa5L/1/

Here is CodePen: https://codepen.io/kidsdial/pen/RmBxZz

Below is Code Snippet :

var target;
        const imageUrl = "https://i.imgur.com/RzEm1WK.png";

        let jsonData = {
            "layers": [{
                "x": 0,
                "height": 612,
                "layers": [{
                    "x": 160,
                    "src": "ax0HVTs.png",
                    "y": 91,
                    "height": 296,
                    "width": 429,
                    "name": "mask_1"
                }, {
                    "x": 25,
                    "src": "iEA642D.jpg",
                    "height": 324,
                    "width": 471,
                    "y": 22,
                    "name": "car"
                }],
                "y": 0,
                "width": 612
            }]
        };

        const containerElement = $('#container');
        const fileUp = $('#fileup');
        let mask;

        $(function() {

            // Upload image onclick mask image

            containerElement.click(function(e) {
                var res = e.target;
                target = res.id;
                if (e.target.getContext) {
                    // click only inside Non Transparent part
                    var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
                    if (pixel[3] === 255) {
                        setTimeout(() => {
                            $('#fileup').click();
                        }, 20);
                    }
                }
            });

            // Fetch mask images from json file - IGNORE this code

            function getAllSrc(layers) {
                let arr = [];
                layers.forEach(layer => {
                    if (layer.src) {
                        arr.push({
                            src: layer.src,
                            x: layer.x,
                            y: layer.y,
                            height: layer.height,
                            width: layer.width,
                            name: layer.name
                        });
                    } else if (layer.layers) {
                        let newArr = getAllSrc(layer.layers);
                        if (newArr.length > 0) {
                            newArr.forEach(({
                                src,
                                x,
                                y,
                                height,
                                width,
                                name
                            }) => {
                                arr.push({
                                    src,
                                    x: (layer.x + x),
                                        y: (layer.y + y),
                                        height,
                                        width,
                                        name: (name)
                                });
                            });
                        }
                    }
                });
                return arr;
            }

            function json(data) {
                var width = 0;
                var height = 0;

                let arr = getAllSrc(data.layers);
                let layer1 = data.layers;
                width = layer1[0].width;
                height = layer1[0].height;
                let counter = 0;
                let table = [];

                // container dimensions
                containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
                //end

                for (let {
                        src,
                        x,
                        y,
                        name
                    }
                    of arr) {

                    //Get Height and width of mask image [ edit button ]
                    var ImagePosition = arr;
                    //code end

                    if(name.indexOf('mask_') !== -1){
                    var imageUrl1 = imageUrl;
                }else{
                    var imageUrl1 = '';
                }

                    var mask = $(".container").mask({
                        imageUrl: imageUrl1,

                        // Fetch Mask images
                        maskImageUrl: 'http://i.imgur.com/' + src,
                        // end

                        onMaskImageCreate: function(img) {
                            // Mask image positions
                            img.css({
                                "position": "absolute",
                                "left": x + "px",
                                "top": y + "px"
                            });
                            // end

                        },
                        id: counter
                    });
                    // here
                    table.push(mask);
                    fileup.onchange = function() {

                        let mask2 = table[target];
                        const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                        document.getElementById('fileup').value = "";

                    };
                    counter++;
                }
                return mask;
            }
            mask = json(jsonData);
        }); // end of function

        // Image code

        (function($) {
            window.JQmasks = [];
            $.fn.mask = function(options) {
                // This is the easiest way to have default options.
                var settings = $.extend({
                    // These are the defaults.
                    maskImageUrl: undefined,
                    imageUrl: undefined,
                    scale: 1,
                    id: new Date().getUTCMilliseconds().toString(),
                    x: 0, // image start position
                    y: 0, // image start position
                    onMaskImageCreate: function(div) {},
                }, options);

                // Create the image properties
                settings.maskImage = new Image
                settings.image  = new Image

                // set the cross-origin attributes
                settings.maskImage.setAttribute('crossOrigin', 'anonymous');
                settings.image.setAttribute('crossOrigin', 'anonymous');

                settings.maskImage.onload = function() {
                    // once the mask is loaded, load the image
                    container.loadImage(settings.imageUrl)
                }

                settings.image.onload = function() {
                    // once the image is loaded, render to canvas
                    container.drawMask()
                    container.drawImage()
                }

                var container = $(this);

                let prevX = 0,
                    prevY = 0,
                    draggable = false,
                    img,
                    canvas,
                    context,
                    image,
                    timeout,
                    initImage = false,
                    startX = settings.x,
                    startY = settings.y,
                    div;

                container.drawMask = function() {
                    canvas.width = settings.maskImage.width;
                    canvas.height = settings.maskImage.height;
                    context.save();
                    context.beginPath();
                    context.globalCompositeOperation = "source-over";
                    // draw the masked image after scaling
                    context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
                    context.restore()
                };

                container.drawImage = function() {

                    const img = settings.image

                    settings.x = (canvas.width - (img.width * settings.scale)) / 2
                    settings.y = (canvas.height - (img.height * settings.scale)) / 2

                    context.globalCompositeOperation = 'source-atop';
                    context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                    initImage = false;
                }

                // change the draggable image

                container.loadImage = function(imageUrl) {

                    settings.y = startY;
                    settings.x = startX;
                    prevX = prevY = 0;

                    initImage = true;

                    settings.image.src = imageUrl; // CHANGED

                    // sirpepole Add this
                    return settings.id;
                };

                container.loadMaskImage = function(imageUrl, from) {
                    canvas = document.createElement("canvas");
                    context = canvas.getContext('2d');
                    canvas.setAttribute("draggable", "true");
                    canvas.setAttribute("id", settings.id);
                    // settings.maskImageUrl = imageUrl;
                    settings.maskImage.src = imageUrl // CHANGED

                    div = $("
", {
                        "class": "masked-img"
                    }).append(canvas);

                    // div.find("canvas").on('touchstart mousedown', function(event)
                    div.find("canvas").on('dragstart', function(event) {
                        if (event.handled === false) return;
                        event.handled = true;
                        container.onDragStart(event);
                    });

                    div.find("canvas").on('touchend mouseup', function(event) {
                        if (event.handled === false) return;
                        event.handled = true;
                        container.selected(event);
                    });

                    div.find("canvas").bind("dragover", container.onDragOver);

                    container.append(div);
                    if (settings.onMaskImageCreate)
                        settings.onMaskImageCreate(div);

                    // container.loadImage(settings.imageUrl);
                    // Moved this to the settings.maskImage.onload
                };
                container.loadMaskImage(settings.maskImageUrl);
                JQmasks.push({
                        item: container,
                        id: settings.id
                    })
                    // Edit image
                div.addClass('masked-img' + settings.id);
                div.attr('data-id', settings.id);
                // ends
                return container;
            };
        }(jQuery));

.container {
        background: silver;
        position: relative;
    }

    .container img {
        position: absolute;
        top: 0;
        bottom: 250px;
        left: 0;
        right: 0;
        margin: auto;
        z-index: 999;
    }

    .masked-img {
        overflow: hidden;
        position: relative;
    }

    <input id="fileup" name="fileup" type="file" style="display:none">

Hint :

if I replace "name": "car" by "name": "mask_something", then car image will display, but in that case, a small icon will display on the car, but I don't want that...

Body:
You trie to mask an image, but you are not loading the image because of your name.indexOf('mask_') if condition.

Therefore the car is not shown, because its name is masknot_. Because the image has no url nothing is shown. If you remove that if condition both images (car and icon) are shown, because your code says mask image with image2. But that is exactly what the mask function is for. To mask an image with another image.

So you could apply the if condition to the image that will be shown above the car to not show it if masknot_ is in the name. That is an option, but it is not recommended because a masking function should mask something.

Write a new function to display an image without applying a mask would be the best option.

Below is a working example of your code.

var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 612,
        "layers": [{
            "x": 160,
            "src": "ax0HVTs.png",
            "y": 91,
            "height": 296,
            "width": 429,
            "name": "mask_1"
        }, {
            "x": 25,
            "src": "iEA642D.jpg",
            "height": 324,
            "width": 471,
            "y": 22,
            "name": "car"
        }],
        "y": 0,
        "width": 612
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {

    // Upload image onclick mask image

    containerElement.click(function(e) {
        var res = e.target;
        target = res.id;
        if (e.target.getContext) {
            // click only inside Non Transparent part
            var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
            if (pixel[3] === 255) {
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        }
    });

    // Fetch mask images from json file - IGNORE this code

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                                y: (layer.y + y),
                                height,
                                width,
                                name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data) {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);
        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            }
            of arr) {

            //Get Height and width of mask image [ edit button ]
            var ImagePosition = arr;
            //code end

            var imageUrl1 = imageUrl;

            var mask = $(".container").mask({
                imageUrl: name.indexOf('mask_') !== -1 ? imageUrl1 : undefined,

                // Fetch Mask images
                maskImageUrl: 'http://i.imgur.com/' + src,
                // end

                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            // here
            table.push(mask);
            fileup.onchange = function() {

                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";

            };
            counter++;
        }
        return mask;
    }
    mask = json(jsonData);
}); // end of function

// Image code

(function($) {
    window.JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);

        // Create the image properties
        settings.maskImage = new Image
        settings.image  = new Image

        // set the cross-origin attributes
        settings.maskImage.setAttribute('crossOrigin', 'anonymous');
        settings.image.setAttribute('crossOrigin', 'anonymous');

        settings.maskImage.onload = function() {
            // once the mask is loaded, load the image
            container.loadImage(settings.imageUrl)
          container.drawMask()
        }

        settings.image.onload = function() {
            // once the image is loaded, render to canvas

            container.drawImage()
        }

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;

        container.drawMask = function() {
            if (!settings.maskImage) return true;
            canvas.width = settings.maskImage.width;
            canvas.height = settings.maskImage.height;
            context.save();
            context.beginPath();
            context.globalCompositeOperation = "source-over";
            // draw the masked image after scaling
            if (settings.maskImage) context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
            context.restore()
        };

        container.drawImage = function() {

            const img = settings.image

            settings.x = (canvas.width - (img.width * settings.scale)) / 2
            settings.y = (canvas.height - (img.height * settings.scale)) / 2

            context.globalCompositeOperation = 'source-atop';
            if (img) context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
          context.restore()
            initImage = false;
        }

        // change the draggable image

        container.loadImage = function(imageUrl) {
            if (!imageUrl) return true;
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;

            initImage = true;

            settings.image.src = imageUrl; // CHANGED

            // sirpepole Add this
            return settings.id;
        };

        container.loadMaskImage = function(imageUrl, from) {

            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            // settings.maskImageUrl = imageUrl;
            settings.maskImage.src = imageUrl // CHANGED

            div = $("<div/>", {
                "class": "masked-img"
            }).append(canvas);

            // div.find("canvas").on('touchstart mousedown', function(event)
            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);

            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);

            // container.loadImage(settings.imageUrl);
            // Moved this to the settings.maskImage.onload
        };
        if (settings.maskImageUrl) {
        container.loadMaskImage(settings.maskImageUrl);
        }
        JQmasks.push({
                item: container,
                id: settings.id
            })
            // Edit image
        div.addClass('masked-img' + settings.id);
        div.attr('data-id', settings.id);
        // ends
        return container;
    };
}(jQuery));


问:
how to fix "can't resolve rxkotlin" in android
I'm using room database and need to add rxKotlin to my project, so when I use this code:

```<code>`implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1'`
</code>```

I get this error:

```<code>`ERROR: Failed to resolve: io.reactivex.rxjava2:rxkotlin:2.0.1`
</code>```

how can I fix it?

答:
Here you can find the list of versions you can choose from:

https://mvnrepository.com/artifact/io.reactivex.rxjava2/rxkotlin

Body:
I'm using room database and need to add rxKotlin to my project, so when I use this code:

`implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1'`

I get this error:

`ERROR: Failed to resolve: io.reactivex.rxjava2:rxkotlin:2.0.1`

how can I fix it?


问:
Skip entity that exist in database
I have json data that I need to import in db.
I need to check two field values in database before persisting entity.
If they exist to skip them without throwing an error and if not to create just the one missing.

```<code>        $file = file_get_contents('file.json');
        $jsonData = json_decode($file, true);

        $check = $this->getMyRepository()->findOneBy([
                'first_name' => $firstName,
                'last_name' => $lastName
            ]);

        foreach ($jsonData as $data) {

            if ($check) {
                continue;
            } else {
                $new = new MyEntity();
                $new->setFirstName($data->getFirstName());
                $new->setLastName($data->getLastName());
                $this->em->persist($new);
            }
        }
    }
    $this->em->flush();
}
</code>```

The import is working but when I trigger an api it always import all values and it shouldn't as I mentioned.

答:
Please see the comments in the code to see what has changed and why

Basically you covert the json file to an Array, so you have to address $data as an array to get its values.

The code that checks if this person already exists should be inside the loop as you want to check each person as you process the set of people in the json file.

Now we know that your JSON File is really not helping and does not really deserve the name JSON.....

Example file

```<code>{ "John Doe": "John Doe", "Jane Doe": "Jane Doe" }
</code>```

The code would need to be

```<code>        $file = file_get_contents('file.json');
        $jsonData = json_decode($file, true);

        foreach ($jsonData as $data) {
             // Split the single field into Firstname and lastname
            $name = explode(' ', $data);

            $exists = $this->getMyRepository()->findOneBy([
                                'first_name' => $name[0],
                                'last_name' => $name[1]
                            ]);

            if ($exists) {
                // this person already in the database
                // thats cool, just dont try and insert them again
                continue;
            } else {

                // again in here you are getting data from an array
                // called `$data` and not an entity with getters and setters
                $new = new MyEntity();
                $new->setFirstName($name[0]);
                $new->setLastName($name[1]);
                $this->em->persist($new);
            }
        }
    }
    $this->em->flush();
}
</code>```

Big Warning This code relies on the JSON Data file ALWAYS having a first name and a lastname seperated by a space.  THIS IS A VERY A DANGEROUS THING TO RELY UPON

You should really go back to the person that created this JSON file and ask then to do it properly!!!

Title: Skip entity that exist in database

Body:
I have json data that I need to import in db.
I need to check two field values in database before persisting entity.
If they exist to skip them without throwing an error and if not to create just the one missing.

        $file = file_get_contents('file.json');
        $jsonData = json_decode($file, true);

        $check = $this->getMyRepository()->findOneBy([
                'first_name' => $firstName,
                'last_name' => $lastName
            ]);

        foreach ($jsonData as $data) {

            if ($check) {
                continue;
            } else {
                $new = new MyEntity();
                $new->setFirstName($data->getFirstName());
                $new->setLastName($data->getLastName());
                $this->em->persist($new);
            }
        }
    }
    $this->em->flush();
}

The import is working but when I trigger an api it always import all values and it shouldn't as I mentioned.

Body:
Please see the comments in the code to see what has changed and why

Basically you covert the json file to an Array, so you have to address $data as an array to get its values.

The code that checks if this person already exists should be inside the loop as you want to check each person as you process the set of people in the json file.

Now we know that your JSON File is really not helping and does not really deserve the name JSON.....

Example file

{ "John Doe": "John Doe", "Jane Doe": "Jane Doe" }

The code would need to be

        $file = file_get_contents('file.json');
        $jsonData = json_decode($file, true);

        foreach ($jsonData as $data) {
             // Split the single field into Firstname and lastname
            $name = explode(' ', $data);

            $exists = $this->getMyRepository()->findOneBy([
                                'first_name' => $name[0],
                                'last_name' => $name[1]
                            ]);

            if ($exists) {
                // this person already in the database
                // thats cool, just dont try and insert them again
                continue;
            } else {

                // again in here you are getting data from an array
                // called `$data` and not an entity with getters and setters
                $new = new MyEntity();
                $new->setFirstName($name[0]);
                $new->setLastName($name[1]);
                $this->em->persist($new);
            }
        }
    }
    $this->em->flush();
}

Big Warning This code relies on the JSON Data file ALWAYS having a first name and a lastname seperated by a space.  THIS IS A VERY A DANGEROUS THING TO RELY UPON

You should really go back to the person that created this JSON file and ask then to do it properly!!!


问:
How to implement the Debug trait for struct that has a trait object member?
My goal is printing the contents of struct that has trait object member but I can't find how to tell Rust compiler that the member also implements other traits like Display or Debug.

For example, in the following program, I want to print the structure of S2 (and S1 for comparison) but I get stuck in the implementation of fmt.

trait Tr {}

impl Tr for usize {}

impl Tr for String {}

#[derive(Debug)]
struct S1 {
    member: Box,
}

struct S2 {
    member: Box
,
}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        // ??
        Ok(())
    }
}

fn main() {
    let s1 = S1 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s1);

    let s2 = S2 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s2);
}
```

<p>My desired output of this program is</p>

<pre class="lang-none prettyprint-override"><code>S1 { member: "abc" }
S2 { member: "abc" }
</code>```

Is it possible to implement Debug for a struct like S2?

(Rust version: 1.35)

答:
You can make S2 generic but you don't need to specify that the type should also implement Debug right there. Instead, you can specify it in the impl:

```<code>struct S2<A: Tr> {
    member: Box<A>,
}

impl<A: Tr + std::fmt::Debug> std::fmt::Debug for S2<A> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)?;
        Ok(())
    }
}
</code>```

This way, S2 will implement Debug if the actual type does.

Body:
My goal is printing the contents of struct that has trait object member but I can't find how to tell Rust compiler that the member also implements other traits like Display or Debug.

For example, in the following program, I want to print the structure of S2 (and S1 for comparison) but I get stuck in the implementation of fmt.

trait Tr {}

impl Tr for usize {}

impl Tr for String {}

#[derive(Debug)]
struct S1 {
    member: Box,
}

struct S2 {
    member: Box
,
}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        // ??
        Ok(())
    }
}

fn main() {
    let s1 = S1 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s1);

    let s2 = S2 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s2);
}

My desired output of this program is

S1 { member: "abc" }
S2 { member: "abc" }

Is it possible to implement Debug for a struct like S2?

(Rust version: 1.35)

Body:
You can make S2 generic but you don't need to specify that the type should also implement Debug right there. Instead, you can specify it in the impl:

struct S2<A: Tr> {
    member: Box<A>,
}

impl<A: Tr + std::fmt::Debug> std::fmt::Debug for S2<A> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)?;
        Ok(())
    }
}

This way, S2 will implement Debug if the actual type does.


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
I think it's worth pointing out that the default constructor will only be created by the compiler if you provide no constructor whatsoever.  That means if you only provide one constructor that takes an argument, the compiler will not create the default no-arg constructor for you.

The zeroing-out behavior that your book talks about is probably specific to a particular compiler.  I've always assumed that it can vary and that you should explicitly initialize any data members.

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bill the Lizard


问:
TFS REST API Get items that failed to build
Someone know the way to get projects that failed to build,
through the TFS REST API?</p>

答:
You can download the build logs with Build - Get Build Log Rest API. You need to know which log id is the build log (if you have few tasks so each task has a log), so you can  check all the available logs with Build - Get Build Logs Rest API, then iterate them and check the what is the build. after you have the log you can search and filter the errors.

A small example with PowerShell:

```<code>$collection = "http://tfs-server:8080/tfs/collection"
$project = "team-project"
$buildId = 10

#"api-version=4.1" is for TFS 2018, for other versions you need to change the number
$logsUrl = "$collection/$project/_apis/build/builds/$buildId/lgos?api-version=4.1"
$logs = Invoke-RestMethod -Uri $logsUrl -Method Get -UseDeafultCredntials -ContentType application/json

$buildLog = ""
ForEach($log in $logs.value)
{
    $urlLog = "$collection/$project/_apis/build/builds/$buildId/logs/$($log.id)?api-version=4.1"
    $logDetails = Invoke-RestMethod -Uri $urlLog -Method Get -UseDefaultCredntials -ContentType application/json
    if($logDetails.Contains("msbuild"))
    {
         $buildLog = $logDetails
         break
    }
}
# Now you have the logs in your hand and you can find in which projects have errors
</code>```

If you want to do it with C# you can call the Rest API with HttpClient:

```<code>using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDeafultCredntials = true } )
{
     string url = "the-url-from-above-powershell-script";
     var method = new HttpMethod("GET");
     var reqeust = new HttpRequestMessage(mehtod,url);
     var result = await client.SendAsync(rqeuest);
}
// In this way you get the Rest API response, so you need to it once for the logs, iterate them to get each log and then filter the errors.
</code>```

Body:
You can download the build logs with Build - Get Build Log Rest API. You need to know which log id is the build log (if you have few tasks so each task has a log), so you can  check all the available logs with Build - Get Build Logs Rest API, then iterate them and check the what is the build. after you have the log you can search and filter the errors.

A small example with PowerShell:

$collection = "http://tfs-server:8080/tfs/collection"
$project = "team-project"
$buildId = 10

#"api-version=4.1" is for TFS 2018, for other versions you need to change the number
$logsUrl = "$collection/$project/_apis/build/builds/$buildId/lgos?api-version=4.1"
$logs = Invoke-RestMethod -Uri $logsUrl -Method Get -UseDeafultCredntials -ContentType application/json

$buildLog = ""
ForEach($log in $logs.value)
{
    $urlLog = "$collection/$project/_apis/build/builds/$buildId/logs/$($log.id)?api-version=4.1"
    $logDetails = Invoke-RestMethod -Uri $urlLog -Method Get -UseDefaultCredntials -ContentType application/json
    if($logDetails.Contains("msbuild"))
    {
         $buildLog = $logDetails
         break
    }
}
# Now you have the logs in your hand and you can find in which projects have errors

If you want to do it with C# you can call the Rest API with HttpClient:

using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDeafultCredntials = true } )
{
     string url = "the-url-from-above-powershell-script";
     var method = new HttpMethod("GET");
     var reqeust = new HttpRequestMessage(mehtod,url);
     var result = await client.SendAsync(rqeuest);
}
// In this way you get the Rest API response, so you need to it once for the logs, iterate them to get each log and then filter the errors.


问:
Regular expression help - comma delimited string
I don't write many regular expressions so I'm going to need some help on the one.

I need a regular expression that can validate that a string is an alphanumeric comma delimited string.

Examples:

123, 4A67, GGG, 767 would be valid.

12333, 78787&*, GH778 would be invalid

fghkjhfdg8797< would be invalid

This is what I have so far, but isn't quite right: ^(?=.*[a-zA-Z0-9][,]).*$

Any suggestions?

答:
Try the following expression:

/^([a-z0-9\s]+,)*([a-z0-9\s]+){1}$/i

This will work for:

test

test, test

test123,Test 123,test

I would strongly suggest trimming the whitespaces at the beginning and end of each item in the comma-separated list.


问:
Filter 2 arrays with object in php
I write a reservation system for rooms in a hotel.
I have one table in the database with all the rooms in the hotel (rooms). The next table is reservations. I need to write a function to which I will be given a date, start and end time of the reservation, and that this function would return all free rooms to me within the given time limit. I do not know how to bite it completely. Could someone guide me?

I was thinking about get all the rooms, then all the reservations, with the shipment to the function date, but what next? How to arrange it all?

@edit

Rooms table:

```<code>- id
- number
</code>```

Reservation table:

```<code>- id
- room_id
- date
- time_start
- time_finish
</code>```

答:
You can do something like this:

```<code>select rooms.* from rooms
left join reservations
on rooms.id = reservations.room_id
and reservations.date = '2019-05-28' and reservations.time_start < '14:00' and reservations.time_finish > '14:00'
where reservations.id is null
</code>```

If the test schema is like:

```<code>SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

CREATE TABLE `reservations` (
  `id` int(11) NOT NULL,
  `room_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `time_start` time NOT NULL,
  `time_finish` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `reservations` (`id`, `room_id`, `date`, `time_start`, `time_finish`) VALUES
(0, 2,  '2019-05-28',   '13:00:00', '16:00:00');

CREATE TABLE `rooms` (
  `id` int(11) NOT NULL,
  `name` varchar(15) NOT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `rooms` (`id`, `name`) VALUES
(1, 'room1'),
(2, 'room2');
</code>```

Fiddle example:

http://sqlfiddle.com/#!9/f82a5c/1

Title: Filter 2 arrays with object in php

Body:
I write a reservation system for rooms in a hotel.
I have one table in the database with all the rooms in the hotel (rooms). The next table is reservations. I need to write a function to which I will be given a date, start and end time of the reservation, and that this function would return all free rooms to me within the given time limit. I do not know how to bite it completely. Could someone guide me?

I was thinking about get all the rooms, then all the reservations, with the shipment to the function date, but what next? How to arrange it all?

@edit

Rooms table:

- id
- number

Reservation table:

- id
- room_id
- date
- time_start
- time_finish

Body:
You can do something like this:

select rooms.* from rooms
left join reservations
on rooms.id = reservations.room_id
and reservations.date = '2019-05-28' and reservations.time_start < '14:00' and reservations.time_finish > '14:00'
where reservations.id is null

If the test schema is like:

SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

CREATE TABLE `reservations` (
  `id` int(11) NOT NULL,
  `room_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `time_start` time NOT NULL,
  `time_finish` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `reservations` (`id`, `room_id`, `date`, `time_start`, `time_finish`) VALUES
(0, 2,  '2019-05-28',   '13:00:00', '16:00:00');

CREATE TABLE `rooms` (
  `id` int(11) NOT NULL,
  `name` varchar(15) NOT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `rooms` (`id`, `name`) VALUES
(1, 'room1'),
(2, 'room2');

Fiddle example:

http://sqlfiddle.com/#!9/f82a5c/1