text:
Q: Repeat Fade In / Fade Out effects to switch between three views I've created one view containing three subviews.
I would like to fade in / out the three subviews and repeat the effect indefinitely.
I try something like :
+ (void)fadeIn:(UIView *)view withDuration:(float)duration
{
    [UIView animateWithDuration:duration animations:^{
        view.alpha = 1.0;
    }];
}

+ (void)fadeOut:(UIView *)view withDuration:(float)duration
{
    [UIView animateWithDuration:duration animations:^{
        view.alpha = 0.0;
    }];
}

[UIView animateWithDuration:5.0
                      delay:2.0
                    options:UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                 animations:^
{
    [Utilities fadeOut:headSubtitle_1 withDuration:1];
    [Utilities fadeIn:headSubtitle_2 withDuration:1];
    [Utilities fadeOut:headSubtitle_2 withDuration:1];
    [Utilities fadeIn:headSubtitle_3 withDuration:1];
    [Utilities fadeOut:headSubtitle_3 withDuration:1];
    [Utilities fadeIn:headSubtitle_1 withDuration:1];
}
                 completion:^(BOOL finished)
{}];

But it doesn't work well.
The effect that I would obtain is :

*

*Display headSubtitle_1 for 2 seconds

*FadeOut headSubtitle_1 in 1 second

*FadeIn headSubstitle_2 in 1 second

*Display headSubstitle_2 for 2 seconds

*FadeOut headSubtitle_2 in 1 second

*FadeIn headSubstitle_3 in 1 second

*Display headSubstitle_3 for 2 seconds

*FadeOut headSubtitle_3 in 1 second

*FadeIn headSubtitle_1 in 1 second

*Repeat to 1.

Thanks a lot !
EDIT
Finally, I try something like this :
+ (void)runAnimationSubtitleOrdersWithSub1:(UITextView *)headSubtitle_1 andSub2:(UITextView *)headSubtitle_2 andSub3:(UITextView *)headSubtitle_3
{
    [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        headSubtitle_1.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished)
        {
            [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                headSubtitle_2.alpha = 1;
            } completion:^(BOOL finished) {
                if (finished)
                {
                    [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                        headSubtitle_2.alpha = 0;
                    } completion:^(BOOL finished) {
                        if (finished)
                        {
                            [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                                headSubtitle_3.alpha = 1;
                            } completion:^(BOOL finished) {
                                if (finished)
                                {
                                    [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                                        headSubtitle_3.alpha = 0;
                                    } completion:^(BOOL finished) {
                                        if (finished)
                                        {
                                            [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                                                headSubtitle_1.alpha = 1;
                                            } completion:^(BOOL finished) {
                                                [FormBuilder runAnimationSubtitleOrdersWithSub1:headSubtitle_1 andSub2:headSubtitle_2 andSub3:headSubtitle_3];
                                            }];
                                        }
                                    }];
                                }
                            }];
                        }
                    }];
                }
            }];
        }
    }];
}

It's really ugly ! If some body knows a better way to do this.

A: Maybe you can play with several animation with something like this (but, it's not beautiful) :
_imageView.alpha = 0.0f;
_imageView2.alpha = 0.0f;
_imageView3.alpha = 0.0f;

[UIView animateWithDuration:1
                      delay:0
                    options:UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                 animations:^{

                     _imageView.alpha = 1.0f;

                     [UIView animateWithDuration:1
                                           delay:1
                                         options:UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                                      animations:^{

                                          _imageView2.alpha = 1.0f;

                                      } completion:^(BOOL finished) {

                                          _imageView2.alpha = 0.0f;

                                      }
                      ];

                 } completion:^(BOOL finished) {

                     _imageView.alpha = 0.0f;

                 }
 ];

A: Take a look at [UIView beginAnimations:(NSString *) context:(void *)].


text:
Q: How to post model that contains a collection? Have a model containing an empty list.  I want to add items to the list and post it all in one go.
Main Model
[Required]
public string WillAttend { get; set; }

///
/// Guests to accompany the RSVPer
///
public List<Guest> Guests { get; set; }

Guest Model
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }

Inside the form:

        Yes @Html.RadioButtonFor(m => m.WillAttend, "yes", new { @class = "" })
        No @Html.RadioButtonFor(m => m.WillAttend, "no", new { @class = "" })

        Will you bringing any children or guests?
        <input id="InputAddGuest" type="button" class="form-control" value="Add Guest or Child" />

        <button type="submit" class="btn btn-block">Finish</button>

There is one form on the page for submitting the main model above, and I'm using jquery to generate html:

but what goes in here so that when I post my model contains actual guests?

A: You basically need to build the html markup with input field names matching to your view model property hierarchy.
Since your main view model has a Guests property which is a collection, your input field's name should be like Guests[0].FirstName, Guests[0].LastName,Guests[1].FirstName etc.
This should work
$(document).ready(function () {
    $('#InputAddGuest').click(function () {
       var index = $(".guestRow").length;
       var row = "
";
       row += "<input type='text' name='Guests[" + index + "].FirstName' />";
       row += "<input type='text' name='Guests[" + index + "].LastName' />";
       row += "
";
       $('#ListGuest').append(row);
    });
});

Assuming your HttpPost action method parameter is of MainModel type
[HttpPost]
public ActionResult Register(MainModel model)
{
    //check model.WillAttend
    // iterate through model.Guests
    // to do : return something
}

A:
I have similar case, at Feature.
What I do is: I make session on controller, so when
$('#InputAddGuest').click(function () {

        });

I call $.ajax like this:
  var valDdlTeamProject = $('#TeamProjectCollection').val();
        var valDdlProject = $('#Project').val();
$.ajax({
                type: 'POST',
                dataType: 'json',
                url: '@Url.Action("AddTfsFeature", "Request")',
                data: {
                    requestNo: '@Model.RequestNo',
                    teamProjectCollection: valDdlTeamProject,
                    project: valDdlProject
                },
                success: function (response) {
                    if (response.Result == 'Success') {
                        var additionalHtml = "";
                        var additionalHtml = '';
                        additionalHtml += response.TempObject.TeamProjectCollection + ' - ' + response.TempObject.Project;
                        additionalHtml += '';
                        additionalHtml += '';
                        $('.body-add-feature').append(additionalHtml);
                        clearTfsFeatureForm();
                        iCounterFeature = response.TempObjectCount;
                        if (response.TempObjectCount > 0)
                            $('#DialogCreateFeature').modal('hide');
                    }
                    if (response.Result == 'Failed') {
                        alert(response.Message);
                    }
                },
                error: function (response) { }
            })

