问:
HTMLElement.innerHTML adding attributes to  closing tag, and I don't know why
I am using Angular 13 with a pipe to reformat text in a contenteditable div. Everything is working fine until the innerHtml is replaced with the new code. The attributes from the last child node (a span tag) are appended to the inside of the closing span tag. I have no idea why this is happening.

I'm using TypeScript, with Angular 13, on Chromium (MS Edge) v97.0.1072.76 and Firefox v95.0.

Here's an example:

```<code>reformatContent(event: Event) {
const el = (event.target as HTMLElement);

const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text <span id="someTextId" class="someTextClass">More Text</span>

const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- this is ok, what I expected.

el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span id="someTextId" class="someTextClass someNewClass"> <-- why is this happening???
}
</code>```

I just want to be clear that the originalHtml includes the close  tag. So I don't think the browser is trying to close the tag.

Edit for typo.

Edit 2:
I updated the original code for typos and to make it more clear how I was getting the innerHTML. I didn't think that was where the problem was, but apparently that's it, because this works:

```<code>reformatContent(event: Event) {
const e = (event.target as HTMLElement);
const el = document.getElementById(e.id);

const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text <span id="someTextId" class="someTextClass">More Text</span>

const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- this is ok, what I expected.

el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- now it works
}
</code>```

I don't understand why the original way of getting the element caused this problem. I fixed it, but I'd really like to understand what's happening here.

答:
What is reformatText function?

```<code>this.reformatText(originalHtml)
</code>```

This function is changing your span and your bug is from here.

You might say that your result are right but you are using console.log on an invalid variable (originalHtml)

What is and where is originalHtml?

But generally what I know, your problem is because of this line:

```<code>const newHtml = this.reformatText(originalHtml);
</code>```

Title: HTMLElement.innerHTML adding attributes to </span> closing tag, and I don't know why

Body:
I am using Angular 13 with a pipe to reformat text in a contenteditable div. Everything is working fine until the innerHtml is replaced with the new code. The attributes from the last child node (a span tag) are appended to the inside of the closing span tag. I have no idea why this is happening.

I'm using TypeScript, with Angular 13, on Chromium (MS Edge) v97.0.1072.76 and Firefox v95.0.

Here's an example:

reformatContent(event: Event) {
const el = (event.target as HTMLElement);

const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text More Text

const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text More Text <-- this is ok, what I expected.

el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text More Text <-- why is this happening???
}

I just want to be clear that the originalHtml includes the close  tag. So I don't think the browser is trying to close the tag.

Edit for typo.

Edit 2:
I updated the original code for typos and to make it more clear how I was getting the innerHTML. I didn't think that was where the problem was, but apparently that's it, because this works:

reformatContent(event: Event) {
const e = (event.target as HTMLElement);
const el = document.getElementById(e.id);

const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text More Text

const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text More Text <-- this is ok, what I expected.

el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text More Text <-- now it works
}

I don't understand why the original way of getting the element caused this problem. I fixed it, but I'd really like to understand what's happening here.

Body:
What is reformatText function?

this.reformatText(originalHtml)

This function is changing your span and your bug is from here.

You might say that your result are right but you are using console.log on an invalid variable (originalHtml)

What is and where is originalHtml?

But generally what I know, your problem is because of this line:

const newHtml = this.reformatText(originalHtml);


来源: stackexchange

问:
Why does DEBUG=False setting make my django Static Files Access fail?
Am building an app using Django as my workhorse. All has been well so far - specified db settings, configured static directories, urls, views etc. But trouble started sneaking in the moment I wanted to render my own beautiful and custom 404.html and 500.html pages.

I read the docs on custom error handling, and set necessary configurations in UrlsConf, created corresponding views and added the 404.html and the 500.html to my app's template directory (specified in the settings.py too).

But the docs say you can actually view custom error views until Debug is Off, so I did turn it off to test my stuff, and that's when stuff goes berserk!

Not only do I fail to view the custom 404.html (actually, it loads, but because my error pages each contain a graphic error message -as some nice image), the source of the error page loads, but nothing else loads! Not even linked CSS or Javascript!

Generally, once I set DEBUG = False, all views will load, but any linked content (CSS, Javascript, Images, etc) wont load! What's happening? Is there something am missing, concerning static files and the DEBUG setting?

答:
From here I took help by mixing a few answers. Here, I am adding my whole parts. [I am doing this for a beginners help and for my future use as well]

Well at first the question is why Debug=False needed!
I put my project in AWS and it was being connection timeout after few hours because of memory leaking.
At first I thought for celery. [of course I am just a beginner]
Then I put DEBUG=False from DEBUG=True As we can see the security warning in settings.py

```<code># SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
</code>```

Once I did that my staticfiles were not loading successfully in webpages.
Then I searched everywhere and at first tried from here the --insecure command to runserver.

```<code>python manage.py runserver --insecure
</code>```

Which is successful but I don't want the insecure mode in my project when it is in production.
And as the proper solution [according to me] I followed the steps below.

At first, I correct the static URL,root, and dir in settings.py

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
</code>```

Then collect the static files by command

```<code>python manage.py collectstatic
</code>```

Now the second step, [which also provided here]
At first install whitenoise in your project directory in the command line

```<code>pip install whitenoise
</code>```

Then Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.

This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-

```<code>MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #after this line
    'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
    'django.contrib.sessions.middleware.SessionMiddleware', #before this
    '...'
]
</code>```

Add 'whitenoise.runserver_nostatic' on top of your installed apps So that your installed apps list will look like this:-

```<code>INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    '...'
]
</code>```

Done, you will be able to serve static files in production now!! [I did on my local environment as well]

Just use the runserver command as always no insecure or anything needed.

```<code>python manage.py runserver
</code>```

Boom!!! It's working for me.
Hahaha. I know kinda childish nature but I am so happy now.

Thanks to everyone who provided answers here and help my work.

ContentLicense: CC BY-SA 4.0

Body:
From here I took help by mixing a few answers. Here, I am adding my whole parts. [I am doing this for a beginners help and for my future use as well]

Well at first the question is why Debug=False needed!
I put my project in AWS and it was being connection timeout after few hours because of memory leaking.
At first I thought for celery. [of course I am just a beginner]
Then I put DEBUG=False from DEBUG=True As we can see the security warning in settings.py

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

Once I did that my staticfiles were not loading successfully in webpages.
Then I searched everywhere and at first tried from here the --insecure command to runserver.

python manage.py runserver --insecure

Which is successful but I don't want the insecure mode in my project when it is in production.
And as the proper solution [according to me] I followed the steps below.

At first, I correct the static URL,root, and dir in settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Then collect the static files by command

python manage.py collectstatic

Now the second step, [which also provided here]
At first install whitenoise in your project directory in the command line

pip install whitenoise

Then Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.

This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #after this line
    'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
    'django.contrib.sessions.middleware.SessionMiddleware', #before this
    '...'
]

Add 'whitenoise.runserver_nostatic' on top of your installed apps So that your installed apps list will look like this:-

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    '...'
]

Done, you will be able to serve static files in production now!! [I did on my local environment as well]

Just use the runserver command as always no insecure or anything needed.

python manage.py runserver

Boom!!! It's working for me.
Hahaha. I know kinda childish nature but I am so happy now.

Thanks to everyone who provided answers here and help my work.


问:
Grails Connections behaving very differently in Integration test
We have a custom data source that extends BasicDataSource.  We have overridden the getConnection method which does a couple things inside of it.  When we run the webapp outside of testing, when we call a service from a controller it will grab a new connection and use that connection until the service is done.  All is well.  However, inside an integration test, the connection appears to be grabbed before the test even calls the controller.  Flow below

Regular Run:
call controller -> controller calls service method ->  connection is grabbed -> service method is run and returns to controller

Integration Test:
connection is grabbed -> call controller from test -> controller calls service method ->  service method is run and returns to controller

Needless to say, this is giving us problems as having the correct connection is very important for our app.  Thoughts?

Edit:  Still getting significant issues with this.  We've reached a point where we have to avoid creating integration tests, or do some manual connection switching (which defeats half the point of the tests)

DataSource.groovy

```<code>dataSource {
pooled = true
dialect="org.hibernate.dialect.OracleDialect"
properties {
    maxActive = 50
    maxIdle = 10
    initialSize = 10
    minEvictableIdleTimeMillis = 1800000
    timeBetweenEvictionRunsMillis = 1800000
    maxWait = 10000
    testWhileIdle = true
    numTestsPerEvictionRun = 3
    testOnBorrow = true
}

}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}
</code>```

答:
This is not a final Answer, however I believe this is an explanation of what is going on:

Running as Web app: your Service class has a transactionManager which has a sessionFactory, which gets the connection! So in this case, assuming that you Service is 'transactional=true' all methods that you call in your services will have a 'Session.beginTransaction()' in the beginning of the method(there is a Grails`s Proxy to do that, when you set 'transactional=true'), which will call all that stack until getConnection().