At code behind:
[HttpPost]
        public JsonResult AddTfsFeature(string requestNo, string teamProjectCollection, string project)
        {
            ResultMessageViewModel result = new ResultMessageViewModel
            {
                Result = "Failed",
                Message = "No data"
            };

            TfsFeature feature = new TfsFeature
            {
                ID = sessTempIndexTfsFeature,
                RequestNo = requestNo,
                TeamProjectCollection = teamProjectCollection,
                Project = project,
                CreatedBy = UserID
            };
            for (int i = 0; i < sessListTfsFeature.Count; i++)
            {
                if (sessListTfsFeature.ElementAt(i).TeamProjectCollection == teamProjectCollection &&
                    sessListTfsFeature.ElementAt(i).Project == project)
                {
                    result.Result = "Failed";
                    result.Message = "Existing feature data has already exist.";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }
            sessListTfsFeature.Add(feature);

        result.Result = "Success";
        result.Message = "Add Success";
        result.TempObject = feature;
        result.TempObjectCount = sessListTfsFeature.Count;
        return Json(result, JsonRequestBehavior.AllowGet);

sessListTfsFeature is List<TfsFeature>
and if there is button to delete Guest, you need new ajax, and new controller to delete object Guest at session.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read word document story which is already open? I have created a Word add-in. I want to read an active word document which is currently open(Content of word document story) by pressing a button which is on window form, and window form get open by click on the button from the ribbon. So let me be clear that how flow happens.
Ribbon -> Button on Ribbon (click it) -> A window form open (Having a button to read active document content) -> Reads the document.
I have tried to access document content by WordOpenXML property and the second method I've tried is to access paragraphs of the active document.
Try 1: Accessing paragraphs
private async Task<bool> SaveDocToCryptacomm1(string fileName)
{
    [...some code here...]

    StringBuilder sb = new StringBuilder();
    long paraCount = application.ActiveDocument.Paragraphs.Count;
    while (i < paraCount) {
        sb.Append(application.ActiveDocument.Paragraphs[i].Range.Text);
    }

    [...some code here...]
}

Try 2: Accessing content from WordOpenXML property.
private async Task<bool> SaveDocToCryptacomm1(string fileName)
{
    [...some code here...]

    Encoding.Default.GetBytes(application.ActiveDocument.WordOpenXML);

    [...some code here...]
}

Result of Try 1:
Document get saved successfully but no content is there.
Result of Try 2:
Document get saved successfully but when I try to open it, it is corrupted.
In this case, what should i do, to read active document from Window form button click event.
Does the Microsoft.Office.Interop.Word.Application.ActiveDocument will work? Am I doing something wrong or what?
Edit: Need to do this, without saving open document on local drive and Provided code I have written on Window form's button click event. Will it work?


text:
Q: Setting python pandas histogram size I'm trying to set size of pandas histogram when saving to a file. I go about this like that:
fig = df_analyze.hist();
fig.set_size_inches(16,12)
plt.savefig('hist.png')

But this doesn't work. What is the correct syntax?

A: Setting
rcParams['figure.figsize'] = 16, 12

before calling df_analyze.hist() does the job. So, the full solution reads:
rcParams['figure.figsize'] = 16, 12
df_analyze.hist()
plt.savefig('hist.png')


text:
Q: Multiple select values being retrieved and not being sent as a single slug ID Ok I've looked through the site and a few others trying to find an answer to this, but I am struggling. Essentially I am sending from my users index page -> user change primary and from there the user then chooses a house from the select box and then when accepts it sends the ID back so that I can modify and designate the house as being primary.
The code has been changed quite often as tried different solutions, however what happens is that when a user sends the form back to the index page it then submits all house ID's instead of only the specific ID of the house that has been selected.

This is the changeprimary view

 @extends('app')
    @section('links')

Back

    @stop

    @section('content')

Change your password

                            @if (count($errors) > 0)

                                    Whoops! There were some problems with your input.

                                        @foreach ($errors->all() as $error)

{{ $error }}

                                        @endforeach

                            @endif

                                {!! Form::model($houses,['method' => 'POST','route'=>['user.cprimary',$house_id->$houses->id]]) !!}
                                {!! Form::open(['url' => 'user']) !!}

                                @if($houses != null)

                                        {!! Form::label('primary', 'Choose a house to make primary') !!}
                                        {{--{!! Form::select('primary', $houses, $houses) !!}--}}

                                            {!! Form::select('primary', $houses) !!}

                                        {!! Form::close() !!}

                                        {!! Form::submit('Make House Primary House', ['class' => 'btn btn-primary']) !!}

                                @else

Add new house

                                    </form>
                                @endif

This is the user controller for show primary and change priamry

    public function showcp()
    {
        $houses = House::where('user_id', '=', Auth::id())
            ->lists('h_name');

        $house_id = House::where('user_id', '=', Auth::id())
            ->lists('id');
//        foreach($house_ids as $house_id) {
//            $house_id = $house_id->id;
//        }
//        $house = House::find($house_id)->h_name->first();
        if (!$houses->isEmpty()) {
            return view('users.changeprimary', compact('houses','house_id'));
        }
        return view('house.nohouse');
    }

    public function changeprimary($id)
    {
        //Find and update password linked to User ID.

        $house_all = House::all()->where('user_id', Auth::id());
        foreach($house_all as $houses)
        {
            $houses->primary = '0';
            $houses->save();

        }
        $houses->save();
        $updateHouse = House::find($id);
        $updateHouse->primary = '1';
        $updateHouse->save();
        return redirect('user')->with('message', 'House '.House::find($id)->h_name.' is primary');
    }

And this is the code for the index view

@extends('app')

@section('links')

Back

@stop

@section('content')

Profile Options

                            @if (session('message'))

                                    {{ session('message') }}

                            @endif

                            {!! Form::open() !!}

                                    Change User Settings and Details

                                    Change Password

                                    Change Primary House

                            {!! Form::close() !!}

@stop

And this is my routes file

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
 */

//Home Routes

Route::get('/', 'HomeController@index');
Route::get('home', 'HomeController@index');

//User Routes

Route::post('user/{id}/cprimary',['as' => 'user.cprimary', 'uses' => 'UserController@changeprimary']);
Route::get('user/changeprimary',['as' => 'user.changeprimary', 'uses' => 'UserController@showcp']);
Route::get('user/changepassword', 'UserController@changepassword');
Route::any('user/cpassword',['as' => 'user.cpassword', 'uses' => 'UserController@cpassword']);
Route::resource('user','UserController');
//House Routes

Route::get('createfirsthouse', 'CreateFirstHouseController@index');
Route::get('/house/alternate', 'HouseController@alternate_index');
Route::resource('house', 'HouseController');

//Google Routes
Route::get('googlemap', 'GoogleMapsTest@index');

//Profile Routes

Route::resource('profile', 'ProfileController');
Route::get('profile/resetpassword', 'ProfileController@resetpassword');

//Route to reverse schemas and get migrations.

//Route::get('tc', 'TController@index');

//Any Controller Routes not covered above

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

Route::get('/dash', 'DashController@index');
Route::get('/', 'DashController@index');
Route::get('/temp', 'TempReset@index');
Route::resource('dash', 'DashController');

Ok the correct answer was changing the controller, not sure why I was adding both options for the form::open, I saw on laracasts and assumed it to be the standard.
    public function changeprimary($id)
    {

        // Get the current users ID
        $users= Auth::id();

        // Fetch all houses linked to user and loop through collection setting primary to 0
        $allhouses=House::where('user_id', $users)->get();
        foreach($allhouses as $all) {
            $all->primary = '0';
            $all->save();
        }

        //        Retrieve the selected input
        $houses = Input::get('primary');

//        Find house linked to ID
        $house = House::find($houses);
        $house->primary = '1';
        $house->save();
        return redirect('user')->with('message', 'House '.$house->h_name.' is primary');
}

That was the correct code I needed to solve this :)


text:
Q: node-windows not installing as windows service We are trying to install the Node JS app as service in one of the server but when we run below script, it does not create the windows service. However, we were able to create windows service in another server using same script.
var Service = require('node-windows').Service;
console.log(" entered ");
// Create a new service object
var svc = new Service({
  name:'NodeJS App New',
  description: 'Node JS Application which converts Html String to PDF',
  script: 'S:\\HtmlToPdf\\MainApp.js',
  wait: 2,
  grow: .5
});
console.log(" entered 2 ");

console.log(" entered 3");
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
console.log(" entered install ");
  svc.start();
});

svc.install();
console.log(" completed ");

A: It's working after removing the space in service name as below
name:'NodeJSAppNew',


text:
Q: JPA annotation to do on-many mapping I am facing an issue while doing one-many mapping,
for e.g. I have a class USER and another class PHONE and there is one to many mapping from USER to PHONE.
I have designed my class like this,
class USER{

@Column(name="user_id")
UUID user_id;

@OneToMany
Set<PHONE> phones;
}

class PHONE{
@Column(name="phone_id")
UUID phone_id;

@Column(name=user_id)
UUID user_id;
}

Is there any annotation I can use without defining type of USER in phone class ?
If I do like this "USER user in PHONE class" then I can define uni or bi directional relationship. but I want to keep user_id in PHONE Table because when I get a PHONE I dont want to get USER details also. Thanks !

A: If you don't want to load the user when loading a phone, make the association lazy:
@Entity
public class User {
    ...

    @OneToMany(mappedBy = "user")
    private Set<Phone> phones;
}

@Entity
public class Phone
    ...

    @ManyToOne(fetch = FetchType.LAZY)
    private User user;
}

Note that the above code also respects the Java naming conventions. Classes should not be in all-uppercase.


text:
Q: NServiceBus - Type was not registered in the serializer - Fix? We are using NServiceBus in a web application and each time we deploy our code to production, we have to delete the Temporary Files in the folder:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

We are following the instructions here to fix this:
http://www.nservicebus.com/faq/TypeNotRegisteredInSerializer.aspx

I was wondering if there is a more permanent fix to this? I feel like I am fighting with this every time I deploy new code. What is the best way to handle this from code? If that doesn't work, is it best to just stop the application pools, delete the files, and restart the app pools every time I deploy new code?
Thanks for any advice.

A: Instead of using Configure.WithWeb(), try instead:
Configure.With(HttpRuntime.BinDirectory)

That way, it will search the actual bin folder in your deployed web application instead of the temporary folder. This is also the default behavior in nservicebus 3.0.

A: We've hit this too.  Haven't found anything better than stopping the app pools, deleting the temp asp.net files and then restarting.

A: What is the solution if you have some assemblies that should be ignored. We have something like this:
_bus = Configure.With(AllAssemblies.Except("IncompatibleAssembly.dll"))


text:
Q: Why is writing to I2C too slow in Python comparing to C? I am trying to find out why the same code in Python works 25 times slower than C even if I use CDLL, when I try to write into I2C. Below I will describe all the details what I am doing step by step.
The version of Raspberry PI: Raspberry PI 3 Model B
OS: Raspbian Buster Lite Version:July 2019
GCC version: gcc (Raspbian 8.3.0-6+rpi1) 8.3.0
Python version: Python 3.7.3
The device I am working with though I2C is MCP23017. All I do is writing 0 and 1 to the pin B0. Here is my code written in C:
// test1.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <time.h>

int init() {
    int fd = open("/dev/i2c-1", O_RDWR);
    ioctl(fd, I2C_SLAVE, 0x20);
    return fd;
}

void deinit(int fd) {
    close(fd);
}

void makewrite(int fd, int v) {
    char buffer[2] = { 0x13, 0x00 };
    buffer[1] = v;
    write(fd, buffer, 2);
}

void mytest() {
    clock_t tb, te;
    int n = 1000;

    int fd = init();

    tb = clock();
    int v = 1;
    for (int i = 0; i < n; i++) {
        makewrite(fd, v);
        v = 1 - v;
    }
    te = clock();

    printf("Time: %.3lf ms\n", (double)(te - tb) / n / CLOCKS_PER_SEC * 1e3);

    deinit(fd);
}

int main() {
    mytest();
    return 0;
}

I compile and run it with the command:
gcc test1.c -o test1 && ./test1

It gives me the result:
pi@raspberrypi:~/dev/i2c_example $ gcc test1.c -o test1 && ./test1
Time: 0.020 ms

I may conclude that writing to the pin takes 0.02 milliseconds.
After that I create SO-file to be able to access the written functions from my Python script:
gcc -c -fPIC test1.c -o test1.o && gcc test1.o -shared -o test1.so

And my Python script to test:
# test1.py

import ctypes
from time import time

test1so = ctypes.CDLL("/home/pi/dev/i2c_example/test1.so")

test1so.mytest()

n = 1000

fd = test1so.init()

tb = time()
v = 1
for _ in range(n):
    test1so.makewrite(fd, v)
    v = 1 - v
te = time()
print("Time: {:.3f} ms".format((te - tb) / n * 1e3))

test1so.deinit(fd)

This provides me the result:
pi@raspberrypi:~/dev/i2c_example $ python test1.py
Time: 0.021 ms
Time: 0.516 ms

I cannot understand why the call of makewrite is 25 times slower in Python though actually I call the same C-code. I also researched that if I comment write(fd, buffer, 2); in test1.c or change fd to 1, the times given by the Python script are compatible, there is no such huge difference.
// in test1.c
write(fd, buffer, 2); -> write(1, buffer, 2);

Running C-program:
pi@raspberrypi:~/dev/i2c_example $ gcc test1.c -o test1 && ./test1
...Time: 0.012 ms

Running Python-program:
pi@raspberrypi:~/dev/i2c_example $ python3 test1.py
...Time: 0.009 ms
...Time: 0.021 ms

It confused me a lot. Can anybody tell me why does it happen and how can I improve my performance in Python regarding the access via I2C using C-DLL?
Summary:
Descriptor: 1 (stdout)
Execution time of makewrite in C purely: 0.009 ms
Execution time of makewrite in C called as C-DLL function from Python: 0.021 ms
The result is expectable. This difference is not so high. It can be explained that Python loop and its statements are not as efficient as in C, thus it increases the execution time.
Descriptor: I2C
Execution time of makewrite in C purely: 0.021 ms
Execution time of makewrite in C called as DLL function from Python: 0.516 ms
After switching the file descriptor to I2C the execution time in pure C increased in around 0.012 ms, so I would expect the execution time for calling from Python: 0.021 ms + 0.012 ms = 0.033 ms, because all changes I've done are inside of makewrite, so Python is supposed not to know this internal thing (because it's packed in so-file). But I have 0.516 ms instead of 0.033 ms that confuses me.


text:
Q: Pandas resample based on start and end dates I have yearly data for electric vehicle charging and that has the total energy "energy (kwh)" for the charge duration. I also have the start charging time and the end charging time in "Y/m/d H:M:S" format. I am trying to create an average energy use column based on the total energy and the start and end times.
I thought I would need the pandas resample function as I have used it to create timed averages before but was not sure how to create a timed averaged between two times.

A: I don't think you need the pandas resample function. You can do it with some of pandas' more basic datetime functionality instead.
First, here's some toy data:
import numpy as np
import pandas as pd
np.random.seed(42)

start = pd.date_range("2021-04-21", periods=5, freq="H")
end = start + pd.to_timedelta(np.random.rand(len(start)), unit='h')
energy_total = 100 * np.random.rand(len(start))

df = pd.DataFrame({'start': start, 'end': end, 'energy_total': energy_total})

Now we can calculate the charge duration as a Timedelta and convert that to a simple number with dt.total_seconds(). We should divide this by 3600 to get the time in hours, since the total energy is given in kWh. Then we can calculate the average energy flow (in kW) by dividing the total energy by this time:
charge_timedelta = df.end - df.start
charge_hours = charge_timedelta.dt.total_seconds() / 3600

df['energy_flow'] = df.energy_total / charge_hours
df.round(2)

    start                end                  energy_total  energy_flow
0   2021-04-21 00:00:00  2021-04-21 00:22:28  15.60          41.65
1   2021-04-21 01:00:00  2021-04-21 01:57:02   5.81           6.11
2   2021-04-21 02:00:00  2021-04-21 02:43:55  86.62         118.33
3   2021-04-21 03:00:00  2021-04-21 03:35:55  60.11         100.41
4   2021-04-21 04:00:00  2021-04-21 04:09:21  70.81         453.84


text:
Q: Какие используете плагины для профилирования в Visual Studio Code? Нужно выявлять узкие места в коде (в основном Python) , какие функции дольше всего работают, чаще вызываются, сколько жрут памяти и процессора, желательно с графиками

A: cProfile, если говорить о библиотеках. Я ограничиваюсь сохранением его вывода в файл. И там смотрю.


text:
Q: How do I Prevent Beachball in Subprocess I am trying to run various subprocesses in Python, but I always get a beachball.
I have a Menu in Tkinter from where I select, via a button, which process to run. Nevertheless, regardless of the process I choose I am just getting a beachball and the menu freezes.
# Import Libraries
import sys
import pandas as pd
import time
import subprocess
import tkinter as tk

# Initialize tkinter
window = tk.Tk()
# Set window title
window.wm_title("")
window.geometry("600x800")

# Create Title
label_a = tk.Label(master=window, text="IM Web Scarper", fg="black", bg="light green", height=2, width=15,
                   relief=tk.GROOVE, borderwidth=3)
label_a.place(x=225, y=10)

# Label color run/success or error
def scrape_label(color, y_coord):
    # Create frame color indicates running and success
    label_scraper = tk.Label(master=window, text="", bg=color, height=1, width=4, relief=tk.GROOVE,
                             borderwidth=3)
    label_scraper.place(x=350, y=y_coord)

# Exit GUI
def click_exit_button():
    exit()

# Run Stock Scraper after button pressed
def run_stock_scraper():
    print("\n Scraper Running")
    process_stock_scrape = subprocess.Popen([sys.executable, "stock_scrape.py"])
    process_stock_scrape.wait()
    error_code = process_stock_scrape.returncode

    if error_code == 0:
        print("Process OK, return code = 0")
        scrape_label("green", 150)

    else:
        print("Process crashed, return code =", error_code)
        print(process_stock_scrape.stderr)
        scrape_label("red", 150)

    return error_code

# Run Stock Sort after button pressed
def run_stock_sort():
    print("\n Running Stock Sort")
    try:
        subprocess.Popen([sys.executable, "stock_sort.py"])
        scrape_label("green", 200)
    except Exception:
        scrape_label("red", 200)
        print("error")
    return

# Run SPD Prices after button pressed
def run_spd_prices():
    print("\n Running SPD Price Retrieve")
    try:
        subprocess.Popen([sys.executable, "spd_prices.py"])
        scrape_label("green", 250)
    except Exception:
        scrape_label("red", 250)
        print("error")
    return

# Run WEI Prices after button pressed
def run_wei_prices():
    print("\n Running WEI Price Retrieve")
    try:
        subprocess.Popen([sys.executable, "wei_prices.py"])
        scrape_label("green", 300)
    except Exception:
        scrape_label("red", 300)
        print("error")
    return

# Run Cat Scrape after button pressed
def run_cat_scrape():
    print("\n Running Category Scrape")
    try:
        subprocess.Popen([sys.executable, "cat_scrape.py"])
        scrape_label("green", 350)
    except Exception:
        scrape_label("red", 350)
        print("error")
    return

# Run Img Scrape after button pressed
def run_img_scrape():
    print("\n Running Image Scrape")
    try:
        subprocess.Popen([sys.executable, "img_scrape.py"])
        scrape_label("green", 400)
    except Exception:
        scrape_label("red", 400)
        print("error")
    return

# Run Desc Scrape after button pressed
def run_desc_scrape():
    print("\n Running Description Scrape")
    try:
        subprocess.Popen([sys.executable, "desc_scrape.py"])
        scrape_label("green", 450)
    except Exception:
        scrape_label("red", 450)
        print("error")
    return

# Run Price Calculation button pressed
def run_price_calc():
    print("\n Running Price Calculation")
    try:
        subprocess.Popen([sys.executable, "price_calc.py"])
        scrape_label("green", 500)
    except Exception:
        scrape_label("red", 500)
        print("error")
    return

# Run Shipping Data Fix after button pressed
def run_ship_data():
    print("\n Running Ship Data Fix")
    try:
        subprocess.Popen([sys.executable, "ship_data.py"])
        scrape_label("green", 550)
    except Exception:
        scrape_label("red", 550)
        print("error")
    return

# Run Category Fix after button pressed
def run_cat_fix():
    print("\n Running Category Fix")
    try:
        subprocess.Popen([sys.executable, "cat_fix.py"])
        scrape_label("green", 600)
    except Exception:
        scrape_label("red", 600)
        print("error")
    return

# Run Table Merge after button pressed
def run_merge_table():
    print("\n Running Table Merge")
    try:
        subprocess.Popen([sys.executable, "merge_table.py"])
        scrape_label("green", 650)
    except Exception:
        scrape_label("red", 650)
        print("error")
    return

# Run Stock Sort 2 after button pressed
def run_stock_sort_2():
    print("\n Running Stock Sort Final")
    try:
        subprocess.Popen([sys.executable, "stock_sort_2.py"])
        scrape_label("green", 700)
    except Exception:
        scrape_label("red", 700)
        print("error")
    return

# Runs all other scripts
def inventory_logic():
    try:
        run_stock_sort()
        time.sleep(2)

        # Import CSV missing data
        print("\n Determine Missing Data")
        data_df = pd.read_csv('/Users/manuel/Desktop/PCMaxx DB/LIVE_DATA/missing_data/missing_data.csv')
        data_df = pd.DataFrame(data_df)
        print(data_df)
        data_list = data_df['missing_data'].to_list()
        # print(data_list)
        desc_data = data_list[0]
        cat_data = data_list[1]
        img_data = data_list[2]
        prc_data = data_list[3]
        # print(desc_data, cat_data, img_data, prc_data)

        if prc_data > 0:
            run_spd_prices()
            time.sleep(2)
            run_wei_prices()
            time.sleep(2)
            run_price_calc()
            time.sleep(2)
        else:
            print("No new prices")

        if cat_data > 0:
            run_cat_scrape()
            time.sleep(2)
            run_cat_fix()
            time.sleep(2)
        else:
            print("No new categories")

        if img_data > 0:
            run_img_scrape()
            time.sleep(2)
        else:
            print("No new images")

        if desc_data > 0:
            run_desc_scrape()
            time.sleep(2)
            run_ship_data()
            time.sleep(2)
        else:
            print("No new descriptions")

        if desc_data or img_data or cat_data > 0:
            run_merge_table()
            time.sleep(2)

        run_stock_sort_2()
        print("Finished Process")

    except Exception:
        scrape_label("red", 75)

    return

# Run Stock Sort 2 after button pressed
def run_inventory_scraper():
    print("Running Main Inventory Scraper")
    # Clear labels
    scrape_label("white", 150)
    scrape_label("white", 200)
    scrape_label("white", 250)
    scrape_label("white", 300)
    scrape_label("white", 350)
    scrape_label("white", 400)
    scrape_label("white", 450)
    scrape_label("white", 500)
    scrape_label("white", 550)
    scrape_label("white", 600)
    scrape_label("white", 650)
    scrape_label("white", 700)

    # Run Inventory logic
    try:
        scrape_error = run_stock_scraper()
        print(scrape_error)
        time.sleep(2)
        if scrape_error == "0":
            inventory_logic()
        elif scrape_error == "1":
            print("houston we have a problem")
            exit()
    except Exception:
        print("Exception error")

# Create Main Run Button, link it to run_inventory_scrape()
web_scraper_button = tk.Button(height=2, width=20, text="Run Main Inventory Scraper", fg="blue", bg="light blue",
                               command=run_inventory_scraper, relief=tk.GROOVE, borderwidth=3)
web_scraper_button.place(x=150, y=75)

# Create button, link it to click_Exit_Button()
exitButton = tk.Button(window, text="Exit", height=2, width=5, fg="red", bg="yellow", command=click_exit_button,
                       relief=tk.GROOVE, borderwidth=3)
exitButton.place(x=50, y=30)

# Create Stock Scraper Button, link it to run_stock_scraper()
web_scraper_button = tk.Button(height=2, width=20, text="Run Stock Scraper", fg="green", bg="light blue",
                               command=run_stock_scraper, relief=tk.GROOVE, borderwidth=3)
web_scraper_button.place(x=150, y=150)

# Create Stock Sort Button, link it to run_stock_sort()
stock_sort_button = tk.Button(height=2, width=20, text="Run Stock Sort", fg="green", bg="light blue",
                              command=run_stock_sort, relief=tk.GROOVE, borderwidth=3)
stock_sort_button.place(x=150, y=200)

# Create SPD Prices Retrieval Button, link it to run_SPD_prices()
SPD_button = tk.Button(height=2, width=20, text="Run SPD Prices", fg="green", bg="light blue", command=run_spd_prices,
                       relief=tk.GROOVE, borderwidth=3)
SPD_button.place(x=150, y=250)

# Create WEI Prices Retrieval Button, link it to run_WEI_prices()
WEI_button = tk.Button(height=2, width=20, text="Run WEI Prices", fg="green", bg="light blue", command=run_wei_prices,
                       relief=tk.GROOVE, borderwidth=3)