Running as Integration Test: as Grails doesnt commit your DB changes, it always rollback them! I believe that when you are starting your Integration test, grails is creating a transaction right away! so it will be able to rollback it afterwards!(which make totally sense right!), you can confirm that taking a look at the class org.codehaus.groovy.grails.test.support.GrailsTestInterceptor. The method init() is called before your services in your integration test. So that`s why getConnection() is being called before everything!

Suggestion:
You can try setting your integration test class as 'transaction=false' and see if getConnection() doesn't get call in the beginning!
Go to Transactions section in here to see more!
Just dont forget that in your test you will have to rollback your transaction! if your set transaction=false.

ContentLicense: CC BY-SA 3.0

Body:
We have a custom data source that extends BasicDataSource.  We have overridden the getConnection method which does a couple things inside of it.  When we run the webapp outside of testing, when we call a service from a controller it will grab a new connection and use that connection until the service is done.  All is well.  However, inside an integration test, the connection appears to be grabbed before the test even calls the controller.  Flow below

Regular Run:
call controller -> controller calls service method ->  connection is grabbed -> service method is run and returns to controller

Integration Test:
connection is grabbed -> call controller from test -> controller calls service method ->  service method is run and returns to controller

Needless to say, this is giving us problems as having the correct connection is very important for our app.  Thoughts?

Edit:  Still getting significant issues with this.  We've reached a point where we have to avoid creating integration tests, or do some manual connection switching (which defeats half the point of the tests)

DataSource.groovy

dataSource {
pooled = true
dialect="org.hibernate.dialect.OracleDialect"
properties {
    maxActive = 50
    maxIdle = 10
    initialSize = 10
    minEvictableIdleTimeMillis = 1800000
    timeBetweenEvictionRunsMillis = 1800000
    maxWait = 10000
    testWhileIdle = true
    numTestsPerEvictionRun = 3
    testOnBorrow = true
}

}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}


问:
How to execute Javascript in browser with Python Selenium and record output
I am inquiring about executing javascript in the browser with selenium. I've seen plenty of ways how to do this, however, saving the output to a variable seems to be something else.

```<code>r = driver.execute_script("`; ${document.cookie}`.split(`; bearer_token=`).pop().split(';').shift()")
</code>```

This makes R = None, which is not the output of the code.

答: execute_script() function in the selenium works for executing something particularly in the specific browser tab only, I am sure that the outputs won't be stored in a python variable. Instead I recommend to save the cookies in your local dir and later perform your tasks.

Body:
I am inquiring about executing javascript in the browser with selenium. I've seen plenty of ways how to do this, however, saving the output to a variable seems to be something else.

r = driver.execute_script("`; ${document.cookie}`.split(`; bearer_token=`).pop().split(';').shift()")

This makes R = None, which is not the output of the code.


问:
How to delete all duplicate records from SQL Table?
Hello I have table name FriendsData that contains duplicate records as shown below

```<code>fID UserID  FriendsID       IsSpecial      CreatedBy
-----------------------------------------------------------------
1   10         11            FALSE            1
2   11          5            FALSE            1
3   10         11            FALSE            1
4    5         25            FALSE            1
5   10         11            FALSE            1
6   12         11            FALSE            1
7   11          5            FALSE            1
8   10         11            FALSE            1
9   12         11            FALSE            1
</code>```

I want to remove duplicate combinations rows using MS SQL?

Remove latest duplicate records from MS SQL FriendsData table.
here I attached image which highlights duplicate column combinations.

How I can removed all duplicate combinations from SQL table?

答:
Works in Postgres:</p>
```<code>DELETE from "FriendsData" where "fID" in
   (SELECT "fID" from
        (SELECT *, ROW_NUMBER() OVER(PARTITION BY "UserID", "FriendsID" ORDER BY  "fID") as rn
    FROM "FriendsData") as inner1
WHERE rn > 1);
</code>```

Body:
Hello I have table name FriendsData that contains duplicate records as shown below

fID UserID  FriendsID       IsSpecial      CreatedBy
-----------------------------------------------------------------
1   10         11            FALSE            1
2   11          5            FALSE            1
3   10         11            FALSE            1
4    5         25            FALSE            1
5   10         11            FALSE            1
6   12         11            FALSE            1
7   11          5            FALSE            1
8   10         11            FALSE            1
9   12         11            FALSE            1

I want to remove duplicate combinations rows using MS SQL?

Remove latest duplicate records from MS SQL FriendsData table.
here I attached image which highlights duplicate column combinations.

How I can removed all duplicate combinations from SQL table?

Body:
Works in Postgres:

DELETE from "FriendsData" where "fID" in
   (SELECT "fID" from
        (SELECT *, ROW_NUMBER() OVER(PARTITION BY "UserID", "FriendsID" ORDER BY  "fID") as rn
    FROM "FriendsData") as inner1
WHERE rn > 1);


问:
Laravel 8 - Get Data One to Many Relation
I Have Problem with get data

This is my code
Controller

```<code>$class = DetailMentor::with('Kelas')->where('id', Auth::user()->id)->get();
</code>```

Model:

```<code>
    protected $primaryKey = 'id_mentor';

    protected $fillable = [
        'id',
        'id_kelas',
    ];

    public $timestamps = true;

    public function Kelas()
    {
        return $this->hasMany(Kelas::class, 'id_kelas','id_kelas');
    }

    public function User()
    {
        return $this->belongsTo(User::class, 'id','id');
</code>```

View index

```<code> <tbody>

 @forelse ($class->Kelas as $item)
 <tr role="row" class="odd">
   <th scope="row" class="small" class="sorting_1">{{ $loop->iteration}}.</th>
   <td>{{ $item->nama_kelas }}</td>
   <td>{{ $item->Jeniskelas->jenis_kelas }}</td>
   <td>{{ $item->level->nama_level }}</td>
   <td class="text-center">
       @if ($item->status_video == 'Telah Dibuat')
          <span class="badge badge-success ">Telah Dibuat</span>
       @else
          <span class="badge badge-danger">Belum Dibuat</span>
       @endif
   </td>
   </tr>
 @empty

 @endforelse

</tbody>
</code>```

Error:
Property [Kelas] does not exist on this collection instance. (View: C:\laragon\www\Bootcamp\resources\views\mentor\listkelas\index.blade.php)

I want to group data kelas by id. If i use first it only takes one data, If i use get it say error. Can someone Helpme, Please! I'm new to this

[Picture: Array Return $class][1]
[1]: https://i.stack.imgur.com/0fjIj.png

答:
the first ensure if the data get correctly test it on postman or on browser you can use method dd()
so if the data come correct

the problem in view index.blade.php

I think it works on first method because you get one object (one record)

and it doesn't work for get method because it gets array of object so the way of display this array it is different from the one object

ensure the way of display it and use foreach in index.blade.php

hopefully that is help you

update:

```<code>        @foreach ($class as $item)
         <tr role="row" class="odd">
         <th scope="row" class="small" class="sorting_1">{{ $loop->iteration}}.</th>
         <td>{{ $item->kelas[0]->nama_kelas }}</td>
         <td>{{ $item->kelas[0]->Jeniskelas->jenis_kelas }}</td>
         <td class="text-center">
       @if ($item->kelas[0]->status_video == 'Telah Dibuat')
          <span class="badge badge-success ">Telah Dibuat</span>
       @else
          <span class="badge badge-danger">Belum Dibuat</span>
       @endif
   </td>
   </tr>

     @empty

     @endforeach
</code>```

you can access like this $item->kelas[0]->nama_kelas

Body:
I Have Problem with get data

This is my code
Controller

$class = DetailMentor::with('Kelas')->where('id', Auth::user()->id)->get();

Model:

    protected $primaryKey = 'id_mentor';

    protected $fillable = [
        'id',
        'id_kelas',
    ];

    public $timestamps = true;

    public function Kelas()
    {
        return $this->hasMany(Kelas::class, 'id_kelas','id_kelas');
    }

    public function User()
    {
        return $this->belongsTo(User::class, 'id','id');

View index

 @forelse ($class->Kelas as $item)

   {{ $loop->iteration}}.
   {{ $item->nama_kelas }}
   {{ $item->Jeniskelas->jenis_kelas }}
   {{ $item->level->nama_level }}

       @if ($item->status_video == 'Telah Dibuat')
          Telah Dibuat
       @else
          Belum Dibuat
       @endif

 @empty

 @endforelse

Error:
Property [Kelas] does not exist on this collection instance. (View: C:\laragon\www\Bootcamp\resources\views\mentor\listkelas\index.blade.php)

I want to group data kelas by id. If i use first it only takes one data, If i use get it say error. Can someone Helpme, Please! I'm new to this

[Picture: Array Return $class][1]
[1]: https://i.stack.imgur.com/0fjIj.png

Body:
the first ensure if the data get correctly test it on postman or on browser you can use method dd()
so if the data come correct

the problem in view index.blade.php

I think it works on first method because you get one object (one record)

and it doesn't work for get method because it gets array of object so the way of display this array it is different from the one object

ensure the way of display it and use foreach in index.blade.php

hopefully that is help you

update:

        @foreach ($class as $item)
         <tr role="row" class="odd">
         <th scope="row" class="small" class="sorting_1">{{ $loop->iteration}}.</th>
         <td>{{ $item->kelas[0]->nama_kelas }}</td>
         <td>{{ $item->kelas[0]->Jeniskelas->jenis_kelas }}</td>
         <td class="text-center">
       @if ($item->kelas[0]->status_video == 'Telah Dibuat')
          <span class="badge badge-success ">Telah Dibuat</span>
       @else
          <span class="badge badge-danger">Belum Dibuat</span>
       @endif
   </td>
   </tr>

     @empty

     @endforeach

you can access like this $item->kelas[0]->nama_kelas


问:
Search multiple column values with one search string
I have this query where I want to return results if the search string provided yields data from the 'FirstName' and 'LastName' column of my database. They each work individually as I can get results for Firstname = 'john' and LastName = 'doe'. I also want to be able to pass in a search string of 'John doe' and get results. How would I implement this using .net/linq

snippet:
var query = _context.Players.Where(p => p.Firstname.Contains(searchString.ToLower().Trim()) || p.Lastname.Contains(searchString.ToLower().Trim()));

答:
Separating the input data is also convenient</p>
```<code>  var parts = searchString.Split();
    var partOne = parts[0].ToLower().Trim();
    var partTwo = parts[1].ToLower().Trim()

    var query = _context.Players.Where(
         p => p.Firstname.Contains(partOne)
           || p.Lastname.Contains(partTwo));
</code>```

Body:
Separating the input data is also convenient

  var parts = searchString.Split();
    var partOne = parts[0].ToLower().Trim();
    var partTwo = parts[1].ToLower().Trim()

    var query = _context.Players.Where(
         p => p.Firstname.Contains(partOne)
           || p.Lastname.Contains(partTwo));


问:
How to add a constraint (which is not implemented) to a form?
On some browsers, inputs like date, time, datetime-local, number are not implemented and are considered as text inputs.

I made these RegExp to check these input values :

```<code>const RegExpYear = '(000[1-9]|00[1-9]\\d|0[1-9]\\d\\d|100\\d|10[1-9]\\d|1[1-9]\\d{2}|[2-9]\\d{3}|[1-9]\\d{4}|1\\d{5}|2[0-6]\\d{4}|27[0-4]\\d{3}|275[0-6]\\d{2}|2757[0-5]\\d|275760)',
      RegExpMonth ='(0[1-9]|1[012])',
      RegExpDay = '(0[1-9]|[12]\\d|3[01])',
      RegExpHour = '(0\\d|1\\d|2[0-4])',
      RegExpMinSec = '(0\\d|[1-5]\\d)',
      RegExpMilli = '(00\\d|0[1-9]\\d|[1-9]\\d{2})',
      patternWeek = new RegExp('^'+RegExpYear+'-W(([1-4][0-9])|(5[0-3])|0[1-9])$'),
      patternMonth = new RegExp('^'+RegExpYear + '-' + RegExpMonth + '$'),
      patternDateTimeLocal = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + 'T' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'),
      patternDate = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + '$'),
      patternTime = new RegExp('^' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'),
      patternNumber = new RegExp('^-?\d+\.?(\d+)?([eE][+-]?\d+)?$');

document.querySelectorAll('[type=datetime-local], [type=date], [type=time], [type=month], [type=week], [type=number]').forEach(function(a){
  let type = a.type,
      attrtype = a.attributes.getNamedItem('type').value,
      pattern;

  if (type !== attrtype) {

    switch(attrtype) {
      case 'number' : pattern = patternNumber; break;
      case 'week' : pattern = patternWeek; break;
      case 'month' : pattern = patternMonth; break;
      case 'datetime-local' : pattern = patternDateTimeLocal; break;
      case 'date' : pattern = patternDate; break;
      case 'time' : pattern = patternTime; break;
    }

    a.addEventListener('input',function(e){
      let test = pattern.test(this.value);

      if (test) {
        a.classList.add('valid')
        a.classList.remove('invalid')
      } else {
        a.classList.add('invalid')
        a.classList.remove('valid')
      }
    });
  }
});
</code>```

This way I can style the wrong entries but can't prevent form submit.

Is it possible to add a constraint that passes through the ValidityState property ?

答:
You won't have to revalidate all the inputs or prevent form submission inside onsubmit event handler, if you use the inbuilt DOM Constraint Validation API. Every input element validates itself and reports to form if it's valid or invalid. Special handling can be done inside onInput event handler.

Demo:

const fruitRegx = "(?!\s*[Mm]ango).*" // we don't want mango

// set patterns on all required input elements
let inpt = document.getElementById('choose');
inpt.setAttribute("pattern", fruitRegx);

// set input handlers
inpt.addEventListener('input', function(e) {
  if (inpt.validity.patternMismatch) {
    inpt.setCustomValidity("I said no mango!!");
    // if pattern doesn't mismatch report it
    // rest is taken care of automatically
    inpt.reportValidity();
  } else {
    inpt.setCustomValidity("");
  }
});

// this one has no pattern assigned, so doing validation manually
choose2.addEventListener('input', function(e) {
  let val = e.target.value;

  if (val.includes("banana")) {
    e.target.setCustomValidity("How dare you!!");
    e.target.reportValidity();
  } else {
    e.target.setCustomValidity("");
  }
});

function send(event) {
  // mimicking form submit
  output.innerHTML += `Requesting ${choose.value} and ${choose2.value}...<br>`;

  // just for the demo preventing form submission
  event.preventDefault();
  return false;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input:invalid {
  background-color: rgb(255, 196, 196);
}

input:valid {
  background-color: lightgreen;
}</code>```

<form onsubmit="send(event)" target="_self">
  What fruit would you prefer? Except mango!

  <input id="choose" required>

  This one doesn't have pattern validation. But don't enter 'banana'!

  <input id="choose2" required>

  <button>Submit</button>

```
</form></code>```

If you type 'mango' in above demo, send method doesn't get called.
Also note how the <input> automatically gets :valid and :invalid CSS pseudo classes. So the styling is taken care of automatically.

If you are looking for solution to prevent form submission then above demo is already doing it. Fore more refer https://stackoverflow.com/a/8664680/15273968

Body:
On some browsers, inputs like date, time, datetime-local, number are not implemented and are considered as text inputs.

I made these RegExp to check these input values :

const RegExpYear = '(000[1-9]|00[1-9]\\d|0[1-9]\\d\\d|100\\d|10[1-9]\\d|1[1-9]\\d{2}|[2-9]\\d{3}|[1-9]\\d{4}|1\\d{5}|2[0-6]\\d{4}|27[0-4]\\d{3}|275[0-6]\\d{2}|2757[0-5]\\d|275760)',
      RegExpMonth ='(0[1-9]|1[012])',
      RegExpDay = '(0[1-9]|[12]\\d|3[01])',
      RegExpHour = '(0\\d|1\\d|2[0-4])',
      RegExpMinSec = '(0\\d|[1-5]\\d)',
      RegExpMilli = '(00\\d|0[1-9]\\d|[1-9]\\d{2})',
      patternWeek = new RegExp('^'+RegExpYear+'-W(([1-4][0-9])|(5[0-3])|0[1-9])$'),
      patternMonth = new RegExp('^'+RegExpYear + '-' + RegExpMonth + '$'),
      patternDateTimeLocal = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + 'T' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'),
      patternDate = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + '$'),
      patternTime = new RegExp('^' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'),
      patternNumber = new RegExp('^-?\d+\.?(\d+)?([eE][+-]?\d+)?$');

document.querySelectorAll('[type=datetime-local], [type=date], [type=time], [type=month], [type=week], [type=number]').forEach(function(a){
  let type = a.type,
      attrtype = a.attributes.getNamedItem('type').value,
      pattern;

  if (type !== attrtype) {

    switch(attrtype) {
      case 'number' : pattern = patternNumber; break;
      case 'week' : pattern = patternWeek; break;
      case 'month' : pattern = patternMonth; break;
      case 'datetime-local' : pattern = patternDateTimeLocal; break;
      case 'date' : pattern = patternDate; break;
      case 'time' : pattern = patternTime; break;
    }

    a.addEventListener('input',function(e){
      let test = pattern.test(this.value);

      if (test) {
        a.classList.add('valid')
        a.classList.remove('invalid')
      } else {
        a.classList.add('invalid')
        a.classList.remove('valid')
      }
    });
  }
});

This way I can style the wrong entries but can't prevent form submit.

Is it possible to add a constraint that passes through the ValidityState property ?

Body:
You won't have to revalidate all the inputs or prevent form submission inside onsubmit event handler, if you use the inbuilt DOM Constraint Validation API. Every input element validates itself and reports to form if it's valid or invalid. Special handling can be done inside onInput event handler.

Demo:

const fruitRegx = "(?!\s*[Mm]ango).*" // we don't want mango

// set patterns on all required input elements
let inpt = document.getElementById('choose');
inpt.setAttribute("pattern", fruitRegx);

// set input handlers
inpt.addEventListener('input', function(e) {
  if (inpt.validity.patternMismatch) {
    inpt.setCustomValidity("I said no mango!!");
    // if pattern doesn't mismatch report it
    // rest is taken care of automatically
    inpt.reportValidity();
  } else {
    inpt.setCustomValidity("");
  }
});

// this one has no pattern assigned, so doing validation manually
choose2.addEventListener('input', function(e) {
  let val = e.target.value;

  if (val.includes("banana")) {
    e.target.setCustomValidity("How dare you!!");
    e.target.reportValidity();
  } else {
    e.target.setCustomValidity("");
  }
});

function send(event) {
  // mimicking form submit
  output.innerHTML += `Requesting ${choose.value} and ${choose2.value}...<br>`;

  // just for the demo preventing form submission
  event.preventDefault();
  return false;
}

input:invalid {
  background-color: rgb(255, 196, 196);
}

input:valid {
  background-color: lightgreen;
}

<form onsubmit="send(event)" target="_self">
  <label for="choose">What fruit would you prefer? Except mango!</label><br>
  <input id="choose" required><br><br>
  <label for="choose">This one doesn't have pattern validation. But don't enter 'banana'!</label><br>
  <input id="choose2" required><br><br>
  <button>Submit</button>
  <pre id=output></pre>
</form>

If you type 'mango' in above demo, send method doesn't get called.
Also note how the <input> automatically gets :valid and :invalid CSS pseudo classes. So the styling is taken care of automatically.

If you are looking for solution to prevent form submission then above demo is already doing it. Fore more refer https://stackoverflow.com/a/8664680/15273968


问:
Launching Spring batch job
I have a problem where in I need to receive a series of messages from an MQ queue and write this to a file and initiate a spring batch job with the file as input. Right now I'm thinking of launching the job with wired @Autowired JobLauncher jobLauncher and  @Autowired Job job; from the MDB itself.But I feel this is not a good approach as spring batch may create a series of threads and EJB as such doesnt support multi threading.

Is there any other effective way to do this ?  I dont want to use quartz scheduler or anything else since it adds complexity. Is there any interface in spring batch itself which launches a job soon after a file comes in a directory ? Any leads in doing this better would be appreciated.

Thanks.

答:
I'm not sure I understand why you have a message queue, a message-driven POJO/EJB, AND a batch job.

One way to do it is to have the message driven POJO/EJB do the work.  It's already an asynch process.  You can pool the message driven beans so there are sufficient workers to handle the load.  Why add complexity?

If you'd rather not do that, forget the queue and use Spring Batch on its own.  I wouldn't do both.

Title: Launching Spring batch job


问:
How can I apply aggregate on array of objects?
I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.

Original Data

[
  {
    "_id": "61ff24b2db73094dd3029c7e",
    "TeamName": "GoodTeam",
    "TeamImage": "Avatar",
    "TeamMember": [
      {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ],
    "createdAt": "2022-02-06T01:30:26.893Z",
    "updatedAt": "2022-02-06T02:23:16.660Z",
    "__v": 0
  }
]
```
<p>Reconstruct Data</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "timezone":"PST",
    "TeamMember":[
       {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
  {
    "timezone":"AKST",
    "TeamMember":[
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ]
  }
]
</code>```

And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?

答:
It is better to do it in the backend and recommended.

You can achieve this by multiple ways in the backend using mongo aggregation framework. It is very powerful framework with multiple operators to handle these kind of data.

Body:
I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.

Original Data

[
  {
    "_id": "61ff24b2db73094dd3029c7e",
    "TeamName": "GoodTeam",
    "TeamImage": "Avatar",
    "TeamMember": [
      {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ],
    "createdAt": "2022-02-06T01:30:26.893Z",
    "updatedAt": "2022-02-06T02:23:16.660Z",
    "__v": 0
  }
]

Reconstruct Data

[
  {
    "timezone":"PST",
    "TeamMember":[
       {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
  {
    "timezone":"AKST",
    "TeamMember":[
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ]
  }
]

And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?


问:
etcd err: context deadline exceeded
When I use shell it returns ok,
but when I use golang it returns err: context deadline exceeded.

Why?

package main

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
    "time"
)
func main()  {
    cli,err := clientv3.New(clientv3.Config{
        Endpoints: []string{"http://192.168.11.34:2379"},
        DialTimeout: 5*time.Second,
    })
    if err != nil{
        panic(err)
    }
    fmt.Println("connect etcd success!")
    defer cli.Close()

    ctx,cancel := context.WithTimeout(context.Background(),time.Second*5)
    _,err = cli.Put(ctx,"mac","leave")
    defer  cancel()
    if err !=nil{
        fmt.Println("put etcd err:",err.Error())
        return
    }
}
```
```connect etcd success!
{"level":"warn","ts":"2021-02-08T17:10:46.490+0800","caller":"clientv3/retry_interceptor.go:62","msg":"retrying of unary invoker failed","target":"endpoint://client-5b14f6c4-2395-4a15-9ebb-cadf5985fb06/192.168.11.34:2379","attempt":0,"error":"rpc error: code = DeadlineExceeded desc = latest balancer error: all SubConns are in TransientFailure, latest connection error: connection error: desc = \"transport: Error while dialing dial tcp 192.168.11.34:2379: connect: connection refused\""}
put etcd err: context deadline exceeded
```

答: Deferring the cancel() means that the context won't be canceled until after your Println and return (during function tear-down). If the Put() call is on the edge of the timeout period that will cause the error to be reported. But calling cancel() directly after the Put() call seems to also have issues (see my recent question)</p>

Title: etcd err: context deadline exceeded

Body:
When I use shell it returns ok,
but when I use golang it returns err: context deadline exceeded.

Why?

package main

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
    "time"
)
func main()  {
    cli,err := clientv3.New(clientv3.Config{
        Endpoints: []string{"http://192.168.11.34:2379"},
        DialTimeout: 5*time.Second,
    })
    if err != nil{
        panic(err)
    }
    fmt.Println("connect etcd success!")
    defer cli.Close()

    ctx,cancel := context.WithTimeout(context.Background(),time.Second*5)
    _,err = cli.Put(ctx,"mac","leave")
    defer  cancel()
    if err !=nil{
        fmt.Println("put etcd err:",err.Error())
        return
    }
}

connect etcd success!
{"level":"warn","ts":"2021-02-08T17:10:46.490+0800","caller":"clientv3/retry_interceptor.go:62","msg":"retrying of unary invoker failed","target":"endpoint://client-5b14f6c4-2395-4a15-9ebb-cadf5985fb06/192.168.11.34:2379","attempt":0,"error":"rpc error: code = DeadlineExceeded desc = latest balancer error: all SubConns are in TransientFailure, latest connection error: connection error: desc = \"transport: Error while dialing dial tcp 192.168.11.34:2379: connect: connection refused\""}
put etcd err: context deadline exceeded


问:
Generate Monthly Aggregated Values in SQlite
I am new in SQLite and i have been working on SQL Query for quite some time.

Lets say we have database table say tbl_expense with the following table structure.

tbl_expense

```<code>CREATE TABLE IF NOT EXISTS tbl_expense(
    expense_id INTEGER PRIMARY KEY AUTOINCREMENT,
    expense_name VARCHAR(20) DEFAULT NULL,
    expense_desc VARCHAR(500) DEFAULT NULL,
    expense_type VARCHAR(20) DEFAULT NULL,
    expense_amt DECIMAL(6.3) DEFAULT NULL,
    expense_date TIMESTAMP DEFAULT NULL
)
</code>```

Assume we have the following data stored in the table.

Expected Output

Assuming we have expense_date as timestamp, How can i write a SQL query in such a way that i can produce the output like the one below.

Please help me on this issue.

答:
You need a LEFT join of a cte that returns all the month abbreviations to the table and conditional aggregation:

```<code>WITH cte(month, month_name) AS (VALUES
  ('01', 'JAN'), ('02', 'FEB'), ('03', 'MAR'), ('04', 'APR'), ('05', 'MAY'), ('06', 'JUN'),
  ('07', 'JUL'), ('08', 'AUG'), ('09', 'SEP'), ('10', 'OCT'), ('11', 'NOV'), ('12', 'DEC')
)
SELECT c.month_name,
       TOTAL(CASE WHEN expense_type = 'Income' THEN expense_amt END) Income,
       TOTAL(CASE WHEN expense_type = 'expense' THEN expense_amt END) Expense
FROM cte c LEFT JOIN tbl_expense e
ON strftime('%m', e.expense_date, 'unixepoch') = c.month
AND strftime('%Y', e.expense_date, 'unixepoch') = strftime('%Y', CURRENT_DATE)
GROUP BY c.month_name
ORDER BY c.month;
</code>```

The condition:

```<code>strftime('%Y', e.expense_date, 'unixepoch') = strftime('%Y', CURRENT_DATE)
</code>```

is used to return results only for the current year.

You can change it to get results for any year that you want, like:

```<code>strftime('%Y', e.expense_date, 'unixepoch') = '2020'
</code>```

See the demo.

Body:
I am new in SQLite and i have been working on SQL Query for quite some time.

Lets say we have database table say tbl_expense with the following table structure.

tbl_expense

CREATE TABLE IF NOT EXISTS tbl_expense(
    expense_id INTEGER PRIMARY KEY AUTOINCREMENT,
    expense_name VARCHAR(20) DEFAULT NULL,
    expense_desc VARCHAR(500) DEFAULT NULL,
    expense_type VARCHAR(20) DEFAULT NULL,
    expense_amt DECIMAL(6.3) DEFAULT NULL,
    expense_date TIMESTAMP DEFAULT NULL
)

Assume we have the following data stored in the table.

Expected Output

Assuming we have expense_date as timestamp, How can i write a SQL query in such a way that i can produce the output like the one below.

Please help me on this issue.

Body:
You need a LEFT join of a cte that returns all the month abbreviations to the table and conditional aggregation:

WITH cte(month, month_name) AS (VALUES
  ('01', 'JAN'), ('02', 'FEB'), ('03', 'MAR'), ('04', 'APR'), ('05', 'MAY'), ('06', 'JUN'),
  ('07', 'JUL'), ('08', 'AUG'), ('09', 'SEP'), ('10', 'OCT'), ('11', 'NOV'), ('12', 'DEC')
)
SELECT c.month_name,
       TOTAL(CASE WHEN expense_type = 'Income' THEN expense_amt END) Income,
       TOTAL(CASE WHEN expense_type = 'expense' THEN expense_amt END) Expense
FROM cte c LEFT JOIN tbl_expense e
ON strftime('%m', e.expense_date, 'unixepoch') = c.month
AND strftime('%Y', e.expense_date, 'unixepoch') = strftime('%Y', CURRENT_DATE)
GROUP BY c.month_name
ORDER BY c.month;

The condition:

strftime('%Y', e.expense_date, 'unixepoch') = strftime('%Y', CURRENT_DATE)

is used to return results only for the current year.

You can change it to get results for any year that you want, like:

strftime('%Y', e.expense_date, 'unixepoch') = '2020'

See the demo.


问:
How to scrape dates of News Site
I am trying to scrap the news website with news that are valid of a certain date.
The output of the function return :

```<code><li class="meta-data"><time data-datetime="relative" datetime="2022-01-30T08:56:09Z" title="2022-01-30T08:56:09Z">January 30, 2022 08:56</time></li>
</code>```

How can I only print the Date time only?
Printing i.text dont seem to work.

Below is the code.

```<code>import requests
from bs4 import BeautifulSoup
import datetime as datetime
from datetime import timedelta
import pandas as pd
pd.set_option('display.max_columns',None)
pd.set_option('max_colwidth',None)

def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        small_soup2 = soup2.find_all('li', {'class': 'meta-data'})
        #print(small_soup2)
        for i in small_soup2:
            print(i)

okx_scrap()
</code>```

答:
Considering i as a string (if not typecase the variable i to a string using built in method i = str(i))

```<code>i = str(i)
i = i.split("><")[1]
i = i.split("datetime=")[2]
i = i.split("\"")[1]

print(i)
# 2022-01-30T08:56:09Z

</code>```

Title: How to scrape dates of News Site

Body:
I am trying to scrap the news website with news that are valid of a certain date.
The output of the function return :

<time data-datetime="relative" datetime="2022-01-30T08:56:09Z" title="2022-01-30T08:56:09Z">January 30, 2022 08:56</time>

How can I only print the Date time only?
Printing i.text dont seem to work.

Below is the code.

import requests
from bs4 import BeautifulSoup
import datetime as datetime
from datetime import timedelta
import pandas as pd
pd.set_option('display.max_columns',None)
pd.set_option('max_colwidth',None)

def okx_scrap():

    b = []
    url = 'https://www.okex.com/support/hc/en-us/sections/360000030652-Latest-Announcements'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')
    small_soup = soup.find_all(class_ = "article-list-link")
    url_1st = 'https://www.okex.com/support'

        #Getting Yesterday's Date

    for i in small_soup:
        full_url = url_1st +(i['href'])
        page2 = requests.get(full_url)
        soup2 = BeautifulSoup(page2.content,'html.parser')
        small_soup2 = soup2.find_all('li', {'class': 'meta-data'})
        #print(small_soup2)
        for i in small_soup2:
            print(i)

okx_scrap()

Body:
Considering i as a string (if not typecase the variable i to a string using built in method i = str(i))

i = str(i)
i = i.split("><")[1]
i = i.split("datetime=")[2]
i = i.split("\"")[1]

print(i)
# 2022-01-30T08:56:09Z


答:
```<code>SELECT id
FROM your_table
GROUP BY id
HAVING sum(old_value = 0 AND new_value = 1) > 0
   AND sum(old_value = 1 AND new_value = 0) > 0
   AND sum(old_value = 1 AND new_value = 2) = 0
   AND sum(old_value = 2 AND new_value = 1) = 0
</code>```

Title: Get statuses that changed from 0->1->0 but not 0->1->2->1->0 sql

Body:
I am working on retrieving status changes from a DB where the table is something like

ID
Old_value
new_value
old_value_date
new_value_date

1
0
1
2021-12-01 00:00:00
2021-12-03 00:00:00

1
1
0
2021-12-03 00:00:00
2021-12-04 00:00:00

2
0
1
2021-12-01 00:00:00
2021-12-03 00:00:00

2
1
2
2021-12-03 00:00:00
2021-12-04 00:00:00

2
2
1
2021-12-04 00:00:00
2021-12-05 00:00:00

2
1
0
2021-12-05 00:00:00
2021-12-06 00:00:00

From this table I need the IDs which have gone from 0 to 1 and back to 0 but not the Ids which have gone from 0 to 1 to 2 and then back to 1 then 0.

Please help. Thanks!


问:
Ruby on Rails - Thinking Sphinx Problem

Possible Duplicate:

  Problem running Thinking Sphinx with Rails 2.3.5

I'm running rails 2.3.5
Every time I run rake ts:start or ts.rebuild the rake file quite with the following:

```<code>Sphinx cannot be found on your system. You may need to configure the following
settings in your config/sphinx.yml file:
  * bin_path
  * searchd_binary_name
  * indexer_binary_name

rake aborted!
key not found
</code>```

I have Sphinx running and the sphinx.yml in config is correct:(I believe)

```<code>bin_path: /usr/bin/searchd
  searchd_binary_name: searchd
  indexer_binary_name: sphinx-indexer
</code>```

Sphinx seems to be running, as when it is running ( by running command: service searchd start)

The error I get when I browse to a page that uses search is:

```<code>ThinkingSphinx::SphinxError in Jobs#index
 Showing app/views/jobs/index.html.erb where line #30 raised:
 unknown local index 'job_core' in search request
</code>```

Rather than a connection error?
Probably a multitude of problems here but i"m stuck.
Alternatively, I could rewrite the code I'm amending to use a different search function, if so, what's best?

答: bin_path should not include the actual binary names (as you're setting them with searchd_binary_name and indexer_binary_name) - so try it with just /usr/bin.

Title: Ruby on Rails - Thinking Sphinx Problem

Body:
Possible Duplicate:

  Problem running Thinking Sphinx with Rails 2.3.5

I'm running rails 2.3.5
Every time I run rake ts:start or ts.rebuild the rake file quite with the following:

Sphinx cannot be found on your system. You may need to configure the following
settings in your config/sphinx.yml file:
  * bin_path
  * searchd_binary_name
  * indexer_binary_name

rake aborted!
key not found

I have Sphinx running and the sphinx.yml in config is correct:(I believe)

bin_path: /usr/bin/searchd
  searchd_binary_name: searchd
  indexer_binary_name: sphinx-indexer

Sphinx seems to be running, as when it is running ( by running command: service searchd start)

The error I get when I browse to a page that uses search is:

ThinkingSphinx::SphinxError in Jobs#index
 Showing app/views/jobs/index.html.erb where line #30 raised:
 unknown local index 'job_core' in search request

Rather than a connection error?
Probably a multitude of problems here but i"m stuck.
Alternatively, I could rewrite the code I'm amending to use a different search function, if so, what's best?


问:
INSERT statement gives column reference is ambiguous error when used in Postgres function
I have the following function in Postgres for inserting values to a table employee_leaves and the table has the following structure

id[PK]
emp_id[varchar]
lt_id[int]
from_dt[date]
from_session_id[int]
to_dt[Date]
to_session_id[int]
reasons[varchar]
contact_details[varchar]
status[int]
notify_users[jsonb]
pending_with[int]
other_info[jsonb]
created_by[int]
created_on[date]
last_updated_by[int]
last_updated_on[date]

The function is as follows:

```<code>-- FUNCTION: company.lib.org.create_edit_employee_leave(json)

-- DROP FUNCTION IF EXISTS "company.lib.org".create_edit_employee_leave(json);

CREATE OR REPLACE FUNCTION "company.lib.org".create_edit_employee_leave(
    params json)
    RETURNS json
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
--select"company.lib.org".create_edit_employee_leave('{"emp_id":292, "lt_id":1, "from_dt":"2022-01-10", "from_session_id":1,"to_dt":"2022-01-11" ,"to_session_id":"2", "reasons":"Leave Reason", "contact_details":"8884514965", "status":1, "notify_users":[1,2,3] ,"pending_with":3, "other_info":"{}"," created_by":"123", "last_updated_by":13, "last_updated_on":"2022-01-20 00:00:00"}');

declare
        emp_id character varying(50);
        query text;
        cond text;
        response json;
        message character varying(50);

        lt_id smallint;
        from_dt date;
        from_session_id smallint;
        to_dt date;
        to_session_id smallint;
        reasons character varying(1024);
        contact_details character varying(1024);
        status smallint;
        notify_users json;
        pending_with character varying(50);
        other_info json;
        created_by integer;
        created_on timestamp with time zone;
        last_updated_by integer;
        last_updated_on timestamp with time zone;

        begin
        emp_id = (params->>'emp_id');
        lt_id = (params->>'lt_id');
        from_dt = (params->>'from_dt');
        from_session_id = (params->>'from_session_id');
        to_dt =  (params->>'to_dt');
        to_session_id = (params->>'to_session_id')::smallint;
        reasons = (params->>'reasons');
        contact_details = (params->>'contact_details');
        status = (params->>'status')::smallint;
        notify_users = COALESCE((params ->> 'notify_users')::jsonb,'{}'::jsonb);
        pending_with=(params->>'pending_with');
        other_info = COALESCE((params ->> 'other_info')::jsonb,'{}'::jsonb);
        created_by = (params->>'created_by')::integer;
        created_on = (params->>'created_on')::date;
        last_updated_by = (params->>'last_updated_by')::integer;
        last_updated_on = (params->>'last_updated_on')::date;
        message = '';
        raise info 'leave_application_id %',emp_id;

        if (params->>'action') = 'C' then
        INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on
        ) returning emp_id into emp_id;
        end if;
        message = 'New Leave application created successfully';

        response = ('{"status": 200, "leave_application_id": "' || emp_id || '", "message":"' || message ||'"}')::json;

       return response;

    EXCEPTION
        WHEN unique_violation THEN
            response = '{"status": 500, "data": "Unique key violation"}';
        WHEN check_violation THEN
            response = '{"status": 500, "data": "Check violation"}';
        WHEN no_data_found THEN
            response = '{"status": 500, "data": "Check"}';
        WHEN others THEN
            RAISE INFO 'Error Name:%', SQLERRM;
            RAISE INFO 'Error State:%', SQLSTATE;
            response = '{"status": 500, "data": "Unknown exception '|| SQLERRM || '"}';
    return response;

    END;

$BODY$;

ALTER FUNCTION "company.lib.org".create_edit_employee_leave(json)
    OWNER TO postgres;
</code>```

Now when I use the following INSERT directly, it is working fine

```<code>INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            '25506', 1, '2020-01-11', 1, '2020-01-12', 2, 'Leave Reasons', '8884514965', 1, '[25509,25336]', 25509, '{}', 25506, '2022-02-06T06:01:31.025Z', 25506, '2022-02-06T06:01:31.025Z'
        )
</code>```

But when I call function like this,

```<code>select "company.lib.org".create_edit_employee_leave(
    (
        '{"action":"C","emp_id":"25506","lt_id":1,"from_dt":"2020-01-11","from_session_id":1,"to_dt":"2020-01-12","to_session_id":2,"reasons":"LeaveReasons","contact_details":"8884514965","status":1,"notify_users":["25509","25336"],"pending_with":25509,"other_info":{},"created_by":"25506","created_on":"2022-02-06T06:08:11.531Z","last_updated_by":"25506","last_updated_on":"2022-02-06T06:08:11.531Z"}'
    )::json
</code>```

)

It is giving an error like

```<code>INFO:  Error Name:column reference "emp_id" is ambiguous
INFO:  Error State:42702
</code>```

As I have shown in the table structure, the column exists in the table and there are no other columns with the same name. However, I have other tables with the same column name and there is a foreign key constraint that refers to the employee table and the emp_id in that table. Also, this is an INSERT statement. So I am not sure what went wrong here. If someone can tell me what is the error here, that would be helpful.

答:
I think that it is the line

```<code>returning emp_id into emp_id;
</code>```

which is causing the problem.
You could change the name the local variable in the procedure, insert_emp_id for example.

Body:
I have the following function in Postgres for inserting values to a table employee_leaves and the table has the following structure

id[PK]
emp_id[varchar]
lt_id[int]
from_dt[date]
from_session_id[int]
to_dt[Date]
to_session_id[int]
reasons[varchar]
contact_details[varchar]
status[int]
notify_users[jsonb]
pending_with[int]
other_info[jsonb]
created_by[int]
created_on[date]
last_updated_by[int]
last_updated_on[date]

The function is as follows:

-- FUNCTION: company.lib.org.create_edit_employee_leave(json)

-- DROP FUNCTION IF EXISTS "company.lib.org".create_edit_employee_leave(json);

CREATE OR REPLACE FUNCTION "company.lib.org".create_edit_employee_leave(
    params json)
    RETURNS json
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
--select"company.lib.org".create_edit_employee_leave('{"emp_id":292, "lt_id":1, "from_dt":"2022-01-10", "from_session_id":1,"to_dt":"2022-01-11" ,"to_session_id":"2", "reasons":"Leave Reason", "contact_details":"8884514965", "status":1, "notify_users":[1,2,3] ,"pending_with":3, "other_info":"{}"," created_by":"123", "last_updated_by":13, "last_updated_on":"2022-01-20 00:00:00"}');

declare
        emp_id character varying(50);
        query text;
        cond text;
        response json;
        message character varying(50);

        lt_id smallint;
        from_dt date;
        from_session_id smallint;
        to_dt date;
        to_session_id smallint;
        reasons character varying(1024);
        contact_details character varying(1024);
        status smallint;
        notify_users json;
        pending_with character varying(50);
        other_info json;
        created_by integer;
        created_on timestamp with time zone;
        last_updated_by integer;
        last_updated_on timestamp with time zone;

        begin
        emp_id = (params->>'emp_id');
        lt_id = (params->>'lt_id');
        from_dt = (params->>'from_dt');
        from_session_id = (params->>'from_session_id');
        to_dt =  (params->>'to_dt');
        to_session_id = (params->>'to_session_id')::smallint;
        reasons = (params->>'reasons');
        contact_details = (params->>'contact_details');
        status = (params->>'status')::smallint;
        notify_users = COALESCE((params ->> 'notify_users')::jsonb,'{}'::jsonb);
        pending_with=(params->>'pending_with');
        other_info = COALESCE((params ->> 'other_info')::jsonb,'{}'::jsonb);
        created_by = (params->>'created_by')::integer;
        created_on = (params->>'created_on')::date;
        last_updated_by = (params->>'last_updated_by')::integer;
        last_updated_on = (params->>'last_updated_on')::date;
        message = '';
        raise info 'leave_application_id %',emp_id;

        if (params->>'action') = 'C' then
        INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on
        ) returning emp_id into emp_id;
        end if;
        message = 'New Leave application created successfully';

        response = ('{"status": 200, "leave_application_id": "' || emp_id || '", "message":"' || message ||'"}')::json;

       return response;

    EXCEPTION
        WHEN unique_violation THEN
            response = '{"status": 500, "data": "Unique key violation"}';
        WHEN check_violation THEN
            response = '{"status": 500, "data": "Check violation"}';
        WHEN no_data_found THEN
            response = '{"status": 500, "data": "Check"}';
        WHEN others THEN
            RAISE INFO 'Error Name:%', SQLERRM;
            RAISE INFO 'Error State:%', SQLSTATE;
            response = '{"status": 500, "data": "Unknown exception '|| SQLERRM || '"}';
    return response;

    END;

$BODY$;

ALTER FUNCTION "company.lib.org".create_edit_employee_leave(json)
    OWNER TO postgres;

Now when I use the following INSERT directly, it is working fine

INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            '25506', 1, '2020-01-11', 1, '2020-01-12', 2, 'Leave Reasons', '8884514965', 1, '[25509,25336]', 25509, '{}', 25506, '2022-02-06T06:01:31.025Z', 25506, '2022-02-06T06:01:31.025Z'
        )

But when I call function like this,

select "company.lib.org".create_edit_employee_leave(
    (
        '{"action":"C","emp_id":"25506","lt_id":1,"from_dt":"2020-01-11","from_session_id":1,"to_dt":"2020-01-12","to_session_id":2,"reasons":"LeaveReasons","contact_details":"8884514965","status":1,"notify_users":["25509","25336"],"pending_with":25509,"other_info":{},"created_by":"25506","created_on":"2022-02-06T06:08:11.531Z","last_updated_by":"25506","last_updated_on":"2022-02-06T06:08:11.531Z"}'
    )::json

)

It is giving an error like

INFO:  Error Name:column reference "emp_id" is ambiguous
INFO:  Error State:42702

As I have shown in the table structure, the column exists in the table and there are no other columns with the same name. However, I have other tables with the same column name and there is a foreign key constraint that refers to the employee table and the emp_id in that table. Also, this is an INSERT statement. So I am not sure what went wrong here. If someone can tell me what is the error here, that would be helpful.

Body:
I think that it is the line

returning emp_id into emp_id;

which is causing the problem.
You could change the name the local variable in the procedure, insert_emp_id for example.


问:
Parsing and searching a CSV file
I want to parse through a contacts list CSV file that looks like this:

```<code>First Name  Last Name  Full Name                            Short Name  Phone Number
Jenny       Smith      CN=Jenny Smith/OU=CORP/O=COMPANY     jesmi       6468675309
Mary        Poppin     CN=Mary Poppins/OU=STORE/O=COMPANY   mapop       7005555578
Tony        Stark      CN=Tony Stark/OU=STORE/O=COMPANY     tostar      6007777798
Peter       Parker     CN=Peter Parker/OU=NEWS/O=COMPANY    pepar       5008889090
</code>```

I want to be able to search through column "Full Name" and select string "OU=STORE" and move all rows that contain "OU=STORE" aside, and then move it to it's own csv file called "store.csv". Then repeat the same process for "OU=CORP" and "OU=NEWS".

This is what I want my output to look like:

Store.csv should contain only this information once the process is done.

```<code>First Name  Last Name  Full Name                            Short Name  Phone Number
Mary        Poppin     CN=Mary Poppins/OU=STORE/O=COMPANY   mapop       7005555578
Tony        Stark      CN=Tony Stark/OU=STORE/O=COMPANY     tostar      6007777798
</code>```

corp.csv

```<code>First Name  Last Name  Full Name                            Short Name  Phone Number
Jenny       Smith      CN=Jenny Smith/OU=CORP/O=COMPANY     jesmi       6468675309
</code>```

news.csv

```<code>First Name  Last Name  Full Name                            Short Name  Phone Number
Peter       Parker     CN=Peter Parker/OU=NEWS/O=COMPANY    pepar       5008889090
</code>```

I have a small script of what I've done so far but I'm not sure what to do in the end:

```<code>import pandas as pd
import csv

#this is the source folder
source_dir = 'C:/Users/username/documents/contacts/contactslist.csv'

#this is the folder where I want to move the parsed data.
store_target_dir = 'C:/Users/username/documents/contacts/store/'
corp_target_dir = 'C:/Users/username/documents/contacts/corp/'
news_target_dir = 'C:/Users/username/documents/contacts/news/'

col_list = ["Full Name"]

store = 'OU=STORE'
corp = 'OU=CORP'
news = 'OU=NEWS'

#When it comes time to move the data to their folders with their csv name
csvName = store_target_dir + "/" + "store.csv"
csvName2 = corp_target_dir + "/" + "corp.csv"
csvName3 = news_target_dir + "/" +"news.csv"

#opening the file
file = open(source_dir)

#reading the csv file
df = pd.read_csv(file)
</code>```

答:
Trying to not do too much modifications to your code a solution could look like this:

import os, os.path
import csv

#this is the source folder
original_contacts_filename = r'C:\Users\username\documents\contacts\contactslist.csv'

#this is the folder where I want to move the parsed data.
store_target_dir = r'C:\Users\username\documents\contacts\store'
corp_target_dir = r'C:\Users\username\documents\contacts\corp'
news_target_dir = r'C:\Users\username\documents\contacts\news'

os.makedirs(store_target_dir, exist_ok=True)
os.makedirs(corp_target_dir, exist_ok=True)
os.makedirs(news_target_dir, exist_ok=True)

store = 'OU=STORE'
corp = 'OU=CORP'
news = 'OU=NEWS'

#When it comes time to move the data to their folders with their csv name
csv_name = os.path.join(store_target_dir, "store.csv")
csv_name2 = os.path.join(corp_target_dir, "corp.csv")
csv_name3 = os.path.join(news_target_dir, "news.csv")

with (
    open(original_contacts_filename, newline='') as original_contacts_file,
    open(csv_name, mode='w', newline='') as csv_file,
    open(csv_name2, mode='w', newline='') as csv_file2,
    open(csv_name3, mode='w', newline='') as csv_file3):

    original_contacts = csv.DictReader(original_contacts_file)

    store_destination = csv.writer(csv_file)
    corp_destination = csv.writer(csv_file2)
    news_destionation = csv.writer(csv_file3)

    output_headers = ('First Name', 'Last Name', 'Full Name', 'Short Name', 'Phone Number')
    store_destination.writerow(output_headers)
    corp_destination.writerow(output_headers)
    news_destionation.writerow(output_headers)

    for current_contact in original_contacts:
        if store in current_contact['Full Name']:
            output_destination = store_destination
        elif corp in current_contact['Full Name']:
            output_destination = corp_destination
        elif news in current_contact['Full Name']:
            output_destination = news_destionation
        else:
            output_destination = None

        if output_destination is not None:
            output_destination.writerow(current_contact[column] for column in output_headers)
```
<p>But we can see a lot of repetitions which usually smells. We could simplyfy the code like this:</p>
<pre class="lang-py prettyprint-override"><code>import os, os.path
import csv
import re

original_contacts_filename = 'contactslist.csv'

source_directory = r'C:\Users\username\documents\contacts'

corporate_units_expected = ('store', 'corp', 'news')

target_directory = r'C:\Users\username\documents\contacts'
target_files_info = {
    current_unit: (
        current_name := os.path.join(target_directory, current_unit, f'{current_unit}2.csv'),
        open(current_name, 'w', newline='')
    )
    for current_unit in corporate_units_expected
}

for current_target, _ in target_files_info.values():
    os.makedirs(os.path.dirname(current_target), exist_ok=True)

matcher = re.compile(r'OU=([ 0-9a-zA-Z]+)')

with (
    open(original_contacts_filename, newline='') as original_contacts_file,
    target_files_info['store'][1], target_files_info['corp'][1], target_files_info['news'][1]
):
    original_contacts = csv.DictReader(original_contacts_file)

    writers = {
        current_unit: csv.writer(current_target[1])
        for (current_unit, current_target) in target_files_info.items()
    }

    output_headers = ('First Name', 'Last Name', 'Full Name', 'Short Name', 'Phone Number')

    for current_writer in writers.values():
        current_writer.writerow(output_headers)

    for current_contact in original_contacts:
        if match_found := matcher.search(current_contact['Full Name']):
            current_writer = writers[match_found[1].lower()]
            current_writer.writerow(current_contact[column] for column in output_headers)
</code>```

We could also have an example where we don't know in advance how many files we which to sort these entries into but it get a lot more complicated because we cannot use the with statement directly.

Title: Parsing and searching a CSV file

Body:
I want to parse through a contacts list CSV file that looks like this:

First Name  Last Name  Full Name                            Short Name  Phone Number
Jenny       Smith      CN=Jenny Smith/OU=CORP/O=COMPANY     jesmi       6468675309
Mary        Poppin     CN=Mary Poppins/OU=STORE/O=COMPANY   mapop       7005555578
Tony        Stark      CN=Tony Stark/OU=STORE/O=COMPANY     tostar      6007777798
Peter       Parker     CN=Peter Parker/OU=NEWS/O=COMPANY    pepar       5008889090

I want to be able to search through column "Full Name" and select string "OU=STORE" and move all rows that contain "OU=STORE" aside, and then move it to it's own csv file called "store.csv". Then repeat the same process for "OU=CORP" and "OU=NEWS".

This is what I want my output to look like:

Store.csv should contain only this information once the process is done.

First Name  Last Name  Full Name                            Short Name  Phone Number
Mary        Poppin     CN=Mary Poppins/OU=STORE/O=COMPANY   mapop       7005555578
Tony        Stark      CN=Tony Stark/OU=STORE/O=COMPANY     tostar      6007777798

corp.csv

First Name  Last Name  Full Name                            Short Name  Phone Number
Jenny       Smith      CN=Jenny Smith/OU=CORP/O=COMPANY     jesmi       6468675309

news.csv

First Name  Last Name  Full Name                            Short Name  Phone Number
Peter       Parker     CN=Peter Parker/OU=NEWS/O=COMPANY    pepar       5008889090

I have a small script of what I've done so far but I'm not sure what to do in the end:

import pandas as pd
import csv

#this is the source folder
source_dir = 'C:/Users/username/documents/contacts/contactslist.csv'

#this is the folder where I want to move the parsed data.
store_target_dir = 'C:/Users/username/documents/contacts/store/'
corp_target_dir = 'C:/Users/username/documents/contacts/corp/'
news_target_dir = 'C:/Users/username/documents/contacts/news/'

col_list = ["Full Name"]

store = 'OU=STORE'
corp = 'OU=CORP'
news = 'OU=NEWS'

#When it comes time to move the data to their folders with their csv name
csvName = store_target_dir + "/" + "store.csv"
csvName2 = corp_target_dir + "/" + "corp.csv"
csvName3 = news_target_dir + "/" +"news.csv"

#opening the file
file = open(source_dir)

#reading the csv file
df = pd.read_csv(file)

Body:
Trying to not do too much modifications to your code a solution could look like this:

import os, os.path
import csv

#this is the source folder
original_contacts_filename = r'C:\Users\username\documents\contacts\contactslist.csv'

#this is the folder where I want to move the parsed data.
store_target_dir = r'C:\Users\username\documents\contacts\store'
corp_target_dir = r'C:\Users\username\documents\contacts\corp'
news_target_dir = r'C:\Users\username\documents\contacts\news'

os.makedirs(store_target_dir, exist_ok=True)
os.makedirs(corp_target_dir, exist_ok=True)
os.makedirs(news_target_dir, exist_ok=True)

store = 'OU=STORE'
corp = 'OU=CORP'
news = 'OU=NEWS'

#When it comes time to move the data to their folders with their csv name
csv_name = os.path.join(store_target_dir, "store.csv")
csv_name2 = os.path.join(corp_target_dir, "corp.csv")
csv_name3 = os.path.join(news_target_dir, "news.csv")

with (
    open(original_contacts_filename, newline='') as original_contacts_file,
    open(csv_name, mode='w', newline='') as csv_file,
    open(csv_name2, mode='w', newline='') as csv_file2,
    open(csv_name3, mode='w', newline='') as csv_file3):

    original_contacts = csv.DictReader(original_contacts_file)

    store_destination = csv.writer(csv_file)
    corp_destination = csv.writer(csv_file2)
    news_destionation = csv.writer(csv_file3)

    output_headers = ('First Name', 'Last Name', 'Full Name', 'Short Name', 'Phone Number')
    store_destination.writerow(output_headers)
    corp_destination.writerow(output_headers)
    news_destionation.writerow(output_headers)

    for current_contact in original_contacts:
        if store in current_contact['Full Name']:
            output_destination = store_destination
        elif corp in current_contact['Full Name']:
            output_destination = corp_destination
        elif news in current_contact['Full Name']:
            output_destination = news_destionation
        else:
            output_destination = None

        if output_destination is not None:
            output_destination.writerow(current_contact[column] for column in output_headers)

But we can see a lot of repetitions which usually smells. We could simplyfy the code like this:

import os, os.path
import csv
import re

original_contacts_filename = 'contactslist.csv'

source_directory = r'C:\Users\username\documents\contacts'

corporate_units_expected = ('store', 'corp', 'news')

target_directory = r'C:\Users\username\documents\contacts'
target_files_info = {
    current_unit: (
        current_name := os.path.join(target_directory, current_unit, f'{current_unit}2.csv'),
        open(current_name, 'w', newline='')
    )
    for current_unit in corporate_units_expected
}

for current_target, _ in target_files_info.values():
    os.makedirs(os.path.dirname(current_target), exist_ok=True)

matcher = re.compile(r'OU=([ 0-9a-zA-Z]+)')

with (
    open(original_contacts_filename, newline='') as original_contacts_file,
    target_files_info['store'][1], target_files_info['corp'][1], target_files_info['news'][1]
):
    original_contacts = csv.DictReader(original_contacts_file)

    writers = {
        current_unit: csv.writer(current_target[1])
        for (current_unit, current_target) in target_files_info.items()
    }

    output_headers = ('First Name', 'Last Name', 'Full Name', 'Short Name', 'Phone Number')

    for current_writer in writers.values():
        current_writer.writerow(output_headers)

    for current_contact in original_contacts:
        if match_found := matcher.search(current_contact['Full Name']):
            current_writer = writers[match_found[1].lower()]
            current_writer.writerow(current_contact[column] for column in output_headers)

We could also have an example where we don't know in advance how many files we which to sort these entries into but it get a lot more complicated because we cannot use the with statement directly.


问:
How can I use React hooks in React classic `class` component?
In this example, I have this react class:

```<code>class MyDiv extends React.component
   constructor(){
      this.state={sampleState:'hello world'}
   }
   render(){
      return <div>{this.state.sampleState}
   }
}
</code>```

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

答:
I've made a library for this. React Hookable Component.

Usage is very simple. Replace extends Component or extends PureComponent with extends HookableComponent or extends HookablePureComponent. You can then use hooks in the render() method.

```<code>import { HookableComponent } from 'react-hookable-component';

//
class ComponentThatUsesHook extends HookableComponent<Props, State> {
    render() {
        //
        const value = useSomeHook();
        return <span>The value is {value}</span>;
    }
}
</code>```

Body:
In this example, I have this react class:

class MyDiv extends React.component
   constructor(){
      this.state={sampleState:'hello world'}
   }
   render(){
      return
{this.state.sampleState}
   }
}

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

Body:
I've made a library for this. React Hookable Component.

Usage is very simple. Replace extends Component or extends PureComponent with extends HookableComponent or extends HookablePureComponent. You can then use hooks in the render() method.

import { HookableComponent } from 'react-hookable-component';

//
class ComponentThatUsesHook extends HookableComponent<Props, State> {
    render() {
        //
        const value = useSomeHook();
        return <span>The value is {value}</span>;
    }
}


问:
Build relationship between two tables with Times that are bnot exact but close
I have two tables that i need to build a relationship. They both have a timestamp that I want to use to match the data. The problem is that the timestamps are not exact and my be off by a few seconds,. Eg 8.32.50 and 8.32.45.  I could use the hh.mm (change date time to integer)to match the data as but the problem arise in a situation where e.g the times are 8.32.58 and 8.33.067</p>

答: You will need to set up a time-dimension table. A time-dimension table goes down to the granularity of seconds, so you can relate both tables to that one dimension table so that they can "speak" to one another. Radacad has a great script for creating one here, which also has time-binning columns.


问:
React pass fetched data from API to another component
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

```<code>import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">

        {products.map((product) => (
          <div className="card" key={product.id}>
            {" "}

            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FeaturedProduct;
</code>```

My Product Details Page:

```<code>import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (
    <div>
      <div>
        <h1>{props.name}</h1>
        <h1>{props.color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;
</code>```

答:
```<code> //pass it this way
 <Switch>
   <Route
   path="/productdetails"
   render={() => (
   { <ProductDetails  product={product}/>})}/>
   />
  </Switch>
</code>```

Body:
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (

 Your Products List is shown below:

        {products.map((product) => (

            {" "}

{product.item}

              {product.city}, {product.state}

            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>

        ))}

  );
}

export default FeaturedProduct;

My Product Details Page:

import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (

{props.name}

{props.color}

  );
}
export default  ProductDetails;


问:
Why does Visual Studio compile my HTTP server app to run on port 5001 when I set it to 443/80?
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

```<code>"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"
</code>```

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)

答:
You can also use config for Kubernetes</p>
```<code>Kestrel__EndPoints__Http__Url : http://+:80
</code>```

Body:
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)

Body:
You can also use config for Kubernetes

Kestrel__EndPoints__Http__Url : http://+:80


问:
How can you get the return value of a Windows thread?
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

```<code>DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}
</code>```

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?

答:
GetExitCodeThread is the correct function. Here is the MSDN description of what it does:

This function returns immediately. If the specified thread has not
  terminated and the function succeeds, the status returned is
  STILL_ACTIVE. If the thread has terminated and the function succeeds,
  the status returned is one of the following values:

The exit value specified in the ExitThread or TerminateThread function.

The return value from the thread function.

The exit value of the thread's process.

Body:
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?


问:
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?

```<code>SAMPLE_COUNT = 5000
TEST_COUNT = 20000
seed(0)
sample = list()
test_sample = list()
for index, line in enumerate(open('covtype.data','rb')):
    if index < SAMPLE_COUNT:
        sample.append(line)
    else:
        r = randint(0,index)
        if r < SAMPLE_COUNT:
            sample[r] = line
        else:
            k = randint(0,index)
            if k < TEST_COUNT:
                if len(test_sample) < TEST_COUNT:
                    test_sample.append(line)
                else:
                    test_sample[k] = line
from sklearn.preprocessing import StandardScaler
for n, line in enumerate(sample):
sample[n] = map(float, line.strip().split(','))
y = np.array(sample)[:,-1]
scaling = StandardScaler()

X = scaling.fit_transform(np.array(sample)[:,:-1]) ##here use fit and transform

for n,line in enumerate(test_sample):
test_sample[n] = map(float,line.strip().split(','))
yt = np.array(test_sample)[:,-1]

Xt = scaling.transform(np.array(test_sample)[:,:-1])##why here only use transform
</code>```

As the annotation says, why Xt only use transform but no fit?

答:
fit_transform() - learn the parameter of scaling (Train data)

transform() - Apply those learned scaling method here (Test data)

```<code>ss = StandardScaler()
X_train = ss.fit_transform(X_train) #here we need to feed this to the model to learn so it will learn the parameter of scaling
X_test = ss.transform(X_test) #It will use the learn parameter to transform
</code>```

Body:
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?

SAMPLE_COUNT = 5000
TEST_COUNT = 20000
seed(0)
sample = list()
test_sample = list()
for index, line in enumerate(open('covtype.data','rb')):
    if index < SAMPLE_COUNT:
        sample.append(line)
    else:
        r = randint(0,index)
        if r < SAMPLE_COUNT:
            sample[r] = line
        else:
            k = randint(0,index)
            if k < TEST_COUNT:
                if len(test_sample) < TEST_COUNT:
                    test_sample.append(line)
                else:
                    test_sample[k] = line
from sklearn.preprocessing import StandardScaler
for n, line in enumerate(sample):
sample[n] = map(float, line.strip().split(','))
y = np.array(sample)[:,-1]
scaling = StandardScaler()

X = scaling.fit_transform(np.array(sample)[:,:-1]) ##here use fit and transform

for n,line in enumerate(test_sample):
test_sample[n] = map(float,line.strip().split(','))
yt = np.array(test_sample)[:,-1]

Xt = scaling.transform(np.array(test_sample)[:,:-1])##why here only use transform

As the annotation says, why Xt only use transform but no fit?

Body:
fit_transform() - learn the parameter of scaling (Train data)

transform() - Apply those learned scaling method here (Test data)

ss = StandardScaler()
X_train = ss.fit_transform(X_train) #here we need to feed this to the model to learn so it will learn the parameter of scaling
X_test = ss.transform(X_test) #It will use the learn parameter to transform


问:
Unable to Install Pillow for Tkinter via PIP
I tried to install Pillow library for my Tkinter project but when I try to install it, it gives me the following error.

Fatal error in launcher: Unable to create process using "C:\Python310\python.exe"  "C:\Python310\Scripts\pip.exe" install Pillow : The system cannot find the file specified.

I have the latest Python version from the official website and I also have pip manually installed during my Win7 days. Even debugging ain't helping. It gives the same error.

答:
You need unofficial python binaries version of pillow. Go to this website. Then press F3. then in search box, type pillow. then click on the hyperlink which is highlighted by the browser. then download a wheel according to your os and python version. after download, open cmd in the download folder. to do that press SHIFT + RIGHT CLICK and click on Open CMD Here. then on the cmd, type pip3 install <your downloaded file name> It should work. I used this trick for Installing PyAudio in Python 3.10 on Windows 10.

TIP: while typing 3/4 letters of the file name, press TAB to autocomplete