WEI_button.place(x=150, y=300)

# Create Category Scraper Button, link it to run_cat_scrape()
cat_button = tk.Button(height=2, width=20, text="Run Category Scrape", fg="green", bg="light blue",
                       command=run_cat_scrape, relief=tk.GROOVE, borderwidth=3)
cat_button.place(x=150, y=350)

# Create Image Scraper Button, link it to run_img_scrape()
img_button = tk.Button(height=2, width=20, text="Run Image Scrape", fg="green", bg="light blue", command=run_img_scrape,
                       relief=tk.GROOVE, borderwidth=3)
img_button.place(x=150, y=400)

# Create Description Scraper Button, link it to run_desc_scrape()
desc_button = tk.Button(height=2, width=20, text="Run Description Scrape", fg="green", bg="light blue",
                        command=run_desc_scrape, relief=tk.GROOVE, borderwidth=3)
desc_button.place(x=150, y=450)

# Create Price Calculation Button, link it to run_price_calc()
price_calc_button = tk.Button(height=2, width=20, text="Run Price Calculation", fg="green", bg="light blue",
                              command=run_price_calc, relief=tk.GROOVE, borderwidth=3)
price_calc_button.place(x=150, y=500)

# Create Shipping Data Button, link it to run_ship_data()
ship_button = tk.Button(height=2, width=20, text="Run Ship Data Fix", fg="green", bg="light blue",
                        command=run_ship_data, relief=tk.GROOVE, borderwidth=3)
ship_button.place(x=150, y=550)

# Create Category Fix Button, link it to run_cat_fix()
cat_fix_button = tk.Button(height=2, width=20, text="Run Category Fix", fg="green", bg="light blue",
                           command=run_cat_fix, relief=tk.GROOVE, borderwidth=3)
cat_fix_button.place(x=150, y=600)

# Create Merge Table Button, link it to run_merge_tables()
merge_table_button = tk.Button(height=2, width=20, text="Run Merge Table", fg="green", bg="light blue",
                               command=run_merge_table, relief=tk.GROOVE, borderwidth=3)
merge_table_button.place(x=150, y=650)

# Create Stock Sort Button, link it to run_stock_sort_2()
stock_sort_button_2 = tk.Button(height=2, width=20, text="Run Final Stock Sort", fg="green", bg="light blue",
                                command=run_stock_sort_2, relief=tk.GROOVE, borderwidth=3)
stock_sort_button_2.place(x=150, y=700)

# Run Inventory Scrape
# Show window
window.mainloop()

# Run Clock
# app = tk.(window)
# window.wm_title("Tkinter clock")
# window.geometry("50x50")
# window.after(1000, app.update_clock)

# Text entry
# new_label = tk.Label(text="Text entry")
# entry = tk.Entry()
# new_label.pack()
# entry.pack()

# retrieve = ""
# while retrieve == "":
# retrieve = entry.get()

# print(retrieve)

# print("retrieved")
# entry.insert(0, "hola")

# text_box = tk.Text()
# text_box.pack()

# frame = tk.Frame(master=window, relief=tk.GROOVE, borderwidth=3)
# frame.pack()

This is the code I am running, I have been trying to use try, except and other ways of managing to run this code without my menu getting frozen.
What I wish to do is get the subprocess running, and while it runs be able to press other buttons and run different things. If the subprocess that is running for some reason runs into an exception, I would like to get the code, and text for the exception and have it on screen ( BTW I am using Pycharm), all this while I am still being able to access my Tkinter menu.
Any help is welcome,
Thanks
Manolo


text:
Q: OnKeyEvent without focus in Jetpack Compose I am creating an app that makes use of a physical button on the device.
This button will have a different functionality depending on the screen that is active.
With Activities what I would do would be to have an Activity for each screen and in each one I would override the onKeyDown function. How would I do this with a single activity that navigates between different Jetpack Compose screens?
According to the Android documentation the correct way would be something like this...
Box(modifier = Modifier
    .onKeyEvent {
        Log.e("Pressed", it.nativeKeyEvent.keyCode.toString())
        true
    }
    .focusable()
    .fillMaxSize()
    .background(Color.Gray)
) {
    // All screen components
}

But this only works when one of the elements on the screen is focused and what I require is that it always works or not, is there a way to achieve this?

A: One option is to keep the focus on the view so that the Modifier.onKeyEvent always works. Note that it may conflict with other focusable views, like TextField, so all these views should be children(at any level) of this always-focusable view.
val focusRequester = remember { FocusRequester() }
var hasFocus by remember { mutableStateOf(false) }
Box(
    Modifier
        .focusRequester(focusRequester)
        .onFocusChanged {
            hasFocus = it.hasFocus
        }
        .focusable()
        .onKeyEvent {
            TODO()
        }
) {
}
if (!hasFocus) {
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}

Another option is to create compositional local handlers and pass events from your activity:
class MainActivity : AppCompatActivity() {
    private val keyEventHandlers = mutableListOf<KeyEventHandler>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            CompositionLocalProvider(LocalKeyEventHandlers provides keyEventHandlers) {
                // your app
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return keyEventHandlers.reversed().any { it(keyCode, event) } || super.onKeyDown(keyCode, event)
    }
}

val LocalKeyEventHandlers = compositionLocalOf<MutableList<KeyEventHandler>> {
    error("LocalKeyEventHandlers is not provided")
}

typealias KeyEventHandler = (Int, KeyEvent) -> Boolean

@Composable
fun ListenKeyEvents(handler: KeyEventHandler) {
    val handlerState = rememberUpdatedState(handler)
    val eventHandlers = LocalKeyEventHandlers.current
    DisposableEffect(handlerState) {
        val localHandler: KeyEventHandler = {
            handlerState.value(it)
        }
        eventHandlers.add(localHandler)
        onDispose {
            eventHandlers.remove(localHandler)
        }
    }
}

Usage:
ListenKeyEvents { code, event ->
    TODO()
}


text:
Q: Why is there no completion pop-up for XML files? I've made some SublimeText snippets and completions for XML. While all completions work, SublimeText (I'm using v3) never shows the completion pop-up like it does with other file types. How can I enable this behaviour?

A: Try adding the following to your user preferences (Preferences -> Settings-User):
"auto_complete_selector": "source, meta.tag, text.xml"

This enables autocompletion in all source code files (Python, Ruby, etc.), in HTML/XML tags, and anywhere in XML documents.
Good luck!


text:
Q: Constructing an Infinite Family of Graphs In a number of graph theory books that I am working through I come across questions that ask something like $\textit{'Construct an infinite}$ $\textit{family of graphs with _________'}$  and state some property in the blank space that the family of graphs have to satisfy. These questions totally stump me, so my question is what, if any, is a good method of attack for these types of questions? Also what is a 'solution' to these questions meant to look like?
As an example, I am currently trying to work through the following problem from John Meier's book $\textit{Groups, Graphs and Trees; An Introduction to the Geometry of Infinite Groups}$ that asks:

Construct infinitely many distinct (2,3)-biregular graphs

In this case I understand what a biregular graph is and can construct a number of distinct graphs by hand, however, I don't understand how to generalise it to get infinitely many distinct graphs of this type.

A: If you want to construct infinitely many graphs, you want to construct arbitrarily large graphs with the given property. A straightforward approach to try would be to try to find an $n$-vertex graph for any $n$.
This might not always work, because not all values of $n$ are valid. An infinite family also lets you skip values of $n$ that don't work, as long as you still have $n$-vertex graphs for infinitely many $n$. For example:

*

*If you were looking for examples of $10$-regular graphs, you would not be able to find any for fewer than $11$ vertices. It's okay to skip $n=1, 2,\dots, 10$.

*If you were looking for examples of $3$-regular graphs, you would not be able to find any for an odd number of vertices. It's okay to only take $n=2, 4, 6, 8, \dots$.

*Even finding a graph of some type with, say, $2^{2^k}$ vertices for each $k$ is still an infinite family, as long as any sufficiently large $k$ works.

In your case, there's a simple restriction: a $(2,3)$-biregular graph has $3k$ vertices on one side, and $2k$ vertices on the other, for some $k$. So you might try to find an example of a $5k$-vertex $(2,3)$-biregular graph for each $k$, and that would give an infinite family.
(Or you might discover another restriction, specify which values of $n$ work more precisely, and try again.)
In some cases, part of the challenge might be describing how you actually get the example. This would look like an algorithm: given $k$, here is how you construct a $5k$-vertex graph with the property we want.

A: The answer to your problem is quite easy. Just observe that if $K_{2,3}$ is the $(2,3)$-biregular graph with $5$ vertices then the distinct union of $n$ $K_{2,3}$ is a $(2,3)$-biregular graph with $5n$ vertices.
A more general way to attack the problem, where you can see the heuristics is the following:
Let $G=(V,E)$ be a $(2,3)$-biregular graph with parts $B$ and $C$, where $\forall b\in B \ \deg_G b=2$ and $\forall c\in C \ \deg_G c=2$. It is easy to see that $2|B|=3|C|$. Indeed, we can count the number of edges of $G$ in two different ways as follows: the number of edges of $G$ that are incident to some vertex in $B$ is equal to $2|B|$, while the number of edges of $G$ that are incident to some vertex in $C$ is equal to $3|C|$. Hence, since every edge of $G$ is between a vertex in $B$ and a vertex in $C$ we have the equality, i.e. $2|B|=|E|=3|C|$. It is easy to solve this Diophantine equation. We get that $|B|=3n$ and $|C|=2n$ for some positive integer $n$.
Therefore, you have restricted considerably the problem of finding $(2,3)$-biregular graphs to bipartite graphs of parts of sizes $3n$ and $2n$ respectively.
This example is not so interesting as it has an easy solution but in general, the strategy to tackle this kind of problems is to gradually restrict the structure of the graph being considered. In many of these problems a nice way to construct the family of graphs is by induction. This example hides an induction in the construction of the graphs, but it is a trivial one!

A: The question in your first paragraph is way too broad; it's almost like asking "How do I find a graph that satisfies some given conditions?" The difference is, you're asking "How do I find a graph that satisfies some given conditions, where one of the conditions is 'has more than $n$ vertices'?" The question is unanswerable because what gives the problem its flavor is not the part about having more than $n$ vertices, it's the other conditions. If you ask such a general question, the best you can expect is a very general answer, like "Think hard about it."
Your question about $(2,3)$-biregular graphs is the kind we can deal with here. As stated, it's too easy: just consider the graph $nK_{3,2}$, the union of $n$ vertex-disjoint copies of the complete bipartite graph $K_{3,2}$. To make it a little more interesting, lets ask for large connected $(2,3)$-biregular graphs. There are still lots of solutions. Here's one:
Draw an $n\times n$ chessboard, $n\ge3$. Divide each little square into two triangles by drawing a diagonal. Make the chessboard into a torus by identifying the left side with the right side and the top with the bottom. Now each of the $2n^2$ triangles has $3$ sides, and each of the $3n^2$ edges is a side of $2$ triangles, so the triangle-edge incidence graph is a $(3,2)$-biregular graph of order $5n^2$.


text:
Q: How to access in-memory h2 database from Intellij IDEA In Spring Boot project I am trying to see in-memory tables from my IDE.

How to access in-memory h2 database from Intellij IDEA.

Here is a snippet from my application.yml:
 h2:
    datasource:
        url: jdbc:h2:mem:mydb
        username: username
        password: 123
        driver-class-name: org.h2.Driver
        init-sql: h2.sql
    console:
      enabled: true
      path: /search/console
      settings:
        trace: false
        web-allow-others: false

Intellij has no field to input username for in-memory database:

Test Connection shows success, however it doesn't see tables from h2.sql.
I can access them using h2 console.

A: Just please bear in mind this may show you the db but not the table as they will only be visible in the h2 console. For you to access them through IntelliJ you may need to change the url and connection to be of a file type rather than in memory.
So instead of this:
#spring.datasource.url=jdbc:h2:mem:testdb

You'd have something like this:
spring.datasource.url=jdbc:h2:file:~/Users/yourUser/IdeaProjects/resume-portal/src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE

And then after creating a datasource from url

You should now see both the database and its tables.

And that will still also be available from the console if you connect using the new url.

PS: If'd prefer to use a relative path you can change the url to be something similar to jdbc:h2:file:./src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
Here is the application.yml file for the application.
spring.jpa.defer-datasource-initialization=true
#spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.url=jdbc:h2:file:./src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always

A: By the default, IntellJ doesn't show any of database.

*

*right click at the datasource then choose Properties

*At the Schemas tab, you'll see a list of options to choose which database should be shown (I normally choose All databases). Choose the database which you need it to be shown

The result:

A: I found another way. I created the H2 Server bean and added it to my SpringBoot Application. It looks like this:
// Start internal H2 server so can query from IDE
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
    return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}

I also had the following on my application.properties
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.defer-datasource-initialization=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

spring.sql.init.mode=always

# Initialise H2 with H2GIS for spatial support ? see schema-h2.sql also
spring.sql.init.platform=h2
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
h2.tcp.enabled=true

In order to get my data.sql put into the tables in Intellij I had to make sure I used create-drop and added the spring.sql.init.mode=always
Note: I was using the H2GIS dialect - but this has not so far caused any issues
The connection setup in Intellij was still remote with this string jdbc:h2:tcp://localhost:9092/mem:testdb - dont forget to change the port to 9092

I the connection window in Intellij I also checked all tables under Schema. Then the tables are present for the H2 in mem database.


text:
Q: Lava Lamp navigation jQuery Firefox I'm experiancing a weird problem with my lava lamp navigation. It's adapted after Jeffrey Way's Lava lamp tutorial.
 The code for the lava lamp is at the bottom. Problems appear mainly in firefox (I'm using FF6) but occationally also in Chrome and Safari (but not IE9): The orange line above the menu item sometimes is too long and too much to the right when a page is loaded. When I hover over the item then it centers over it and stays there like it should from the beginning.
Any ideas why that happens? Something weird with position().left and outerWidth()?
Feedback very appreciated!
(function($) {
$.fn.spasticNav = function(options) {
    options = $.extend({
        speed: 500,
        reset: 1500,
        color: '#F29400',
        easing: 'easeOutExpo'
    }, options);

    return this.each(function() {

        var nav = $(this),
                currentPageItem = $('#active', nav),
                stroke,
                reset;

        $('

').css({
            width: currentPageItem.outerWidth(),
            height: 4,
            margin: 0,
            left: currentPageItem.position().left,
            top: currentPageItem.position().top,
            backgroundColor: options.color
        }).appendTo(this);
        stroke = $('#stroke', nav);

        $('a:not(#stroke)', nav).hover(function() {
                    // mouse over
                    clearTimeout(reset);
                    stroke.animate(
                            {
                                left : $(this).position().left,
                                width : $(this).width()

                            },
                            {
                                duration : options.speed,
                                easing : options.easing,
                                queue : false
                            }
                    );

                }, function() {
                    // mouse out
                    reset = setTimeout(function() {
                        stroke.animate({
                            width : currentPageItem.outerWidth(),
                            left : currentPageItem.position().left
                        }, options.speed)
                    }, options.reset);

                });
    });
};
})(jQuery);

A: I had the same issue. Try to use jquery trick:
$(document).ready(function(){ bla bla bla });

or if you prefere:
$(window).load(function(){ bla bla bla });

Add this before the function where you call the main java script of the lava menu, like this:
$(window).load(function(){$('#topmenu_ul').spasticNav();});

A: I had the same issue.
The problem is due to the exact moment in which the browser loads the font-face:

IE will download the .eot file immediately when it encounters the @font-face declaration.
Gecko (so, Firefox), Webkit, and Opera all wait until they encounter HTML that matches a >CSS rule with a fontstack including the @font-face font.

I suppose you have the font-face declaration in CSS body statement, aplying it to the entire page, and you have your lavaLamp statement in the jQuery(document).ready() event, in the way:
jQuery(document).ready(function() {
   jQuery('.ha-main-menu ul').lavaLamp({startItem: 3});
});

so, when lavaLamp plugin is created, body css is still not applied, and the calculations about size-positioning are wrong, they refer to old font, before font-face is applied.
As you can see in this question How to know when font-face has been applied , one solution is to call lavaLamp in event onreadystatechange, waiting until the document.readystate === 'complete', in the way:
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        jQuery('.ha-main-menu ul').lavaLamp({startItem: 3});
    }
}

so, lavaLamp is launched after the font-face is loaded, so the size-position methods used inside the lavaLamp plugin will be the correct ones.


text:
Q: Why new shapefile is not appearing in QGIS? In QGIS 3.24.2 I have just opened a new project and when I add a new shapefile layer it brings up a box saying that the layer already exists and asking if I want to overwrite it. However, I haven't added anything or changed anything.
The projection is set to the default EPSG:4326 and I am almost certain this is compatible with the shapefile, however when I click Yes to overwrite nothing appears. I've tried zooming to layer but still, absolutely nothing appears on the screen.
How can I fix it?


text:
Q: Predefined feature selection from pandas dataframe as part of a sklearn gridsearch crossvalidation TLDR: How to iterate through predefined feature subsets as part of a scikit-learn gridsearchcv pipeline?
For a regression task, I have set up a (nested) CV to chose and evaluate models for a given pandas dataframe model_X (all numerical columns, no missing data) and a target pandas series model_y.
My goal is to combine feature selection and hyperparameter tuning. However, for my purpose I do not want to use any of sklearn's feature selection algorithms, instead I simply want to try different predefined subsets of the available columns and get them tested against each other (and of course in all combinations with the other hyperparameters) in the CV.
For this purpose I have a list of tuples feature_candidates_list, where each tuple contains certain column names from model_X to be used together as features.
To achieve this I am using Functiontransformer like so:
def SelectFeatures(model_X, feature_set, feature_sets=feature_candidates_list):
    return model_X.loc[:, feature_sets[feature_set]]

CustomFeatureSelector = FunctionTransformer(SelectFeatures, feature_names_out='one-to-one')

And here is how I put all together in a pipeline and param grid (this is a reduced example for only the relevant steps):
PreProcessor = ColumnTransformer([
      ('selector', CustomFeatureSelector, model_X.columns),
      ('scaler', StandardScaler(), make_column_selector(dtype_include=np.number)),
      ])

pipe = Pipeline(steps=[
    ('preprocessor', PreProcessor),
    ('regressor', DummyRegressor())  # just a dummy here, as it can't be empty (actual regressor see regressor_params)
    ])

preprocessor_params = [
    {
      'preprocessor__selector__kw_args': [{'feature_set':i} for i in range(len(feature_candidates_list))],
      'preprocessor__scaler__with_mean': [True, False],
      'preprocessor__scaler__with_std': [True, False],
    },
]

regressor_params = [
    {
     'regressor': [TweedieRegressor(max_iter=1000)],
        'regressor__power': [0, 1],
        'regressor__alpha': [0, 1],
        'regressor__link': ['log'],
        'regressor__fit_intercept': [True, False],
    },
]

params = [{**dict_pre, **dict_reg} for dict_reg in regressor_params for dict_pre in preprocessor_params]

Finally, to run the model selection and evaluation I use:
scoring = {
    'R2': 'r2',
    'MAPE': 'neg_mean_absolute_percentage_error',
    'MedAE': 'neg_median_absolute_error',
    'MSLE': 'neg_mean_squared_log_error',
  }
refit_scorer = 'R2'

with parallel_backend('loky', n_jobs=-1):
    innerCV = GridSearchCV(
        pipe,
        params,
        scoring= scoring,
        refit= refit_scorer,
        cv=10,
        verbose=1,
        )

    outerCV = cross_validate(
        innerCV,
        model_X,
        model_y,
        scoring=scoring,
        cv=10,
        return_estimator=True,
        verbose=1,
        )

I am not sure if this pipeline actually selects the features as intended.

*

*model_X has m columns

*every tuple in feature_candidates_list contains n column names  (n < m, of course).

What I did to check on a single outer fold's best estimator is:
outerCV['estimator'][0].best_estimator_.named_steps['regressor'].n_features_in_

which gives me m + n but I expected n (also tested it for the other folds).
I think there must be something wrong in how I put together my preprocessor. It seems like it is taking all original columns of model_X and concatenates them with the chosen set of columns instead of replacing. When I switch off the scaler the output of the above is in deed equal to n, however, I still cannot see which features were chosen for a respective estimator because calling .feature_names_in_ on them raises:
AttributeError: 'TweedieRegressor' object has no attribute 'feature_names_in_'
Maybe the whole way I approach this selection of features in gridsearchcv is not smart and I should go a different route? Any hints welcome!
Update:
I switched to sklearn nightly (v1.2.dev0) where I can use set_config(transform_output='pandas') to avoid getting my dataframe converted to a numpy array by transformers. This helps to get feature names when calling the .feature_names_in_ on one of the estimators but it only works when I have just the scaler activated.
When I also activate my custom selector the fitting fails for all folds. But when I turn off the set_config(...) again, it works just like in the stable versions v1.1.2 and v1.1.3 without ability to get feature names.


text:
Q: Service Broker activation procedure in C# with external dependencies I am not entirely sure if I have come to the right place, because this question involves both SQL Server and .Net. Apologies if this is not an appropriate place for my question!
I am currently working on an in-house tool to transfer data from our
ERP system to our SharePoint. Specifically, my boss wants the closing
of a project in the ERP system to trigger a workflow in SharePoint.
My current line of thinking is to use the SQL Server Service Broker -
create a T-SQL trigger on the projects table in the ERP database to
send a message whenever a project is closed. The message would like
carry an XML payload with some information on the project.
I have done something very similar before, so that should not be too
much of a problem.
In the next step I would have to receive these messages, extract the
information from the XML payload and create entries in a list in our
SharePoint server.
Adding items to a SharePoint list from a C# program is also something
I have done before, so that should not be a problem either.
My question is how I should approach the transfer from the Service
Broker Message Queue to the SharePoint list.
My first idea was to write a stored procedure in C# to receive
messages from the queue, extract the relevant information from the XML
payload, and then create a list item SharePoint. (Stored procedures in C# is not something I have done before!)
As far as I could find out, this should not be a problem per
se. However, it would require access to the SharePoint client
assemblies from the stored procedure.
Also, I would like to do some logging, and being a lazy slob, I would
like to use Log4Net for that. So I would need access to two
assemblies. (More actually, I think the SharePoint client library is
split up into several assemblies.)
Can I just load these assemblies into the SQL Server along with the
one for my stored procedure, and then reference them from within the
SQL Server? If so, are there any pitfalls, things I need to keep in
mind?
Or can I just install the required assemblies on the database server
and reference them from within my stored procedure?
Another option just comes to my mind - I could use Fody Costura, I
think, to massage the additional assemblies into the one carrying my
stored procedure... Are there any significant downsides to this?
The alternative, of course, would be a program running externally from
the SQL Server. This seems in some ways to be a better alternative -
the problem with the SharePoint and Log4Net assemblies
disappears. Also, I could deploy the resulting program on an arbitrary
machine.
In that case, though, I am not sure how to interact with the Service
Broker and the Message queue. Can I just issue a RECEIVE statement via
an SqlCommand instance and extract the fields like from a regular
SELECT statement?
Would I have to finish the conversation? I have found some hints to a
Service Broker API, but where do I get the assemblies?
So, my questions, in short, are:
- Can I reference other assemblies from a CLR stored procedure?
- I so, how? What are the pros and cons?
- If now, how do I speak to the Service Broker from an external
  program? Do I need other assemblies besides the SQL Server Client?
Thank you very much for any insight you might be able to share with
me,
Benjamin

A: I suggest external activation rather than SQLCLR. That will provide capabilities like log4net that aren't easily doable in SQLCLR.
The trigger would begin a conversation and sends the project closure message.  The C# app would RECEIVE the closure message from the queue, do the SharePoint stuff, and end the conversation.  You'll also need to close the initiator side of the conversation to avoid endpoint leakage. Below is a single-queue example with the same SB service acting in both initiator and target roles.  Note that your C# will receive EndDialog messages for both sides of the conversation with this method.
CREATE QUEUE dbo.ProjectClosureQueue;
CREATE MESSAGE TYPE ProjectClosureRequest
    VALIDATION = WELL_FORMED_XML;
CREATE CONTRACT ProjectClosureContract (
      ProjectClosureRequest SENT BY INITIATOR
    );
CREATE SERVICE ProjectClosureService
    ON QUEUE dbo.ProjectClosureQueue ([ProjectClosureContract]);
GO

Trigger code snippet:
DECLARE @ProjectClosureConversationHandle  uniqueidentifier;
BEGIN DIALOG CONVERSATION @ProjectClosureConversationHandle
    FROM SERVICE ProjectClosureService
    TO SERVICE 'ProjectClosureService', 'CURRENT DATABASE'
    ON CONTRACT ProjectClosureContract
    WITH ENCRYPTION = OFF;
SELECT @ProjectClosureConversationHandle;

SEND ON CONVERSATION @ProjectClosureConversationHandle
    MESSAGE TYPE ProjectClosureRequest (@ProjectClosureXmlMessage);

Get next message in C# app:
WAITFOR (
    RECEIVE TOP (1)
           conversation_handle
           CAST(message_body AS xml)
        , message_type_name
    FROM dbo.ProjectClosureQueue
    ), TIMEOUT 10000;

If no message received, repeat receive.
If message_type is ProjectCloseRequest, do SharePoint stuff
If message_type is not ProjectCloseRequest or '"http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog', log error
Finally, END CONVERSATION


text:
Q: Is it possible to Import SonarQube rules? We're transferring our CI stack from a consulting company to in-house. We need to export the SonarQube profiles from the consultant's SQ instance to our corporate instance. We can export the profiles but the consultants created hundreds of custom rules and when we try to import the profile it fails to import the custom rules. We found in the API where you can export the rules to a JSON file, but can't find documentation on how to import them.
Is it possible to import SonarQube rules? What is the best way to go about that?
Referenced documentation:
SQ Docs - Copying Quality Profiles:
https://docs.sonarqube.org/display/SONAR/Quality+Profiles#QualityProfiles-CopyaprofilefromoneSonarQubeinstancetoanother
StackOverflow - How to export Rules:
How to extract or export rules from SonarQube
SQ API - Rules:   https://docs.sonarqube.org/pages/viewpage.action?pageId=2392166

A: Anyone trying to replicate rules from the server on their local setup-
For sonarqube community edition 8.7.1 you can simply export the custom rules as XML files.
Goto
Quality Profiles-> Gear Icon -> Backup
This will get you the custom rule in xml file format.

Then in your local setup goto
Quality Profiles-> Restore(top right corner)- select the XML file you downloaded in the previous step

A: It is not possible to import/export the logic of those custom rules, only their presence in a profile.
In the case of rules coded in Java, you must make them give you at least the jar containing the rule implementations. Once you install that jar (and restart your server) the rules will be available to you.
In the case of rules written in XPath, you must make them give you their XPath configurations, and you will need to re-create those XPath rules on your side (a tedious process of filling in a form once for each rule).


text:
Q: Electron Application changes height permanently when minimizing/maximizing This bug occurs when minimizing and maximizing the window of my application.
After every min-/maximizing the window becomes a few pixels shorter.
Here are images from before and after I repeated this process a few times.
Before &
After
Here is my code for creating the window:
app.on('ready', function(){
    const display = electron.screen.getPrimaryDisplay();
    const maxiSize = display.workAreaSize;

    mainWindow = new BrowserWindow({resizable: false,
                                    icon: "Media/Magnet_Icon.ico",
                                    height: maxiSize.height,
                                    width: maxiSize.width
                                    });

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'MagnetMain.html'),
        protocol: 'file:',
        slashes: true
    }));
});

Any Ideas how to fix this?


text:
Q: Question to "Start-up into resistive load" diagram of LTC3106 There is a diagram on page 7 of the LTC3106 (Datasheet) named "Start-up into resistive load" and i couldn't find any explanation on the internet how to understand it.
My assumption is:
This diagram shows what load is allowed at the output of the ltc3106 for a given Vin at start-up without getting any problems.
So this means: if i have 100Ohms load, the ltc might get problems at start-up with 3V Vin.
Is this right?

A: Your assumption is correct.   This chart describes the minimum resistance, using a 10uH Inductor, that will allow the converter to startup.  Otherwise it will not start or go into a protection mode.
Many microcontroller and system on a chip semiconductor loads are not resistive in nature and only start to draw significant current after they reach a certain voltage and go through a startup sequence.  If your load is a microcontroller or processor then you can adjust this startup time to allow the converter to start.


text:
Q: MVC allow an IIS default page in subfolder without breaking parent route I need to bypass an MVC route for an application where the developer left - we're going to fully replace it, but for now if I can bypass this one route, it'll save us a ton of time.
The route is (e.g.) www.this.site/path/subpath
Since it's on IIS, I can take advantage of the default document and create the following folder / file structure:  /path/subpath/index.htm
However if I do this, I'll "break" the parent www.this.site/path route (it throws a 403 - Forbidden: Access is denied) because I now have an actual file folder where the /path/ route was.
Is there a way to get around this / have IIS defer to MVC on /path/ but still handle the child html file?
thanks.  Again, this is not intended as a long term solution but a work-around until we can replace the app entirely.

A: Perhaps a better workaround would be to use the IIS AAR module and it's reverse proxy functionality out the app.
To do so:
a) stand up the app at it's own site the proper path -- so it should work at something like http://localhost:1234/path/subpath/index.htm
b) install IIS AAR module and enable the reverse proxy functions using the WebPI and the IIS management tools
c) Ignore the /path/subpath route in your app
d) Add a virtual directory for /path/subpath to IIS
e) Configure that to reverse back to localhost:1234 or whatever port you configured the site
This will keep the legacy app completely separate while keeping the public facing URLs looking correct for the rest of the world.


text:
Q: Download csv file from webpage after submitting form from dropdown using rvest package in R I am working on a webscraping project to download various csv files from this webpage: https://whalewisdom.com/filer/blue-harbour-group-lp#/tabholdings_tab_link
I would like to be able to programmatically choose the various reported quarters on the drop down list, hit submit (note that the URL for the page doesnt change for each different quarter) and then "Download CSV" for each of the quarters.
As a disclaimer, I am a novice to rvest and below is my attempt at the solution:

*

*I first checked this site and found a relevant post Using r to navigate and scrape a webpage with drop down html forms

*It looks like they use the following code to get a form for what the inputs need to be to refresh an HTML table:
pgsession <- html_session(url)
pgform <-html_form(pgsession)[[3]]
filled_form <-set_values(pgform,
        "team" = "ALL",
        "week" = "1",
        "pos"  = "ALL",
        "year" = "2015"
 )

 submit_form(session=pgsession,form=filled_form, POST=url)

*I tried doing that for the site above and I get the following instead
 > html_form(html_session("https://whalewisdom.com/filer/blue-harbour-group-lp#/tabholdings_tab_link"))
 [[1]]
 <form> '<unnamed>' (GET )
  <input text> '':
  <select> '' [1/7]

 [[2]]
 <form> 'frm_registration' (POST /filer/registration)
  <input hidden> 'permalink': blue-harbour-group-lp
  <input hidden> 'registration_type': register
  <input text> 'user_email':

 [[3]]
 <form> 'frm-report-error' (POST /filer/report_error)
  <input hidden> 'permalink': blue-harbour-group-lp
  <input text> 'user_name':
  <input text> 'user_email':
  <textarea> 'comments' [0 char]
  <textarea> 'g-recaptcha-response' [0 char]

*I dont quite see the same set up and the only form it seems with a drop down option is [1] with [1/7] options, but I dont know what that is referring to.

*Comparing the source code for both sites, it seems like I have a "form-control" class that I should be extracting? How do I do that?

*Finally, after refreshing the table with a different quarter, how do I download the CSV? Is it possible to read the csv from the website directly without downloading the file?
Thanks!

A: +1 for using Developer Tools. That tool/skill will serve you well.
You should seriously consider using the API. But you can use httr and rvest together for this (and I verified it's not against the site rules):
library(rvest)
library(httr)
library(tidyverse)

We'll get the page first since we need to scrape the popup menu data:
pg <- read_html("https://whalewisdom.com/filer/blue-harbour-group-lp#/tabholdings_tab_link")

qtr_nodes <- html_nodes(pg, "select[id='quarter_one'] option")

data_frame(
  qtr = html_text(qtr_nodes),
  value = html_attr(qtr_nodes, "value")
) %>%
  filter(!grepl("ubscri", qtr)) -> qtrs

qtrs
## # A tibble: 10 x 2
##                           qtr value
##                         <chr> <chr>
##  1 Current Combined 13F/13D/G    -1
##  2       Q3 2017 13F Filings     67
##  3       Q2 2017 13F Filings     66
##  4       Q1 2017 13F Filings     65
##  5       Q4 2016 13F Filings     64
##  6       Q3 2016 13F Filings     63
##  7       Q2 2016 13F Filings     62
##  8       Q1 2016 13F Filings     61
##  9       Q4 2015 13F Filings     60
## 10       Q3 2015 13F Filings     59

^^ is a translation table from pretty name to the popup value. The value is necessary for submitting the XHR request that happens behind the scenes.
Let's make a function to simulate that XHR request:
get_qtr <- function(qtr) {

  GET(
    url = "https://whalewisdom.com/filer/holdings",
    httr::add_headers(
      Host = "whalewisdom.com",
      `User-Agent` = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:58.0) Gecko/20100101 Firefox/58.0",
      Accept = "application/json, text/javascript, */*; q=0.01",
      `Accept-Language` = "en-US,en;q=0.5",
      Referer = "https://whalewisdom.com/filer/blue-harbour-group-lp",
      `X-Requested-With` = "XMLHttpRequest",
      Connection = "keep-alive"
    ),
    query = list(
      q1 = qtr,
      id = "384", type_filter = "1,2,3,4", symbol = "",
      change_filter = "1,2,3,4,5", minimum_ranking = "", minimum_shares = "",
      is_etf = "0", sc = "true", `_search` = "false", rows = "25",
      page = "1", sidx = "current_ranking", sord = "asc"
    )
  ) -> res

  stop_for_status(res)

  res <- content(res)

  map_df(res$rows, ~map(.x, ~ifelse(is.null(.x), NA, .x)))

}

We're just passing in value to the qtr parameter, but you could add params for the other bits, too.
Now, use the translation table above to get a randomly chosen set of data:
qtr_65 <- get_qtr(65)

glimpse(qtr_65)
## Observations: 19
## Variables: 24
## $ id                            <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## $ name                          <chr> "Investors Bancorp Inc", "Xilinx, Inc", "BWX TECHNOLOGIES INC", "AGCO Corp", "A...
## $ symbol                        <chr> "ISBC", "XLNX", "BWXT", "AGCO", "AVT", "WBMD", "AKAM", "RDC", "FFIV", "ADNT", "...
## $ permalink                     <chr> "isbc", "xlnx", "bwxt", "agco", "avt", "wbmd", "akam", "rdc", "ffiv", "adnt", "...
## $ security_type                 <chr> "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "SH", "...
## $ stock_id                      <int> 5284, 930, 7803, 600, 375, 838, 3527, 3658, 26, 198034, 5045, 72934, 812, 4116,...
## $ source_date                   <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""
## $ source_type                   <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""
## $ sector                        <chr> "FINANCE", "INFORMATION TECHNOLOGY", "INDUSTRIALS", "INDUSTRIALS", "INFORMATION...
## $ industry                      <chr> "TRUSTS & THRIFTS", "SEMICONDUCTORS", "ELECTRICAL EQUIPMENT", "MACHINERY", "ELE...
## $ current_shares                <int> 29582428, 6058693, 5287927, 3813700, 4363874, 3361336, 2855493, 10542812, 93835...
## $ previous_shares               <int> 29582428, 7514437, 10561086, 6835700, 5415074, 1795914, 2474193, 10542812, 8599...
## $ shares_change                 <int> 0, -1455744, -5273159, -3022000, -1051200, 1565422, 381300, 0, 78373, 1675570, ...
## $ position_change_type          <chr> NA, "reduction", "reduction", "reduction", "reduction", "addition", "addition",...
## $ percent_shares_change         <chr> "0.0", "-19.3726", "-49.9301", "-44.2091", "-19.4125", "87.1658", "15.4111", "0...
## $ current_ranking               <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 999999, 999999, 999999
## $ previous_ranking              <int> 3, 1, 2, 4, 5, 11, 7, 6, 8, 999999, 10, 9, 999999, 12, 14, 13, 15, 16, 17
## $ current_percent_of_portfolio  <dbl> 15.3264, 12.6366, 9.0686, 8.2689, 7.1946, 6.3798, 6.1419, 5.9180, 4.8200, 4.387...
## $ previous_percent_of_portfolio <dbl> 13.7987, 15.1687, 14.0194, 13.2249, 8.6205, 2.9767, 5.5165, 6.6592, 4.1615, NA,...
## $ current_mv                    <chr> "425395000.0", "350738000.0", "251705000.0", "229508000.0", "199691000.0", "177...
## $ previous_mv                   <chr> "412675000.0", "453647000.0", "419275000.0", "395514000.0", "257812000.0", "890...
## $ percent_ownership             <chr> "26.3298285", "2.4338473", "5.3287767", "4.5501506", "3.3856140", "8.6721677", ...
## $ quarter_first_owned           <chr> "Q1 2014", "Q1 2015", "Q4 2013", "Q2 2014", "Q2 2015", "Q4 2016", "Q3 2016", "Q...
## $ quarter_id_owned              <int> 53, 57, 52, 54, 58, 64, 63, 53, 61, 65, 47, 63, 65, 64, 64, 64, 64, 60, 64

I have no idea if ^^ is what's in the CSV since I'm not registering for an account, but you can verify and hopefully modify.


text:
Q: how to look up a a value from another datatable and display it in an unbound column of a bound datagridview I'm sorry, I tried to search for an answer but I'm having a really hard time translating the examples I've found into my own scenario.
I have an MS Access Database that has an "Employees" table with the following columns:
"Employee ID", "Name", "Middle", "Last", "Hire Date", "Fired Date".
Another Table "Work" that has the columns:
"Date", "Employee ID", "Activity", "Hours worked", "Department", "Shift", "Equipment Used",
A datagridview is bound to the "Work" table.
I call the FillbyDate() with a query made with the query editor at design time so only the entries for the specific date are loaded.
I would like to create an unbound column to display the name (NAME, MIDDLE, AND LAST) of the employee from the "Employees Table" using the employee Id to find it.
I'm completely new to coding with VB.Net, that might be reason why i don't understand or find the right examples. I would appreciate some sample code and the comments for each step to see how things are working.
Just as FYI i'm reading a couple of coding books:
Practical Database programming with VB.Net, Clearly Visual Basic 2010, Masterig MS Visual Basic 2010
Thank You in advance.

A: A better way is to create an SQL query that will join the tables based on the Employee ID field and will filter the data based on the date field. The DataGridView will be binded to a DataTable which will be filled based on that SQL query.
Sample code :
Dim FilterStr1 As String = "03/01/2013"
Dim DBPathStr1 As String = "C:\db1.mdb"

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim SqlConnStr1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPathStr1 & ";"

    Dim SqlStr1 As String = <SQL>
                                SELECT
                                    W.[Date]
                                    ,W.[Employee ID]
                                    ,W.[Activity]
                                    ,W.[Hours worked]
                                    ,W.[Department]
                                    ,W.[Shift]
                                    ,W.[Equipment Used]
                                    ,E.[Name]
                                    ,E.[Middle]
                                    ,E.[Last]
                                FROM [Work] AS W
                                INNER JOIN [Employees] AS E
                                    ON W.[Employee ID] = E.[Employee ID]
                                WHERE W.[Date] = #<%= FilterStr1 %>#
                            </SQL>.Value

    Dim OleDBAdap1 As New OleDbDataAdapter(SqlStr1, SqlConnStr1)
    Dim SqlDTable1 As New DataTable

    OleDBAdap1.Fill(SqlDTable1)
    DataGridView1.DataSource = SqlDTable1

    OleDBAdap1.Dispose()
End Sub

To use this code you will need to change the value of the variable DBPathStr1 with the path of your MS Access Database and set a date value for the FilterStr1 variable.
EDIT
The value of the FilterStr1 variable can be assigned by using a DateTimePicker control. To do that you will need to add a DateTimePicker control on the form and add the following code.
Private Sub DateTimePicker1_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged
    FilterStr1 = DateTimePicker1.Value.ToString("dd/MM/yyyy")
End Sub


text:
Q: Scraping pdf newspaper for keywords I have couple of hundreds of newspapers in pdf format and a list of keywords. My ultimate goal is to get the number of articles mentioning a specific keyword keeping in mind that one pdf might contain multiple articles mentioning the same keyword.
My problem is that when I converted the pdf files to plain text I lost the formatting which makes it impossible to know when an article start and when it ends.
What is the best way to approach this problem because right now I'm thinking it is impossible.
I am currently using python for this project and the pdf library pdfminer.
Here is one of the pdfs.
http://www.gulf-times.com/PDFLinks/streams/2011/2/27/2_418617_1_255.02.11.pdf

A: Depending on the format of the text you might be able to come up with some sort of heuristic which identifies a headline - say, it's a line on its own with fewer than 15 words and it doesn't contain a full stop/period character. This will get confused by things like the name of the newspaper, but hopefully they won't have significant amounts of "non-headline" text after them to mess up the results too badly.
This relies on the conversion to text having left every article contiguous (as opposed to just ripping raw columns and mixing the article up). If they're mixed up, I'd say you have very little chance - even if you can find a PDF library which maintains formatting, it's not necessarily easy to tell what constitutes an article's "bounding box". For example, many papers put callouts and other features which could confuse even quite an advanced heuristic.
Actually doing the counting is simple enough. If the assumptions I've mentioned hold, your could would likely end up looking like:
import re
import string

non_word_re = re.compile(r"[^-\w']+")

article = ""
for filename in list_of_text_files:
    with open(filename, "r") as fd:
        for line in fd:
            # Split line on non-word characters and lowercase them for matching.
            words = [i.lower() for i in non_word_re.split(line)
                     if i and i[0] in string.ascii_letters]
            if not words:
                continue
            # Check for headline as the start of a new article.
            if len(words) < 15 and "." not in line:
                if article:
                    # Process previous article
                    handle_article_word_counts(article, counts)
                article = line.strip()
                counts = {}
                continue
            # Only process body text within an article.
            if article:
                for word in words:
                    count[word] = count.get(word, 0) + 1
    if article:
        handle_article_word_counts(article, counts)
    article = ""

You'll need to define handle_article_word_counts() to do whatever indexing of the data you want, but each key in counts will be a potential keyword (including things like and and the, so you may want to drop the most frequent words or something like that).
Basically it depends how accurate you want the results to be. I think the above has some chance of giving you a fair approximation, but it has all the assumptions and caveats I've already mentioned - for example, if it turns out that headlines can span lines then you'll need to modify the heuristics above. Hopefully it'll give you something to build on, at least.


text:
Q: Android - Import Java Class into Activity I have a java class called Constants filled with variables. And currently if I want to use that variable in an activity I have to use it like this.
Constants.variable = "blah blah";

Is there a way to import my Constants class into my activity so that I can just use it like a normal variable like this
variable = "blah blah";

I have tried
import com.myname.appname.Constants;

but this doesn't seem to work.
Thanks for the help in advance.

A: considering Constants.variable is a static variable
import static com.myname.appname.Constant.*;

this will import all you static variables in you current namespace only the static variable
import static com.myname.appname.Constant.variable;

now you can use variable like a normal variable

A: try:
import com.myname.appname.Constants;

Are you using an IDE?
Also, they way you have stated is how you are suppose to use a Constants class. But you are not suppose to assign anything... because the variable are suppose to be constant, ie. static final

A: You have to declare "variable" as static and import the class as static by following syntax
    import static com.myname.appname.Constants.*;

A:
Is there a way to import my constants class into my activity so that I
  can just use it like a normal variable like this

I dont think so, its not what import for.
See this SO question : Meaning of the import statement in a Java file


text:
Q: SSL Pinning with AFNetworking 2.0 allowing POST requests regardless of cert file used We are using DigiCert as our CA.  We have made the .cer file with the following command:
openssl x509 -in WEBSITE.crt -outform der -out WEBSITE.cer

which SHOULD work but the issue is that not only will that cer work but any file we put into the code will work. We have even tested blank .cer files and that works as well.  By work I mean we are able to make a post request to the server regardless of what .cer file is used.  Obviously we would like it to fail if something other than our signed cert is used.
Our origin is set at Cloudflare which then routes to an Amazon load balancer which has our certificates installed onto it.
I'm using Charles Proxy to MITM myself and I can do it with or without the cert in the iOS app.
We are using the latest release of AFNetworking to do the SSL pinning.  I subclassed AFHTTPRequestOperationManager and added the following method:
+ (AFSecurityPolicy*) siteSecurityPolicy
{
    /**** SSL Pinning ****/
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"WEBSITE" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:NO];
    [securityPolicy setPinnedCertificates:@[certData]];
    [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate];
   /**** SSL Pinning ****/

    return securityPolicy;
}

My code to make the post is as follows:
websiteRequestOperationManager *manager = [websiteRequestOperationManager manager];

/**** SSL Pinning ****/
[manager setSecurityPolicy:[websiteRequestOperationManager siteSecurityPolicy]];
/**** SSL Pinning ****/

[manager GET:WEBSITE_URL parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {
    //code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //code
}];

What critical step have we missed?
I should also mention that I NSLog'd:
[manager.securityPolicy.pinnedCertificates count]

and received a 1.

A: This seems to be the case for me as well, using AFNetworking 2.3.1. AFNetworking 2.1.0 does not have this problem, however the pinning there breaks on iOS 8 beta 5.


text:
Q: first parameter in send function "SERVER/CLIENT" I am writing a CLIENT/SERVER program and I have a problem with the client part.
In the client part, I start by receiving messages from the server but when I want to send a message to the server, I have a problem - how can I get the server socket that I can use as first parameter in the send function?
Function: int connect (int socket, struct sockaddr *addr, socklen_t length)

this is a part of the client code :
#if defined (WIN32)
#include <winsock2.h>
typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#endif

#include <stdio.h>
#include <stdlib.h>
#define PORT 23

int main(void)
{

#if defined (WIN32)
    WSADATA WSAData;
    int erreur = WSAStartup(MAKEWORD(2,2), &WSAData);
#else
    int erreur = 0;
#endif

SOCKET csock;
SOCKADDR_IN sin;
char buffer[32] = "";

if(!erreur)
{
    csock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_addr.s_addr = inet_addr("127.0.0.1");
    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);

    if(connect(csock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR)
    {

     //
        if(recv(csock, buffer, 32, 0) != SOCKET_ERROR)
            printf("Recu : %s\n", buffer);

         char buffer1[32] = "how are you  !";
         send( ?sock?, buffer1, 32, 0);  // here is my problem , so what is the first parameter(?sock?) in the "send" function that i need to send message to the server ?

.......
......
.....

A: You already have it: it is your csock variable. TCP Connections are established both ways. When you connected to your sever you got value for your csock: you can use it for both sending and receiving data.


text:
Q: why I use fetch to upload img in react don't have fileName? I use fetch to upload images in react,my code is like below:
    let formData = new FormData();
    let file = {uri: imgdata, type: 'multipart/form-data', name: '2_resources.jpg'};
    formData.append("name", "name");
    formData.append("mobile", "18381307123");
    formData.append("content", "123654");
    formData.append("resources", file,"2_resources.jpg");//mind this line
    fetch(Config.report,
        {
            mode: 'cors',
            method: "POST",
            body: formData
        })
        .then(res => res.json())
        .then((data) => {
                console.log(data)
            }
        ).catch((err) => {
            console.log(err)
        }
    );

but,run it I get the request :

I have look for FormData API document on https://developer.mozilla.org/en-US/docs/Web/API/FormData
it have write below:

and the fetch used is :"isomorphic-fetch": "^2.2.1"
what should I do to use fetch upload images? thanks.

A: You are adding the file to the FormData object incorrectly. isomorphic-fetch wraps github's fetch polyfill. Looking at their docs shows that it should be:
handleFileUpload(event) {
  var formData = new FormData();
  formData.append('fileName', event.target.files[0]);
  fetch('http://your-domain/upload',
    {
      mode: 'cors',
      method: 'POST',
      body: formData
    }).then(function (response) {
   console.log('response: ', response);
  });
}

The field name on the server will be whatever you use as the key when appending formData. In the above example it will be 'fileName'. I also don't think you need to set the content-type and file name yourself. It should get set automatically.
In the above example, 'event' is the event fired from the input tag when the user upload the file:
<input type="file" onChange={this.handleFileUpload}/>


text:
Q: Discard all characters but the first 10 words before and after a search term I'm trying to finish the search function in one of the sites I'm developing. Since my search results only display excerpts of the contents of matched items, what I want to do is to highlight search terms within the search results and display only portions of texts that actually contain those search terms.
What I figured I'd do is to fetch the whole content from the database and use preg_replace to insert  elements around the search terms and at the same time extract only the first 10 words before and after the term. So this is the regex part of it:
(?:.*?)((?:\w+\W+){0,10})('.implode('|', $terms).')((?:\W*\w+\W+){0,10})

Basically, I try to "discard" all text except the first 10 words before the search term by using a non-capturing subpattern, then get the 10 words before the term, then the term itself, then the next 10 words.
This is the replacement text in preg_replace:
\\1\\2\\3...

The search term is being searched via the MySQL's MATCH()...AGAINST() for MyISAM FULLTEXT indeces on multiple columns. However, the above regex is only being applied in one column (let's call this column, the one that uses the above regex, content).
So my problem is whenever I get a match on other columns but not on the content column, the regex above strips all text from the content column. That's because of the (?:.*?) subpattern at the very beginning which continues to match without ever finding the next subpatterns.
I was wondering if there was any other way to implement the original purpose of the regex without this side effect. I am currently thinking of simply using preg_match_all to just match the search term and 10 words before and after it. I'll just iterate over all of the matches and build the preview text manually. Yes, this is a sound solution but given my inexperience with regex, I thought I might as well try to find a solution to this.
UPDATE
I just noticed that I only get blank contents when I put 2 or more search terms. Other than that, it works perfectly. I now have no idea why this is happening.
UPDATE 2
Echo'ing preg_last_error(), I get this error PREG_BACKTRACK_LIMIT_ERROR. I use the words new and post for the search terms.
A var_dump of the regex and the terms show this:
@(?:.*?)((?:\w+\W+){0,10})(new|post)((?:\W*\w+\W+){0,10})@i

array
  0 => string 'new' (length=3)
  1 => string 'post' (length=4)

UPDATE 3
I used Regex Coach to walk me through the matching pattern, it seems that it backtracks too much after it finds no match for (new|post). The target text is simply a random 3-paragraph lorem ipsum. I think I need to find a better regex for this task.
UPDATE 4
Using a Once-Only subpattern solves the problem. Though I have no idea of its details, I just re-read the PHP Manual and read a part of it that Once-Only subpatterns help with too much backtracking. This is the new regex:
(?:.*?)((?>\w+\W+){0,10})('.implode('|', $terms).')((?:\W*\w+\W+){0,10})

But I'm still open for suggestions for better regexes. Thanks!

A: If you're having issues with hitting the backtracking limit, you generally want to look at once-only subpatterns.
In this case however your main issue seems to be the (?:.*?) being followed by (?:\w+\W+){0,10}. Take for example the string 'hello world!', ignoring for now the {0,10}. This will match the two patterns as all of the following:

*

*'' and 'hello '

*'h' and 'ello '

*'he' and 'llo '

*'hel' and 'lo '

*'hell' and 'o '

*'hello ' and 'world!'

*'hello w' and 'orld!'

*'hello wo' and 'rld!'

*'hello wor' and 'ld!'

*'hello worl' and 'd!'

The easiest way to block this redundant backtracking is to add a word boundary check (\b) after the (?:.*?) subpattern. This will reduce these potential matches to

*

*'' and 'hello '

*'hello ' and 'world!'

EDIT: Here is an example of why a once-only subpattern will not work here:
preg_replace('/(?>[a-z]{0,2})a/','x','bac')

In this example we would expect the result 'xc', however the subpattern matches greedily to 'ba' and then never backtracks, thus missing the match. We could make the pattern ungreedy, but then we would get the result 'bxc', because it never backtracks after matching '' for the subpattern.