text:
Q: Are recursive modules even a possibility in Terraform? Are recursive modules even a possibility in Terraform?
I want to create a module called my_module with the below content
variable "name" {
  type = "string"
}

variable "children" {
  type = list(object)
}

resource "XXX" "example_resource" {
  name = var.name
}

module "example_recursion" {
  source = "../my_module"

  count = length(var.children)

  name = var.children[count.index].name
}

When I do init it seems to get itself in a twist and ends up corrupting the module cache!
Initializing modules...
- name in ../modules/my_module
- name.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module
- name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion in ../modules/my_module

Error: Failed to remove local module cache
│
│ Terraform tried to remove
│ .terraform/modules/name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion
│ in order to reinstall this module, but encountered an error: unlinkat
│ .terraform/modules/name.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion.example_recursion:
│ file name too long


text:
Q: Does Fluent NHibernate support "trigger-identity" I posted the question in the Fluent-NHibernate newgroup but so far there has been no answer from the void.
Is there a Fluent NHibernate mapping for the NHibernate "trigger-identity" method of generating primary keys.
Thanks

A: Just to keep this discussion up-to-date :
this.Id(x => x.Id, "id").GeneratedBy.TriggerIdentity();

-> Fluent NHibernate V.1.1.0.685

A: Try this:
this.Id(x => x.Id).Column("ID").GeneratedBy.Custom("trigger-identity");

A: So it turns out that trigger-identity is not currently supported.

A: So far, the only solution I've found is to use an hbm.xml file for those entities that require trigger-identity generators.  However, we ran into another problem when using trigger-identity and "long" ids and our Oracle database .  There is a bug where NHibernate does not translate the Id values returned from properly.  Here is the JIRA entry:
https://nhibernate.jira.com/browse/NH-1893

A: I have tried with FluentNHibernate v2.0.50727
Following mapping works fine:
this.Id(x => x.Id, "id").GeneratedBy.TriggerIdentity();
Following mapping is not supported anymore:
this.Id(x => x.Id).Column("ID").GeneratedBy.Custom("trigger-identity");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to measure similarity of inner observation variation without considering actual values? I am sure that this has been done before but I am unsure of how to even phrase the question for google and have been racking my brain for a few hours now, but I can explain it with an example. Imagine you have the data below.

observation #
m1
m2
m3
m4
m5
m6

1
T
L
T
L
T
L

2
A
R
A
R
A
A

3
B
C
B
C
B
C

4
K
K
K
A
L
K

5
P
P
P
R
L
P

I want to generate some sort of similarity metric between observations that relates to the variation across the m1-6 variables. The actual values in the cells shouldn't matter at all.
Considering the table above, for example observations 1 and 3 are exactly the same as they vary the same across the m's (TLTLTL & BCBCBC). 1 & 3 are very similar to 2, and observations 4 and 5 are the same but not similar to 1-3.
I would like an output that captures all these relationships for example . . .

observation #
1
2
3
4
5

1
1
0.8
1
0.1
0.1

2
0.8
1
0.8
0.2
0.2

3
1
0.8
1
0.1
0.1

4
0.1
0.2
0.1
1
1

5
0.1
0.2
0.1
1
1

A few notes - each cell can have more than just 1 letter but again the actual contents of each cell don't matter - just the variation across the m's within each observation compared to other observations. Is their a name for what I am trying to do here? Also I only know python & R so if you provide any code please have it in those (python preferred).
It is driving me crazy that I can't figure this out. Thanks in advance for any help :)


text:
Q: Use wget to download pdf with no direct link Some websites provide pdf files for viewing but I can't download such pdf files with wget.
Calling the website in question from my browser views the pdf:
https://www.lokalmatador.de/epaper/ausgabe/gemeinderundschau-muehlhausen-14-2021/
But using the following code I only get a pdf file with 0 lenght.
wget --content-disposition -nd https://www.lokalmatador.de/epaper/ausgabe/gemeinderundschau-muehlhausen-14-2021/

I tried some combinations with saving and loading cookies and referer but nothing works.
At this point I'm just curious what is happening and why wget is not fetching anything except maybe an empty index.html.

A: When I was looking at server response, it was saying the content length was 0.
--2021-04-17 14:59:35--  https://www.lokalmatador.de/epaper/ausgabe/gemeinderundschau-muehlhausen-14-2021/
Resolving www.lokalmatador.de (www.lokalmatador.de)... 37.202.6.70
Connecting to www.lokalmatador.de (www.lokalmatador.de)|37.202.6.70|:443... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Date: Sat, 17 Apr 2021 13:59:36 GMT
  Server: Apache
  Set-Cookie: fe_typo_user=477e8a1d2b3dd74bc5b6b408a6d74edd; expires=Mon, 17-May-2021 13:59:36 GMT; Max-Age=2592000; path=/; domain=.lokalmatador.de; httponly; samesite=lax
  Upgrade: h2,h2c
  Connection: Upgrade, Keep-Alive
  Content-Length: Array
  Cache-Control: max-age=2592000
  Expires: Mon, 17 May 2021 13:59:36 GMT
  X-UA-Compatible: IE=edge
  X-Content-Type-Options: nosniff
  Keep-Alive: timeout=5, max=100
  Content-Type: application/pdf
Length: 0 [application/pdf]
Remote file exists but does not contain any link -- not retrieving.

So looked at the manual:
https://www.gnu.org/software/wget/manual/html_node/HTTP-Options.html
And there is a command just exactly for this:
'--ignore-length'

    Unfortunately, some HTTP servers (CGI programs, to be more precise) send out bogus Content-Length headers, which makes Wget go wild, as it thinks not all the document was retrieved. You can spot this syndrome if Wget retries getting the same document again and again, each time claiming that the (otherwise normal) connection has closed on the very same byte.

    With this option, Wget will ignore the Content-Length header—as if it never existed.

Then the wget command started working as expected:
 wget --ignore-length -O epaper.pdf https://www.lokalmatador.de/epaper/ausgabe/gemeinderundschau-muehlhausen-14-2021

Here is output which I'm seeing with the ignore length:
--2021-04-17 14:56:19--  https://www.lokalmatador.de/epaper/ausgabe/gemeinderundschau-muehlhausen-14-2021
Resolving www.lokalmatador.de (www.lokalmatador.de)... 37.202.6.70
Connecting to www.lokalmatador.de (www.lokalmatador.de)|37.202.6.70|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: ignored [application/pdf]
Saving to: 'epaper.pdf'

epaper.pdf                        [                  <=>                             ]   4.39M  1.23MB/s    in 3.6s

2021-04-17 14:56:23 (1.21 MB/s) - 'epaper.pdf' saved [4601842]


text:
Q: Odd behaviour with byte[] C++ I have been writing some code to create a byte array I will be sending over a socket to another process. However noticed some really odd behavior regarding my byte[].
The cout at the end prints out 99, however looking at my code, I couldn't find where the value is being set. I create a char array of size sendingSize which is a constant. I don't set the value 307200* 3 so I don't understand how it prints out with a value...
char tosend[sendingSize];
//Send over the frame
for(int i = 0; i < 307200; i++)
{
    tosend[i * 3] = (byte)imCopy[i/640][i%640].red;
    tosend[i * 3+1] = (byte)imCopy[i/640][i%640].green;
    tosend[i * 3+2] = (byte)imCopy[i/640][i%640].blue;
}

char *bytePointer = tosend;

cout<<(int)tosend[307200* 3]<<endl;

A: Your code does not write any value into index 307200*3 (because the highest index your for loop reaches is 307199). So you are reading some byte from memory beyond the declared size of your array. This is undefined behaviour and anything could happen.
Some other programming languages (such as Java) do automatic range checking on arrays and would throw an exception in this case. In C++, you are expected to do the right thing and the compiler doesn't generate range checking code for you.


text:
Q: How to make computer interface with circuit I understand that I can build a circuit that will do whatever I like (ex: a simple circuit that will turn on a motor to open the blinds or something), and I can write a program that will automate my computer/mac however I like (ex: open this program at this time, or with this input and create a new file, ect).
My question is, how can I interface the two?  Is there an easy DIY or cheap commercial (or not cheap but functional) USB plug that will turn on/off from computer commands?  I'm basically looking for some sort of on/off switch I can script/applescript.  How would you even approach this problem, would I have to write my own driver some where along the way?

A: I've used hardware from phidgets.com. Attached a stepper motor with a stepper controller and used their drivers/api and it worked fine for my needs.
Looks like one of their relays might be what you are looking for.

A: You may want to have a look at Arduino:  http://www.arduino.cc/
It provides a very flexible interface (hardware and software) between your computer and external circuitry.


text:
Q: Js Array detect: number of values from php array found (grabbed from database) This is (again) about array (in my Google map project). After being voteddown, finally I succeed to show multiple markers based on Db data.
I have two PHP pages:
 1. inc.php
 2. index.php

In inc.php contains values in php array, as follow:
    //...... previous code
    $googlemap=$result['googlemap'];
    $map[] = $googlemap;
    }
echo implode(', ' , $map);

The result shows: -5.364000343425874,-150.364000343425874-5.362878747789552,-150.3640003436345874 (this line contains 2 values for example)
To get the values, I use native Ajax:
In index.php contains Javascript codes to fetch the php array (inc.php), extract them into each values for latt and long value, as follow:

*

*Array Values from inc.php is caught by this code:
var wwwsitus = document.querySelector("#valdata").value;
The value inside #valdata grabbed by native ajax:

*Extract #valdata:

var n_result = wwwsitus.split(',');
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];

*Show the map from this format array:

var wwwsitus = [
  ['
Universitas Lampung
', x0,y0],
  ['
Universitas Lampung
', x1,y1]
];
All works 100%.
The problem is:
Values grabbed from database can be 1, 2 or more. (here, I limit the values into 5).
Question:
How do I detect the values in #valdata if #valdata contains 1 or more values so that I can create if for the result???. or, you have other suggestion to handle this.
I hope my question is very clear and pls help me out from this. Thnks.
UPDATED:
What I expect is, for instance:
var wwwsitus = document.querySelector("#valdata").value;
var n_result = wwwsitus.split(',');
    if (wwwsitus =null) {
       alert('No rent-house found near the place'); // if no value.
       // no action
        }
    else if (wwwsitus =1) {
        alert('Found 1 rent-houses'); // if found only 1 value
//continue to show the map based on the value - will show 1 marker.
        var x0 = n_result[0];
        var y0 = n_result[1];
        var wwwsitus = [['
Kost 1
', x0,y0]];
        }
    else if (wwwsitus =2) {
        alert('Found 2 rent-houses'); //if found 2 value
// continue to show the value - will show 2 markers.
        var x0 = n_result[0];
        var y0 = n_result[1];
        var x1 = n_result[2];
        var y1 = n_result[3];
        var wwwsitus = [['
Kost 1
', x0,y0],['
Kost 2
', x1,y1]];
    }

HOWEVER, the alert() NOT SHOWING the real number of the values as in the Database. How should I code with this.?

A: This following solution perhaps stupid coding. But it finally works 1000%.

To detect number of values inside #valdata, I add one input field as follow:

*

*<input type='hidden' id='numvalue' value=''/>

*Create native Ajax again to grabbed the information about number of values in new file (e.g. num_inc.php)

Here, with that ajax, I will be able to get number of values exist based on mysql query and send to input field #numvalue.
Here's in num_inc.php last code:
$result = $uQuery->fetchColumn();
if($result> 0) {
    echo $result; // number of value detected!!!
    }

From the process, I finally can extract the data from #valdata and display the map successfully.
Here's the full code:

Input Field:
<input id="qfront" name="qfront" placeholder="Type your campus ..."
value="" type="text" onKeyPress="script_grabbed(this.value);"  />
<input id="valdata" name="valdata" type="hidden" value=""/>
<input id="numvalue" name="numvalue" type="hidden" value=""/>

in num_inc.php:
$result = $uQuery->fetchColumn();
if($result> 0) {
    echo $result;
    }

in inc.php:
    $googlemap=$result['googlemap'];
    $map[] = $googlemap;
    }
echo implode(', ' , $map);

NOTE: If you have another nice solution, please let me know. Of course, I like the better one than I attempt.
Complete Source: Github


text:
Q: javascript, selection option using for loop that return the selected value I'm pretty new to javascript so please bear with me. I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default. I also need to get the return value of the choice user selected so i can use to calculate the years. Here is the code i'm playing around with so far.

    function createAgeList()
    {
        var myAgeOptions;

        for (cntr=1; cntr<100; cntr++)
        {
           myAgeOptions = myAgeOptions + "<option value=" + cntr + ">" + cntr + "</option>";
        }

        var myAgeSelect = document.getElementById('agelist');
        myAgeSelect.innerHTML = myAgeOptions;
    }

HTML code:
<form name="yearsleptform" id="yearsleptform" method="post">
  <select size="1" id="agelist" name="agelist">
  </select>
</form>

A: document.yearsleptform.agelist.value

This is going to return you the value they have selected.

A: To set the default option:
function createAgeList()
    {
        var myAgeOptions;

        for (cntr=1; cntr<100; cntr++)
        {
           myAgeOptions = myAgeOptions + "<option value=" + cntr + " "+(cntr===20?"selected=selected":"")+ ">" + cntr + "</option>";
        }

        var myAgeSelect = document.getElementById('agelist');

Live Demo
        myAgeSelect.innerHTML = myAgeOptions;
    }

to get the selected value:
document.yearsleptform.agelist.value

Live Demo


text:
Q: mv: cannot remove directory: Directory not empty Running the command
/data/jritchie$ mv ~/jenkins_dev /data/jritchie/jenkins_dev

I'm getting a bunch of errors like the following:
mv: cannot remove `/home/jritchie/jenkins_dev/plugins/valgrind/WEB-INF/lib': Directory not empty

This is similar to errors returned by rm.
My question is, does this error mean that my files were all successfully moved to the new location, but removing them from the old location failed? Or that they didn't get moved at all? Can I safely remove the old files with rm -r ~/jenkins_dev?

A: Check to see if there is a file/folder in there that you don't own.  Assuming bash and all file names are nicely behaved, something like:
for file in $(find ~/jenkins_dev); do stat -c '%U %n' $file;done | grep -v jritchie

If something pops up then you need to get the owner (or sysadmin) to handle it for you.


text:
Q: Dingo API, use Database Query Builder Does anyone know how can I use the Eloquent Query Builder with Dingo API ?
Using Eloquent out of the box, it is working great :
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([ ... ]);

$capsule->setAsGlobal(); // Make this Capsule instance available globally via static methods
$capsule->bootEloquent(); // Setup the Eloquent ORM

And then in my model, I can use the Query Builder :
use Illuminate\Database\Capsule\Manager as Capsule;

Capsule::table('users')->where(...)->select(Capsule::raw('AVG(rating) AS avg_rating'))->first()->avg_rating;

I know that I can use Eloquent to get the same result, but it will only work with easy query :
User::where(..)->selectRaw(...)->first()->avg_rating;

Now with Dingo API, when I wanna use the Query Builder I've got this error message :
Fatal error: Call to a member function connection() on null

I guess that is related to the setAsGlobal method that I have never called in my app/bootstrap.php file. I only have this :
...
$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

// $app->withFacades();

$app->withEloquent();
...

A: I guess it is as I am using lumen that require illuminate/database : https://github.com/laravel/lumen-framework/blob/5.2/composer.json
However, Dingo API in stable mode do not require illuminate/database. Could it be the reason ? Required packages are not automaticaly "sub" required ?

A: I got it. It was only about Facades.
Uncomment the line in app/bootstrap.php to use Facades :
$app->withFacades();

Now, I can use the Facade 'DB' and so the Query Builder...


text:
Q: How to find volume generated by rotating the region using Shell method Refer to the figure below to determine the volume generated by rotating the given region around
of the specified axis:

a) $R_2$ around AB
Using the formula $A(x)=2\pi(radius)(height)$
Why my radius will be $(1-x)$ and my height will be
$(1-\sqrt{x})$?
Aplying in the Volume Formula:
$$=\int_{0}^{1}2\pi(1-x)(1-\sqrt{x})=\frac{7\pi}{15}$$
So my volume will be $\frac{7\pi}{15}$
I didn't understand the reason for the radius and height values.
b) $R_1$ around $OA$
c) $R_2$ around $OA$
d) $R_3$ around $OA$
e) $R_3$ around $AB$
f) $R_1$ around $BC$
Can someone explain to me how I determine the radius and height to be able to develop the letters b through e?

A: The radius is the distance from the solid to the axis of rotation.  For part a), the axis is at $x = 1$, so the distance is $1-x$, for $x$ between $0$ and the boundary of the solid.
If you are not sure, you can do a sanity check:  The closest region $R_1$ gets to the axis is a distance of $0$ when $x = 1$.  Note that this agrees with the answer because $1-1 = 0$.
Let's do part (c).  The axis of rotation is $y = 0$.  Because our shells will now be oriented along the $y-$axis, we solve for $x$ in terms of $y$.  That is, $x = y^2$, where $0 \leq y \leq 1$.  The distance between $R_2$ the the axis $OA$ is $y$.  The height of the shells will be $y^2$.  So, this gives us
$$2\pi \int_{y=0}^{1}y(y^2) dy.$$


text:
Q: How to convert FBV to ListView in Django I want to convert the FBV function to ListView.
But I don't know how to handle the value of slug.
How to get the value of slug in ListView?
view.py
def category(request, slug=None):
    current_ct = None
    categories = Category.objects.all()
    products = Product.objects.filter(ready=True)

    if slug:
        current_ct = get_object_or_404(Category, slug=slug)
        products = products.filter(category=current_ct)

    return render(request, 'home.html', {'current_ct': current_ct, 'categories': categories, 'products': products})

url.py
path('category/<slug>/', category, name="test"),

get_absolute_url() in model.py
def get_absolute_url(self):
    return reverse("test", kwargs={"slug": self.slug})

A: You can get access to the parameters passed to the call with self.args (for positional parameters) and self.kwargs (for named parameters).
That being said, if you use a DetailView [Django-doc], you do not need to do this yourself at all. Indeed a DetailView and all other class-based views that use the SingleObjectMixin [Django-doc] will look for a slug and pk in these parameters, and do the filtering automatically.
We thus can make it a DetailView as:
class CategoryDetailView(DetailView):
    model = Category
    context_object_name = 'current_ct'
    template_name = 'home.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context.update(
            categories=Category.objects.all(),
            products=self.object.product_set.filter(ready=True)
        )
        return context
Here by overriding the .get_context_data(..) method [Django-doc], we thus inject extra items in the context we pass when rendering the template.


text:
Q: Storage Spaces Critical Write Error So I have a Windows 10 box with 5 WD Reds in it configured using Storage Spaces.  Last Saturday I performed windows updates on the machine, which brought Windows 10 up to build 1709.  I have three VMs running in Hyper-V which have their VHDX files on the virtual disk created by Storage Spaces, and now these VMs being started all immediately bring the storage space offline due to Critical Write Errors.
I already went through with the WD Diagnostic tool and ran extended tests against all of the disks, they are not failing and have no issues.  The rest of the files are perfectly accessible, and the space can be written to.  Just the VMs bring the storage space offline.
I pulled the VHDs off of the virtual disk then booted them up from another disk and they run without issue whatsoever (in fact they run considerably faster, but that could be due to them now being temporarily on a RAID 0 SSD pair)
Running this command yields the following results in powershell:
Get-PhysicalDisk 'WDC WD20EFRX-68EUZN0' | Get-StorageReliabilityCounter

DeviceId Temperature ReadErrorsUncorrected Wear PowerOnHours
-------- ----------- --------------------- ---- ------------
2                    0                     0    14637
6                    0                     0    14636
5                    0                     0    14635
4                    0                     0    14635
3                    0                     0    14266

I can't seem to find any errors anywhere - all I can chalk this up to is something about the 1709 update killed my ability to run Hyper-V VHDs on a Storage Spaces volume.
Does anyone have any clue how to proceed with this?  I cannot find any information online other than people who actually have failing disks

A: I have resolved this error again with different steps....so posting another Answer.
I was unable to correct the presumed file system errors which prevented me mounting my Virtual Disk in Write mode. Since i was able to bring the disk online using the below command in Read Only mode. I copied all my data off....and wiped the virtual disk and storage pool away and recreate the volume.
Get-VirtualDisk | ?{ $.ObjectId -Match "{e4cadb43-10be-11e4-826a-005056c00008}" } | Get-Disk | Set-Disk -IsReadOnly $true Get-VirtualDisk | ?{ $.ObjectId -Match "{e4cadb43-10be-11e4-826a-005056c00008}" } | Get-Disk | Set-Disk -IsOffline $false
All the data is back on the disk, Scan disk is fine and no errors are reported.
I am not impressed with Storage Spaces now... :(

A: I had the exact same issue.... (see below)
Storage Spaces 'offline due to critical write failures; add drives'
Basically the Get-StorageReliabilityCounter is useless for identifying issues. I suggest you get a tool from the manufacturer to do an Extended disk test on each drive. For WD i used Data Life Guard and ran 5 copies at once.
This will test for a bad sectors and when identifed an event will be logged in Eventviewer and then crystaldisk info will report data and then finally the Get-StorageReliabilityCounter will have something useful.
Then replace the appropriate disk.
I am now dealing with this issue again....and without jumping the gun i think there may be an issue with WD Reds and Storage spaces....as each time a drive has died i left a bunch of things running on the disk. I think there is a bug.
cheers


text:
Q: Can Moqui implement a form with dynamic fields I have two list listRowKey and listColKey and a nested map map<Row, Map<Col, String>>, I want to create a table to input content into map, the rows and cols of table is generated from two list. I don't known how to use a nested loop to add fields into form.

A: The XML Forms in Moqui are not designed for this sort of thing. I have implemented a number of screens with Moqui that need a dynamic set of columns and the best approach for that is to use an FTL template under the render-mode element, see the Making Apps with Moqui book for examples and details on how to use it. The FTL template can be embedded in the screen XML file or put in a separate file.


text:
Q: What is an API token I'm trying to work out the best way to handle user authentication for my mobile application (iOS & Android) and API (PHP).
From what I've researched the options are:
Basic auth over HTTPS - Check username/password of the user for every request.
Sessions - Send a session ID with each request; server maintains state. So app sends username/password and server checks for a logged in user on subsequent requests, just like my website does.
API tokens - Mobile app sends username/password and receives a token back, then appends this to subsequent requests. Token stored in DB and checked on each request.
I'm guessing my explanation of API tokens is incorrect as they seem identical to sessions because I store session ID's in the DB.

*

*Could my explanation of API tokens be corrected. What are they for? How do they differ to session ID's?

*What are the advantages of API tokens?

*Is oAuth (if we were to simplify its uses) just a protocol for creating "API tokens"?

A: I'm no expert but I'll give you a couple of cents I've picked up:
1) API Tokens is a bit of a general term. Usually an API token is a unique identifier of an application requesting access to your service. Your service would generate an API token for the application to use when requesting your service. You can then match the token they provide to the one you store in order to authenticate.
A session id can be used but its purpose is different to the API token. The session id is not a form of authentication but rather a result of authorisation. Typically a session is established once a user has been authorised to use a resource (such as your service). Therefore a session id is created when a user is granted access to a resource. An API token is the form of authentication similar to a username/password.
2) API tokens are a replacement to sending some username/password combination over HTTP which is not secure. However the problem still exists that someone could take and use the API token instead.
3) In a way yes. It's a method for keeping API tokens "fresh". Instead of passing around the same API token you request an access token when you want to use a service. The OAuth 2.0 steps are as follows:
   a) Request sent to service with credentials of some kind
   b) Successful response returns a code
   c) Another request to service is made with the code
   d) Successful response returns the access token for signing each API request from then until finish.
A lot of the bigger service providers use OAuth 2.0 at the moment. It's not a perfect solution but it's probably the most secure, wide-spread, API security method used at the moment.


text:
Q: k8s: Why coredns can't run on master node? I setup a k8s cluster, which have one master node and one worker node, coredns pod is schedule to worker node and works fine. When I delete worker node, coredns pod is schedule to master node, but have CrashLoopBackOff state, the log of coredns pod as following:
E0118 10:06:02.408608       1 reflector.go:153] pkg/mod/k8s.io/client-go@v0.17.2/tools/cache/reflector.go:105: Failed to list *v1.Endpoints: Get https://10.96.0.1:443/api/v1/endpoints?limit=500&resourceVersion=0: dial tcp 10.96.0.1:443: connect: no route to host
E0118 10:06:02.408752       1 reflector.go:153] pkg/mod/k8s.io/client-go@v0.17.2/tools/cache/reflector.go:105: Failed to list *v1.Namespace: Get https://10.96.0.1:443/api/v1/namespaces?limit=500&resourceVersion=0: dial tcp 10.96.0.1:443: connect: no route to host
[INFO] SIGTERM: Shutting down servers then terminating
[INFO] plugin/health: Going into lameduck mode for 5s

This article say DNS components must run on a regular cluster node (rather than the Kubernetes master):

In addition to Kubernetes core components like api-server, scheduler,
controller-manager running on a master machine there are a number of
add-ons which, for various reasons, must run on a regular cluster node
(rather than the Kubernetes master). Some of these add-ons are
critical to a fully functional cluster, such as Heapster, DNS, and UI.

Can anyone explain why coredns pod can't run on master node?

A: Starting from scratch Kubernetes idea is to deploy pods on worker nodes. Master nodes are a nodes which controls and manages worker nodes.
When the Kubernetes cluster is first set up, a Taint is set on the master node which automatically prevents any pods from being scheduled on this node. You can see this as well as modify this behavior if required. Best practice is not to deploy application workloads on a master server.
Read useful article: master-node-scheduling.
However you can force pods/deployments to be deployed on master nodes by using nodeSelector. For example, give your master node a label say dedicated=master and set nodeSelector for your pod to look for this label.
See more: deployment-on-master-nodes.


text:
Q: How to set AudioStreamBasicDescription properties? I'm trying to play PCM stream data from server using AudioQueue.
PCM data format :
Sample rate = 48000, num of channel = 2, Bit per sample = 16

And, server is not streaming fixed bytes to client. (variable bytes.)
(ex : 30848, 128, 2764, ... bytes )
How to set ASBD ?
I don't know how to set mFramesPerPacket, mBytesPerFrame, mBytesPerPacket .
I have read Apple reference document, but there is no detailed descriptions.
Please give me any idea.
New added :  Here, ASBD structure  what I have setted. (language : Swift)
// Create ASBD structure & set properties.
var streamFormat = AudioStreamBasicDescription()

streamFormat.mSampleRate = 48000
streamFormat.mFormatID = kAudioFormatLinearPCM
streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked
streamFormat.mFramesPerPacket = 1
streamFormat.mChannelsPerFrame = 2
streamFormat.mBitsPerChannel = 16

streamFormat.mBytesPerFrame = (streamFormat.mBitsPerChannel / 8) * streamFormat.mChannelsPerFrame
streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame
streamFormat.mReserved = 0

// Create AudioQueue for playing PCM streaming data.
var err = AudioQueueNewOutput(&streamFormat, self.queueCallbackProc, nil, nil, nil, 0, &aq)

...

I have setted ASBD structure like the above.
AudioQueue play streamed PCM data very well for a few seconds,
but soon playing is stop. What can I do?
(still streaming, and queueing AudioQueue)
Please give me any idea.

A: ASBD is just a structure underneath defined like follows:
struct AudioStreamBasicDescription
{
    Float64             mSampleRate;
    AudioFormatID       mFormatID;
    AudioFormatFlags    mFormatFlags;
    UInt32              mBytesPerPacket;
    UInt32              mFramesPerPacket;
    UInt32              mBytesPerFrame;
    UInt32              mChannelsPerFrame;
    UInt32              mBitsPerChannel;
    UInt32              mReserved;
};
typedef struct AudioStreamBasicDescription  AudioStreamBasicDescription;

You may set the variables of a struct like this:
AudioStreamBasicDescription streamFormat;

streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;

streamFormat.mSampleRate = sampleRate;
streamFormat.mBitsPerChannel = bitsPerChannel;
streamFormat.mChannelsPerFrame = channelsPerFrame;
streamFormat.mFramesPerPacket = 1;

int bytes = (bitsPerChannel / 8) * channelsPerFrame;
streamFormat.mBytesPerFrame = bytes;
streamFormat.mBytesPerPacket = bytes;


text: Q: Solution to remote power cycle embedded devices I am looking for a solution to remotely power cycle embedded devices that are connected via a USB hub to a server. I have a software solution (usbreset.c) that was posted in several responses in stack overflow - rebooting the usb port. This works if the device is still alive, can be detected by the server, but, it just fails to communicate with the server. I have had to use it a few times. however, sometimes the device could hang or freeze on a gui page and there is no serial communication. This requires physically power cycling the device using it's on-off switch. Someone suggested raspberry-pi solution. But as per that solution, I would need one raspberry-pi per device. It's as if using a raspberry-pi to serve as a relay. This is expensive and cannot scale. Could relays work in this situation i.e. the power pins of each device connect to a relay. So, one relay per device. There are remote IP power cycle solutions. so via a web interface it is possible to check which device is offline and power cycle just that one. Such solutions are common in IT. However, is such a solution viable to remote power cycle embedded devices connected at the other end?


text:
Q: Close/Stop Activity before it is shown on Screen This question is little weird.  But Important to me.
Basically I am using a library which shows a full screen Ad from inside of library.
I have to add this activity into my app's manifest, otherwise when library tries to show AdActivity, my app crashes with message "Activity not registered in manifest".
Now I have no option other then registerring AdActivity in Manifest file. and now every time I open the application Library shows this Full screen ad and it is very irritating to users.
As my app is ad free, I would like to stop this activity to be shown!! is there any pointer I can start looking at. I feel there can be three option.
1) Remove AdActivity declaration from manifest and some how handle crash when Library starting AdActivity.
2) Declare AdActivity in Manifest and handle StartActivity call to not let it reach to AdActivity.
3) Let AdActivity be shown,but try to close it down asap from the app.
Please suggest something, I am scratching my head since hours.

A: Have you tried registering the AdActivity, but setting an intent filter that would prevent the AdActivity from being selected ?
Or you could register two activities, forcing android to show a picker for the AdActivity and your own (SkipAdActivity) so the User could at least choose to always run your SkipAdActivity.

A: First option seems to be the best you can do, you can basically try to wrap the call to the library that triggers the AdActivity start inside the try-catch block handling ActivityNotFoundException.


text:
Q: Why can't I play online after changing my profile name? Yesterday, I changed my profile name. Now I can't play online anymore.
When I log on, it says

Account not authenticated with minecraft.net

and

Non-Valid Username.

A: Did you try logging out and logging back in on the Minecraft Launcher? Many times I ran into this problem and this solved the problem.


text: Q: Setup an Android WiFi Hotspot and get login Information How do i set up a hotspot in Android by using code and how can i get infornations about a failed log in? Say, someone want's to connect to the hotspot but is using a wrong password.


text:
Q: Extracting data from new report and compiling specific data to one excel sheet Hello I am trying to create a VBA code where I could automate extracting specific data from new reports and placing them into a home excel sheet. I am using Application.getopenfilename to locate the file but am having issues with errors when i run my code. I get a mismatch error when I try to use For i = 1 To UBound(FileNames)
I have already tried changing the dim i to integer but it didn't work
Sub AutomateReport()
Dim FileNames As Variant
Application.ScreenUpdating = False
Range("A1").Select
FileNames = Application.GetOpenFilename("top 20(*.xlsx)),*.xlsx", ".xlsx", "Insert Latest Top 20 Report", "Import", MultiSelect = True)
Dim i As Integer
For i = 1 To UBound(FileNames)
    Workbooks.Open FileNames(i)
    Range("A1").Select
    Selection.Copy
    Windows("Book1.xlsm").Activate
    Selection.PasteSpecial Paste:=xlPasteAll, Transpose:=True
    Wokbooks.Open FileNames(i)
    ActiveWorkbook.Close Savechanges:=False
    ActiveCells.Offset(1, 0).Activate
Next i

End Sub

I keep recieving the error 13 for mismatched data.

A: I think you have an extra ")" after *.xlsx, you also need to put a colon after multiselect so alltogether
FileNames = Application.GetOpenFilename("top 20(*.xlsx),*.xlsx", , "Insert Latest Top 20 Report", "Import", MultiSelect:= True)

It is interpreting the multiselect as an undefined variable not a parameter accepting an argument.
Edit: You also had an argument as a string ".xlsx" that needs to be an integer or empty.


text:
Q: Signals/Slots Edit buttons are disabled in Qt designer I'm new to Python. I'm studying Python on my own with books. I'm trying using Qt designer following a textbook.
Problem
I can't click a button shown in the following picture. How can I enable the button? I need to set a custom slot named buttonTalkSlot().

What I did
I am sure I did as the textbook says.

*

*Dragged and dropped Push Button and List Widget from Widget Box to MainWindow.

*Changed the mode to Edit Signals/Slots.

*Dragged and dropped from the push button to the list widget.

*Configure Connection popped up, but the edit buttons are disabled.

What I tried
I read the following answers, but I couldn't understand.

*

*Replace QWidget objects at runtime

*Signals and Slots Editing Buttons Are Disabled (Qt Designer 4.8)
My environment

*

*Mac OS (Version 10.14.6)

*Anaconda

*Qt designer (Version 5.9.7)


text:
Q: Sorting Sqlite data while display I have "date"(TEXT) column in db.I want to display dates in ascending order(i.e. group by date).but according to current date.
i.e dates greator or equal than current date should be displayed first and past dates should get appended at last in listview automatically.I used SimpleCursorAdapter to display list.
So how should I do this?

A: Write the proper query and you should be fine. If you are looking for that particular query as an answer to your question, tag it as sql or sqlite as well.

A: You can sort data items when you try to query..here a cursor object set with parameters(just an example),the 7th parameter With "ASC" means that the return data will be in ascending oder
cursor cur = yourdata.query(TableName, coloumns, null, null,null, null, table.COLUMN_NAME + " ASC");
if you want an example you can try this code example
Click me


text:
Q: Adding type argument to EnumSet always give me "Bound mismatch" I have this code below:
public static <E> Set<E> union(Set<E> set1, Set<E> set2) {
    Set<E> resultSet = new HashSet<>(set1);
    resultSet.addAll(set2);
    return resultSet;
}

I want to overload one method like below, and get bound mismatch:
 public static <E> Set<E> union(EnumSet<E extends Enum<E>> set1, EnumSet<E extends Enum<E>> set2){
    Set<E> resultSet = set1.clone();
    resultSet.addAll(set2);
    return resultSet;
}

And I change to below, and it doesn't work.
Why? And how can I do?

A: The class EnumSet is declared as following
public abstract class EnumSet<E extends Enum<E>> extends ... implements ... { ... }

Here you can see that the type variable E is constrained to being a subtype of Enum<E>. Hence, you must constrain the type variable of your static method in the same way:
public static <E extends Enum<E>> Set<E> union(EnumSet<E> set1, EnumSet<E> set2) {
    Set<E> resultSet = set1.clone();
    resultSet.addAll(set2);
    return resultSet;
}


text:
Q: Getting trouble in loading fine-tuned model to call predict I'm new to tensorflow and BERT, n I followed some tutorials on webs to fine-tuning DistilBert by my own dataset on here,
https://medium.com/geekculture/hugging-face-distilbert-tensorflow-for-custom-text-classification-1ad4a49e26a7
My dataset consists of only two column, "message" and "label", looks like,
pic1
I trained model successfully, and predict.proba function also worked well.
but when i saved model, i get some warnings like
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B910694D88>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B97BBC58C8>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B97BCF0E48>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B91071AB08>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B91072E388>, because it is not built.
WARNING:tensorflow:Skipping full serialization of Keras layer <keras.layers.core.dropout.Dropout object at 0x000001B91073FC48>, because it is not built.
WARNING:absl:Found untraced functions such as embeddings_layer_call_fn, embeddings_layer_call_and_return_conditional_losses, transformer_layer_call_fn, transformer_layer_call_and_return_conditional_losses, LayerNorm_layer_call_fn while saving (showing 5 of 164). These functions will not be directly callable after loading.

and when i load saved model and call predict function again, i get error.
i used keras.models.load_model(), tf.saved_model.load() and tf.keras.models.load_model but still getting error like,
ValueError: Exception encountered when calling layer "tf_distil_bert_for_sequence_classification" (type TFDistilBertForSequenceClassification).
Could not find matching concrete function to call loaded from the SavedModel.Got:
  Positional arguments (9 total):
    * {'input_ids': <tf.Tensor 'input_ids_1:0' shape=(None, 100) dtype=int32>, 'attention_mask': <tf.Tensor 'input_ids:0' shape=(None, 100) dtype=int32>}
    * None
    * None
    * None
    * None
    * None
    * None
    * None
    * False
  Keyword arguments: {}

 Expected these arguments to match one of the following 2 option(s):

Option 1:
  Positional arguments (9 total):
    * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
    * None
    * None
    * None
    * None
    * None
    * None
    * None
    * False
  Keyword arguments: {}

Option 2:
  Positional arguments (9 total):
    * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
    * None
    * None
    * None
    * None
    * None
    * None
    * None
    * True
  Keyword arguments: {}

Call arguments received:
  • args=({'input_ids': 'tf.Tensor(shape=(None, 100), dtype=int32)', 'attention_mask': 'tf.Tensor(shape=(None, 100), dtype=int32)'},)
  • kwargs={'training': 'False'}

I'm confused why saved model doesn't work same as before. Can i get any advice?
Here's my full code:
import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
import transformers
from transformers import DistilBertTokenizer
from transformers import TFDistilBertForSequenceClassification
from transformers import TFTrainer, TFTrainingArguments

pd.set_option('display.max_colwidth', None)
BATCH_SIZE = 16
N_EPOCHS = 3

df = pd.read_csv('twitter.csv', names=["message", "label"], encoding='cp949')

X = list(df['message'])
y = list(df['label'])
y = list(pd.get_dummies(y,drop_first=True)[True])

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')

train_encodings = tokenizer(X_train, truncation=True, padding=True)
test_encodings = tokenizer(X_test, truncation=True, padding=True)

train_dataset = tf.data.Dataset.from_tensor_slices((
    dict(train_encodings),
    y_train
))

test_dataset = tf.data.Dataset.from_tensor_slices((
    dict(test_encodings),
    y_test
))

model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")

#chose the optimizer
optimizerr = tf.keras.optimizers.Adam(learning_rate=5e-5)

#define the loss function
losss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

#build the model
model.compile(optimizer=optimizerr,
              loss=losss,
              metrics=['accuracy'])

history = model.fit(train_dataset.shuffle(len(X_train)).batch(BATCH_SIZE),
          epochs=N_EPOCHS,
          batch_size=BATCH_SIZE)

# model evaluation on the test set
model.evaluate(test_dataset.shuffle(len(X_test)).batch(BATCH_SIZE),
               return_dict=True,
               batch_size=BATCH_SIZE)

# tests
def predict_proba(text_list, model, tokenizer):
    #tokenize the text
    encodings = tokenizer(text_list,
                          max_length=1000,
                          truncation=True,
                          padding=True)
    #transform to tf.Dataset
    dataset = tf.data.Dataset.from_tensor_slices((dict(encodings)))
    #predict
    preds = model.predict(dataset.batch(1)).logits

    #transform to array with probabilities
    res = tf.nn.softmax(preds, axis=1).numpy()

    return res

examples = [
    'In 2008, several failing banks were bailed out partially using taxpayer money. Putting all money at bank provide risk, risk of devaluation, risk of inflation, risk of aggressive centralise policy. Decentralized system like bitcoin working on blockchain provide relief.',
    'Bitcoin is counterfeit. Disagree? Look again.',
    'Did I make a bad GPU purchase before the end of Ethereum mining?',
    '@Mamooetz Help. I created this bot to reply to ETH, BITCOIN, and NFT but I dont know how to shut it off.',
    '@WaldorickWilson Cryptocurrency doesnt have to be cryptic. Luno takes the complexity out of #Bitcoin and lets you buy, store, learn and earn all in one place',
]

result = predict_proba(examples, model, tokenizer)
print(result)

# save model
dataset_name = 'adv'
saved_model_path = './{}_bert'.format(dataset_name.replace('/', '_'))

# model.save(saved_model_path)
tf.saved_model.save(model, saved_model_path)

# load model
loaded_model = tf.saved_model.load(saved_model_path)
inference_function = loaded_model.signatures['serving_default']

reloaded = tf.keras.models.load_model(saved_model_path)
predict_proba(examples, reloaded, tokenizer)


text:
Q: Routing issues in Rails when a Blog component was added The app was working fine until we added a blog. Then, we started having some routing issues. Every link on the navbar still works fine, including the blog link, which opens the index of of all the posts. When you click on one of the links to go to a specific post, the page displays, as it should. But, in order for a user to make a comment, he/she needs to login or signup. So, we put two links  on the page. The problem is when you click on one of these links, or any other link on the navbar, you get an error message, a typical message is as follows:
Couldn't find Post with id=login
At this point, we are not at the root anymore. In this instance, the address bar reads:
http://localhost:3000/posts/login

The only way to get to the root is by clicking a 'Back' link on the page , which takes the user back to the Blog index page.
This is what my routes file looks like:
Septactus::Application.routes.draw do
  devise_for :admins
  devise_for :users, :path => "auth", :path_names => {
                                                   :sign_in => 'login',
                                                   :sign_out => 'logout',
                                                   :password => 'secret',
                                                   :confirmation => 'verification',
                                                   :unlock => 'unblock',
                                                   :registration => 'register',
                                                   :sign_up => 'cmon_let_me_in'
                                                  }
 devise_for :users, :controllers => {:registrations => 'registrations'}

 match '/home',         :to => 'site_pages#home'
 match '/about',        :to => 'site_pages#about'
 match '/bookshelf',    :to => 'books#index'
 match '/blog',         :to => 'posts#index'
 match '/icasts',       :to => 'site_pages#icasts'
 match '/portfolio',    :to => 'site_pages#portfolio'

 devise_scope :user do
   match "login",   :to => 'devise/sessions#new'
   match 'logout',  :to => 'devise/sessions#destroy'
   match 'signup',  :to => 'devise/registrations#create'
 end

 resources :site_pages
 resources :books
 resources :users
 resources :posts do
  resources :comments
 end

 root :to => 'site_pages#home'

end

Any clue, anyone?

A: Here is the problem in this line:

To add a comment, <%= link_to 'Login', 'login' %> or <%= link_to 'Signup', "signup" %>

you need to change to

To add a comment, <%= link_to 'Login', login_path %> or <%= link_to 'Signup', signup_path %>

A: I finally managed to fix this issue. And here is the solution for those who might come across it in the future:
As everyone knows, Rails routing uses controller#action to specify a route to a page: for instance: pages#home
If you go beyond the boundaries of the controller (in this instance 'pages'), which is the root, to get to another page/link on another controller, for example a posts' controller and try to reach a page on the 'pages' controller, such as in:
     http://localhost:3000/posts/about

you'll get an error. That's because the routes.rb does not contain a path to that link from where you are, so you have to tell it how to get there. That is exactly what I did:
Here are the routes (untouched) for the site_pages' controller: [http://localhost:3000]
match '/home',         :to => 'site_pages#home'
match '/about',        :to => 'site_pages#about'
match '/bookshelf',    :to => 'books#index'
match '/blog',         :to => 'posts#index'
match '/icasts',       :to => 'site_pages#icasts'
match '/portfolio',    :to => 'site_pages#portfolio'

Here are the new routes for the posts' controller requested from this controller: http://localhost:3000/posts/[id]/
match "/posts/home(.:format)"      => "site_pages#home", :as      => :home
match "/posts/about(.:format)"     => "site_pages#about", :as     => :about
match "/posts/bookshelf(.:format)" => "books#index", :as          => :bookshelf
match "/posts/blog(.:format)"      => "posts#index",   :as        => :blog
match "/posts/icasts(.:format)"    => "site_pages#icasts", :as    => :icasts
match "/posts/portfolio(.:format)" => "site_pages#portfolio",:as  => :portfolio

And here are the routes to Devise 'login', 'logout', and 'signup' links going from the posts' controller (the last 3 lines):
devise_scope :user do
  match "login",          :to  => 'devise/sessions#new'
  match 'logout',         :to  => 'devise/sessions#destroy'
  match 'signup',         :to  => 'devise/registrations#create'
  match "/posts/login",   :to  => "devise/sessions#new"
  match "/posts/logout",  :to  => "devise/sessions#destroy"
  match "/posts/signup",  :to  => "devise/sessions#create"
end

NB. If Devise links are not wrapped within the Devise scope, Rails will return an error.
I hope this helps.


text:
Q: Join two dataframe with two columns [ one of datetime column ] in R I have two df and I'm trying to left or right join them based on two-column. ID and Datetime column. how do I allow DateTime from another df to match the first df even if it's within 10-20sec difference range?
df1 :

ID
Datetime

123
2021-04-02 09:50:11

456
2021-04-02 09:50:15

df2:

ID
Datetime

123
2021-04-02 09:50:31

456
2021-04-02 09:50:23

if the times are within 10-20 diff on df2, return all the columns and DateTime column from the df2 to new,df3.  For all matching IDs and yyyy-mm-dd H:M matches to both dfs. so if the change in :SS is between 10-20 on df2, pick it and do join, If its not within 10-20sec range,skip. someone, please help?

A: Your sample data is very minimalistic. Not sure how you wanetd to implement the 10-20 secs. I assumed everything within -20 to +20 seconds should be matched. This can easily be adjusted in filtering part ID == i.ID & Datetime <= (i.Datetime + 20) & Datetime >= (i.Datetime - 20).
Here is a data.table approach
library(data.table)
# Sample data
DT1 <- fread("ID    Datetime
123     2021-04-02T09:50:11
456     2021-04-02T09:50:15")
DT2 <- fread("ID    Datetime
123     2021-04-02T09:50:31
456     2021-04-02T09:50:23")
# Set datetimes to posix
DT1[, Datetime := as.POSIXct(Datetime)]
DT2[, Datetime := as.POSIXct(Datetime)]

# possible rowwise approach
DT1[, rowid := .I]
setkey(DT1, rowid)
DT1[DT1, Datetime2 := DT2[ID == i.ID & Datetime <= (i.Datetime + 20) & Datetime >= (i.Datetime - 20),
                          lapply(.SD, paste0, collapse = ";"), .SDcols = c("Datetime")],
    by = .EACHI][, rowid := NULL][]

#     ID            Datetime           Datetime2
# 1: 123 2021-04-02 09:50:11 2021-04-02 09:50:31
# 2: 456 2021-04-02 09:50:15 2021-04-02 09:50:23

A: If I understand correctly, the OP wants to retrieve those rows of df2 (including all columns) which have a matching ID in df1 and where the time difference of the time stamps Datetime between df1 and df2 is less or equal than a given value.
So, for the given sample data

*

*if the allowed time difference is 20 seconds at most both rows of df2 are returned.

*If the allowed time difference is 10 seconds at most only the second row of df2 with ID == 456 is returned.

*If the allowed time difference is 5 seconds at most an empty dataset is returned because non of df2's rows fulfills the conditions.

One possible approach is to use a non-equi join which is available with data.table:
library(data.table)
timediff <- 10 # given time difference in seconds
setDT(df1)[, Datetime := as.POSIXct(Datetime)]
setDT(df2)[, Datetime := as.POSIXct(Datetime)]
df2[, c("from", "to") := .(Datetime - timediff, Datetime + timediff)]
df3 <- df2[df1, on = c("ID", "from <= Datetime", "to >= Datetime"),
           nomatch = NULL, .SD][
             , c("from", "to") := NULL][]
df3

    ID            Datetime
1: 456 2021-04-02 09:50:23

If the code is run with
timediff <- 20

the result is
df3

    ID            Datetime
1: 123 2021-04-02 09:50:31
2: 456 2021-04-02 09:50:23

If the code is run with
timediff <- 5

df3 becomes an empty data.table.
EDIT: Show Datetime from df1 and df2
By request of the OP, here is a version which returns both Datetime columns from df1 and df2, renamed as Datetime1 and Datetime2, resp.,:
library(data.table)
timediff <- 20 # given time difference in seconds
setDT(df1)[, Datetime := as.POSIXct(Datetime)]
setDT(df2)[, Datetime := as.POSIXct(Datetime)]
df2[, c("from", "to") := .(Datetime - timediff, Datetime + timediff)]
df3 <- df2[setDT(df1), on = c("ID", "from <= Datetime", "to >= Datetime"),
           nomatch = NULL, .(ID, Datetime1 = i.Datetime, Datetime2 = x.Datetime)]
df3

    ID           Datetime1           Datetime2
1: 123 2021-04-02 09:50:11 2021-04-02 09:50:31
2: 456 2021-04-02 09:50:15 2021-04-02 09:50:23


text:
Q: Try to use bs4 get some infos from wikipedia I started to learn python this year as the new year resolutions;P I encountered some problems when self-learning web-scraping. This may be a dumb questions but I hope someone can point out problems of my codes.
Thanks in advance!
I want to web-scraping from Wikipedia Nobel Economic Prize https://en.wikipedia.org/wiki/List_of_Nobel_Memorial_Prize_laureates_in_Economics
# I first get the whole table
wiki_table = soup.find('table',{'class':'wikitable'})

print(wiki_table)
# And grab the td information
name_list = wiki_table('td')
print(name_list)
type(name_list) #bs4.element.ResultSet
type(name_list[0:]) # list

# My goal is to separate laureate's name from other descriptions i.e. countries, years...What I plan to do is first get some lists containing people's names and then clean others unwanted strings.
# I tried to loop both the bs4 type and list type

laurates=[]
for a in name_list:
    laurates.append(name_list.find_all(class='a'))
print(laurates)

# I looped for a here because the html is like `<a href="/wiki/Ragnar_Frisch" title="Ragnar Frisch">Ragnar Frisch</a>`. I thought the name is with the a code (or I interpreted wrongly?)

A: The simplest way(in this case) is just to load the table into a pandas dataframe and then extract from that whatever items you need using the usual pandas methods. So
import pandas as pd
url = "https://en.wikipedia.org/wiki/List_of_Nobel_Memorial_Prize_laureates_in_Economics"

pd.read_html(url)

will output the table on that page.


text:
Q: How to force discarding ALL my unstaged changes in Git How to remove the items under "Changes not staged for commit:". I found many other tickets in this regards, but none actually worked with me.
What happened ?
I checked out the development branch. But after i edited some local files, these files got stuck in the Unstaged list. Can't stash, clean, rm or even reset --hard them at all. The problem happened when i was trying to remove my local changes by checking out origin/mybranch then trying to reset from there.
Some how i have now an outdated branch. Every time i do :
git fetch origin
git reset --hard origin/mybranch

the unstaged changes STILL there.
modified : *.xlsx

Ho can i force removal of these local changes. It seems the only solution is to clone a clean revision again, but i'm trying to fix it first.

A: Try:
git checkout .

The '.' is used to indicate that you want to replace ALL the files with the version present in origin.

A: The changes not staged can be "removed" using the following command:
git checkout -- <filename>

Or, if you want to remove all the changes, you can use .
git checkout -- .

This should be sufficient to remove items under "Changes not staged for commit".

A: If these files you've changed are within a tracked directory and you are looking to permanently exclude them from the project, you would need to add them to your repository's .gitignore file.

A: So this problem happened only with .xlsx files because every time it's opened by Excel it create a hidden file $.xlsx. Apparently the same issue with other office document files. If i added the changes through :
git add .

It will blindly add even the hidden file $*.xlsx . So after i closed the file, automatically it was removed from the system but not from git because it was added already, git still sees it and can't ignore it or even remove because it was untracked.
What worked for me that i opened the excel file, add, then commit without issues. After that i can remove as any other file.


text:
Q: exception while using ksoap2 library for android I'm using Ksoap2 version 2.5.4 in my maven enabled android Project. Any reference to the Ksoap specific classes is throwing this exception
04-18 20:35:15.429: ERROR/dalvikvm(626): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method com.rare.Main.fetchSoapResponse
04-18 20:35:15.662: ERROR/AndroidRuntime(626): FATAL EXCEPTION: main
04-18 20:35:15.662: ERROR/AndroidRuntime(626): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at com.rare.Main.fetchSoapResponse(Main.java:57)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at com.rare.Main.onCreate(Main.java:23)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.os.Looper.loop(Looper.java:123)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at android.app.ActivityThread.main(ActivityThread.java:3683)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at java.lang.reflect.Method.invokeNative(Native Method)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at java.lang.reflect.Method.invoke(Method.java:507)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-18 20:35:15.662: ERROR/AndroidRuntime(626):     at dalvik.system.NativeStart.main(Native Method)

the line of code causing this is
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

Couldn't find any help related to this on SO or other forums. This seems pretty straight forward. Can any one tell me whats missing and how I can make android use the library at run time.

A: *

*In your build path clear all libraries (jar files).

*In project's main directory create a folder and named it "libs" (not
"lib").

*Now Eclipse ADT Plugin will add your jar files to build path.

*Clean & Build your project if necessary.

*Happy coding

A: I had the same problem.I have added ZIP file instead of jar file to external library, you need to add only the JAR file.


text:
Q: libspotify API: multiple album cover? Given an artist name and an album name, how many cover arts the album could have? I thought it would be only one, but got two album cover arts when searching the artist name "Dire Straits" and album name "Brothers In Arms".

A: One album has one album cover. However, there may be re-releases of the same album that might have different covers. However, one sp_album instance will only have one cover.


text:
Q: How to populate the Django Model with the data fetched from the external site? From the external site thru API, I have fetched the dictionary data that I want to save it to the Django Model.
I have tried to save the data to the Django Model at the models.py but failed.
In the models.py, I wrote the def get_save(self, request) like the following.
class AirData(models.Model):
    co = models.DecimalField(max_digits=5, decimal_places=2)
    no2 = models.DecimalField(max_digits=5, decimal_places=2)
    so2 = models.DecimalField(max_digits=5, decimal_places=2)
    pm10 = models.DecimalField(max_digits=5, decimal_places=2)
    pm25 = models.DecimalField(max_digits=5, decimal_places=2)
    datatime = models.DateTimeField(blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    station = models.CharField(max_length=80)

    def get_save(self, request):

            url = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"

            params = {'stationName': '강남구', 'dataTerm': 'month', 'pageNo': '1', 'numOfRows': '10',
                      '_returnType': 'json', 'ServiceKey': service_key, 'ver': '1.3'}
            airdata_dict = get_airdata(url, service_key, params)

            self.co = airdata_dict['coValue']
            self.save()

But the airdata_dict, fetched from the url, is not saved to the instance.
Please help me show how to save data in the Model.

Based on the suggestions of @HariHaraSudhan, I changed the views.py as follows
def get_value(self):
    url = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"

    params = {'stationName': '강남구', 'dataTerm': 'month', 'pageNo': '1', 'numOfRows': '10',
              '_returnType': 'json', 'ServiceKey': service_key, 'ver': '1.3'}
    airdata_dict = get_airdata(url, service_key, params)
    airdata_list = airdata_dict['airdata']
    kwargs = dict()
    for data in airdata_list:
        kwargs['station'] = data['stationName']
        kwargs['co'] = data['coValue']
        kwargs['no2'] = data['no2Value']
        kwargs['so2'] = data['so2Value']
        kwargs['o3'] = data['o3Value']
        kwargs['pm10'] = data['pm10Value']
        kwargs['pm2.5'] = data['pm25Value']
        kwargs['time'] = data['dataTime']

    obj = AirData.objects.create(self.kwargs)

And the models.py is also changed as:
class AirData(models.Model):
    @classmethod
    def create(cls, **kwargs):
        my_obj = cls(kwargs)
        return my_obj

But the error pops up as AttributeError: 'WSGIRequest' object has no attribute 'kwargs'.

A: Your model method get_save should work if:

*

*You make sure you cast the strings received by the API (airdata['coValue']) to the correct type, e.g. for co:
self.co = Decimal(airdata['coValue'])

Beware also that your dates are strings, so you need to change them to a proper datetime.datetime if you're going to assign them.

*You make sure all required fields are set before saving (self.no2 is required, so if it's None, your model will not save). You should see an error in that case.
An easier way is to create a dictionary of all the correct values, e.g.
kwargs['co'] = Decimal(airdata['coValue'])
...

and pass it to the ModelManager's create() method:
MyModel.objects.create(**kwargs)

Make sure all the keys in the dictionary correspond to fields of your model.


text:
Q: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index' python I want to compute Compound monthly stock returns over 12 months to obtain annual returns.
Here is what I have done, but I am getting an error massage
Month_Return = pd.read_csv("Monthly Stock Return.csv")
Month_Return.set_index('gvkey', inplace=True,drop = False)
Month_Return['Date'] =  pd.to_datetime(Month_Return['Date'], format='%Y%M%d')
Month_Return['Date'] = Month_Return['Date'].dt.date

gvkey  issue   datadate    ticker  Company_name  Price_Close_Monthly    Stock Exchange  gsector

1003    1     2003-01-31    ANTQ    A.A             0.0400                  19.0        25.0
1003    1     2004-01-31    ANTQ    A.A.            0.0400                  19.0        25.0
1003    1     2004-01-29    ANTQ    A.A.            0.0400                  19.0        25.0
1003    1     2004-01-31    ANTQ    A.B             0.0400                  19.0        25.0
1003    1     2004-01-30    ANTQ    A.C             0.0001                  19.0        25.0

Then I retrieved the colunm I need to calculate the monthly return
Month_Return_annual.set_index('Date', inplace=True)
Month_Return_annual.index

 Date      Price_Close_Monthly
2003-01-31  0.0400
2004-01-31  0.0400
2004-01-29  0.0400
2004-01-31  0.0400
2004-01-30  0.0001
2017-01-30  3.7600

results_storage['month'] = Month_Return_annual.index.month
results_storage['year'] = Month_Return_annual.index.year

Traceback:
AttributeError Traceback (most recent call last)
 <ipython-input-855-f1ce19fc30ac> in <module>
  ----> 1 results_storage['month'] = Month_Return_annual.index.month
  2 results_storage['year'] = Month_Return_annual.index.year

 AttributeError: 'Index' object has no attribute 'month'

I understand that this error is coming from the .month method, But is there another way to achieve this..?
I fixed the first error using this
Month_Return_annual.index = pd.to_datetime( Month_Return_annual.index,
                                     errors='coerce')

I also got another error massage when I tried calculating the monthly return
results_storage['month'] = Month_Return_annual.index.month
results_storage.head()

 Date       Price_Close_Monthly     year    month
 2003-01-31     0.0400              2003    1
 2004-01-31     0.0400              2004    1
 2004-01-29     0.0400              2004    1
 2004-01-31     0.0400              2004    1
 2004-01-30     0.0001              2004    1

df_Month_Return_annual = results_storage[['Price_Close_Monthly']].
                                   resample('M').ffill().pct_change()

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but
got an instance of 'Index'


text:
Q: How to create a global transaction in c# between Oracle DB and MQ I need to create an integration flow to move MQ message in a db table.
I would like ensure that:

*

*there is just one reader in MQ at time

*if something goes wrong during the db insert, I must leave the message in the queue

Could you suggest an example code?


text:
Q: TypeScript string literal to basic type I have some settings in a JSON file and if i return one setting value, i want it to be typed:
[
    {
        "name":"setting_1",
        "type":"number",
        "value":"12"
    },
    {
        "name":"setting_2",
        "type":"boolean",
        "value":"false"
    },
    {
        "name":"setting_2",
        "type":"string",
        "value":"setting string"
    }
]

Is it possible to have one function to get the value of the setting returned with the type of the type-attribute?
const settings = [
  { name: 'setting_1', type: 'number', value: '12' },
  { name: 'setting_2', type: 'boolean', value: 'false' },
  { name: 'setting_2', type: 'string', value: 'default string' },
];

function getSetting(name: string): <Type> {
  const { value, type } = settings.find((s) => s.name === name);

  return <type>value;
}

const setting: boolean = getSetting('setting_2');

So that i get errors like this:
const setting: number = getItems('setting_2'); >> TS2322: Type 'boolean' is not assignable to type 'number'.


text:
Q: Accordian Jquery - Toggle Button implementation I have a jquery accordian menu project that I built on the jquery website.
In the accordian menu I have an iframe. I want to toggle between 2 iframes in this menu. So outside of the iframe that is shown on load for first time. I would like to show a toggle button , on clicking which it will take me to a new iframe. Again on click of this iframe it must take me back to the default page.
Please find the project in this link : https://app.box.com/s/vmkhhxcq4gfji2hxwtwx
Kindly help me build a working toggle button below the iframe to toggle between the default src and a new src.
HTML ->
<!doctype html>

    <meta charset="utf-8">
    <link href="css/BlueTheme/jquery-ui-1.10.4.custom.css" rel="stylesheet">

Sample Iframe

This is the html..trying this link : http://jsfiddle.net/ChaseWest/AvEqM/
How to get it to work ?
Thanks

A: I believe you are trying to change this from a two button system to a single toggle button. If that is correct, try this.

<button id="one">toggle</button>


text:
Q: JQuery to find element Given this xpath syntax
//div[@class="sk-circle-container"]

Can somebody convert it to find the div that has attr class sk-circle-container in the entire DOM as JQuery script?
This seems to not find anything, even if the element is there: div:contains(sk-circle-container)

A: Try this one:-
driver.get(" https://www.XYZXYZXYZ.com/");

List<WebElement> list = driver.findElements(By.xpath("//div[@class='sk-circle-container']"));

OR
    List<WebElement> myList = driver.findElements(By.className("sk-circle-container"));
ListIterator<WebElement> myListIterat= myList.listIterator();


text:
Q: С++. Явная специализация. Не является специализацией функции-шаблона Создаю класс множество(Set) на C++. Использую класс BitScale(шкалу битов) для удобного поведения класса Set. Столкнулся с проблемой при реализации метода map. Задумка метода:
(В моём случае не список, а множество).
Суть проблемы: есть оператор объединения в множестве Set& operator |=(T2&& item) - для элемента множества, а есть Set& operator |=<T>(const Set&& set) - для объединения другого множества. Компилятор не может понять, какой шаблон когда использовать:
Например, в main.cpp set1 |= set2; вызывает ошибку "Ошибка    C2912   явная специализация; "Set &Set::operator |=(const Set &&)" не является специализацией функции-шаблона". Тобишь компилятору не нравится как я написал явную специализацию... Нужна помощь...
Ниже реализация класса Set(с методом map), класса BitScale и главная ф-я main.
#pragma once
#include "BitScale.h"

template <class T>
class Set
{
    int reserve_;
    int capacity_;
    BitScale bitScale_;
    T **array_;
public:
    Set(int reserve = 256) :
        reserve_(reserve)
        , capacity_(0)
        , bitScale_(reserve)
        , array_(new T*[reserve_])
    {}
    Set(const Set& arg) : reserve_(arg.reserve_)
        , capacity_(arg.capacity_)
        , bitScale_(arg.bitScale_)
    {
        memcpy(array_, arg.array_, reserve_ * sizeof(T*));
    }

    int capacity() {
        return capacity_;
    }

    void print() {
        bitScale_.print();
    }

    void resize() {
        reserve_ *= 2;
        T **buf = new T*[reserve_];
        memcpy(buf, array_, (reserve_ / 2) * sizeof(T*));
        delete[] array_;
        array_ = buf;
        bitScale_.resize();
    }

    bool hasItem(const T& item)
    {
        return bitScale_.hasBit(item.id);
    }

    template <class T2>
    Set& operator |=(T2&& item)
    {
        while (item.id >= reserve_)
            resize();
        if (!hasItem(item)) capacity_++;
        bitScale_.setBit(item.id);
        array_[item.id] = &item;
        return *this;
    }

    template<>
    Set& operator |=<T>(const Set&& set)
    {
        while (set.reserve_ > reserve_)
            resize();
        bitScale_ |= set.bitScale_;
        capacity_ = countCapacity(bitScale_);
        addItems(set);
        return *this;
    }

    /*
    Set& operator |(int item)
    {
        Set buf = *this;
        buf |= item;
        return buf;
    }
    Set& operator |(const Set& arg)
    {
        Set buf = *this;
        buf |= arg;
        return buf;
    }
    */
    Set& operator -=(T& item)
    {
        if (hasItem(item)) capacity_--;
        bitScale_.clearBit(item.id);
        return *this;
    }

    Set& operator -=(const Set& set)
    {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        capacity_ -= countCapacity(bufBitScale);
        bitScale_ -= set.bitScale_;
        return *this;
    }
    /*
    Set& operator -(const Set& arg)
    {
        Set buf = *this;
        buf -= arg;
        return buf;
    }
    */

    Set& operator &=(const Set & set) {
        bitScale_ &= set.bitScale_;
        capacity_ = countCapacity(bitScale_);
        return *this;
    }
    /*
    Set& operator &=(T& item) {
        Set bufSet();
        bufSet |= item;
        bitScale_ &= bufSet.
        capacity_ = countCapacity(bitScale_);
        return *this;
    }
    */

    bool operator<=(const Set& set) {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        return capacity_ == countCapacity(bufBitScale);
    }

    bool operator>=(const Set& set) {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        return set.capacity_ == countCapacity(bufBitScale);
    }

    bool operator==(const Set& set) {
        return ((*this >= set) && (*this <= set));
    }

    bool operator!=(const Set& set) {
        return !(*this == set);
    }

    template <class T2>
    Set<T2>* map(T2*(*f)(T *item)) {
        Set<T2> bufSet;
        BitScale buf = bitScale_;
        int id;
        using Word = unsigned short;
        Word bufWord;
        for (int i = 0; i < buf.numWords_; i++) {
            bufWord = buf.words_[i];
            for (int j = 0; j < buf.WordBitSize_ - 1; j++) {
                if (bufWord & 1 == 1) {
                    id = i * buf.WordBitSize_ + j;
                    bufSet |= *(f(array_[id]));
                }
                bufWord >>= 1;
            }
        }
        return &bufSet;
    }

private:
    int countCapacity(const BitScale& arg) {
        using Word = unsigned short;
        int count = 0;
        Word buf;
        for (int i = 0; i < arg.numWords_; i++) {
            buf = arg.words_[i];
            for (int j = 0; j < arg.WordBitSize_ - 1; j++) {
                if (buf & 1 == 1)
                    count++;
                buf >>= 1;
            }
        }
        return count;
    }

    void addItems(const Set& set) {
        BitScale buf = set.bitScale_;
        buf -= bitScale_;
        int id;
        using Word = unsigned short;
        Word bufWord;
        for (int i = 0; i < buf.numWords_; i++) {
            bufWord = buf.words_[i];
            for (int j = 0; j < buf.WordBitSize_ - 1; j++) {
                if (bufWord & 1 == 1) {
                    id = i * buf.WordBitSize_ + j;
                    array_[id] = set.array_[id];
                }
                bufWord >>= 1;
            }
        }
    }
};

main.cpp с тестами.
#include <iostream>
#include <bitset>
#include "Set.h"
using namespace std;
typedef unsigned short Word;

struct B;

struct A {
    int id;
    B *b;
};

struct B{
    int id;
};

B* who(A *item) {
    return item->b;
}

int main()

{
    setlocale(LC_ALL, "");
    B b{ 1 };
    B bb{ 2 };
    A a{ 1, &b };
    A aa{ 2, &bb };
    Set<A> set1;
    set1 |= a;

    Set<A> set2;
    set2 |= aa;
    set1 |= set2;
    Set<B> *set3 = set1.map(who);
    cout << set3->capacity();
    set3->print();
    system("pause>nul");
    return 0;
}

BitScale.cpp
#include <iostream>
#include <stdexcept>
#include <bitset>
#include "BitScale.h"
using namespace std;

const int BitScale::WordBitSize_ = 16;

BitScale::BitScale(int numBits)
{
    numBits_ = numBits;
    numWords_ = (numBits_ + WordBitSize_ - 1) / WordBitSize_;
    words_ = new Word[numWords_];
    memset(words_, 0, numWords_ * sizeof(Word));
}

BitScale::BitScale(const BitScale& arg)
{
    numBits_ = arg.numBits_;
    numWords_ = arg.numWords_;
    words_ = new Word[numWords_];
    memcpy(words_, arg.words_, numWords_ * sizeof(Word));
}

BitScale::~BitScale()
{
    delete[] words_;
}

void BitScale::print()
{
    for (int i = 0; i < numWords_; i++) {
        printf("%-3d) ", i);
        cout << std::bitset<WordBitSize_>(words_[i]) << endl;
    }
}

bool BitScale::hasBit(int bit)
{
    if (bit < 0 || bit >= numBits_)
        return false;
    return (words_[bit / WordBitSize_] &
        (1 << bit % WordBitSize_)) != 0;
}

BitScale& BitScale::setBit(int bit)
{
    if (bit < 0)
        throw runtime_error("Signed bit.");
    while (bit >= numBits_)
        resize();
    words_[bit / WordBitSize_] |= (1 << bit % WordBitSize_);
    return *this;
}

BitScale& BitScale::clearBit(int bit)
{
    if (bit < 0 || bit >= numBits_)
        return *this;
    words_[bit / WordBitSize_] &= ~(1 << bit % WordBitSize_);
    return *this;
}

BitScale& BitScale::operator=(const BitScale& arg)
{
    numBits_ = arg.numBits_;
    numWords_ = arg.numWords_;
    words_ = new Word[numWords_];
    memcpy(words_, arg.words_, numWords_ * sizeof(Word));
    return *this;
}

BitScale& BitScale::operator |=(const BitScale& arg)
{
    while (numBits_ < arg.numBits_) {
        resize();
    }
    for (int i = 0; i < arg.numWords_; i++)
        words_[i] |= arg.words_[i];
    return *this;
}

BitScale& BitScale::operator &=(const BitScale& arg)
{
    for (int i = 0; i < numWords_; i++)
        words_[i] &= arg.words_[i];
    return *this;
}

BitScale& BitScale::operator -=(const BitScale& arg)
{
    for (int i = 0; i < numWords_; i++)
        words_[i] &= ~arg.words_[i];
    return *this;
}

void BitScale::resize() {
    numBits_ *= 2;
    int lastNum = numWords_;
    numWords_ = (numBits_ + WordBitSize_ - 1) / WordBitSize_;
    Word *bufWords = new Word[numWords_];
    memset(bufWords, 0, numWords_ * sizeof(Word));
    memcpy(bufWords, words_, lastNum * sizeof(Word));
    delete[] words_;
    words_ = bufWords;
}

A: Так а что это за "специализация" такая? Что вы хотели сказать этим
template <>
Set& operator |=<T>(const Set&& set)

?
Явная специализация должна соответствовать своему основному шаблону
template <class T2>
Set& operator |=(T2&& item)

У вас в треугольных скобах в специализации явно указано, что специализация делается для типа T2 == T, а в списке параметров функции указано const Set &&, то есть согласно списку параметров специализация делается для T2 == const Set<T>.
Это какая-то сама себе противоречащая белиберда. Для какого значения шаблонного параметраT2 вы хотите сделать специализацию? Для T2 == T или для T2 == const Set<T>? Именно это и не может понять компилятор.
К тому же параметр основного шаблона у вас является "универсальной ссылкой". Параметр вашей специализации выглядит довольно необычно - const Set &&, т.е. rvalue-ссылка на константу. Интересно, какие варианты вызова вашей шаблонной функции вы собираетесь покрыть такой специализацией?

A: Решил вопрос, почитав немного статей про шаблоны в C++. Я действительно, криво пытался реализовать специализацию шаблона, из-за этого программа и не компилировалась.
Кому интересно, что вышло:
Set.h
#pragma once
#include "BitScale.h"

template <class T>
class Set
{
    int reserve_;
    int capacity_;
    BitScale bitScale_;
    T **array_;
public:
    Set(int reserve = 256) :
        reserve_(reserve)
        , capacity_(0)
        , bitScale_(reserve)
        , array_(new T*[reserve_])
    {}

    Set(const Set& arg) : reserve_(arg.reserve_)
        , capacity_(arg.capacity_)
        , bitScale_(arg.bitScale_)
    {
        array_ = new T*[reserve_];
        memcpy(array_, arg.array_, reserve_ * sizeof(T*));
    }

    Set& operator =(const Set& arg)
    {
        reserve_ = arg.reserve_;
        capacity_ = arg.capacity_;
        bitScale_ = arg.bitScale_;
        array_ = new T*[reserve_];
        memcpy(array_, arg.array_, reserve_ * sizeof(T*));
        return *this;
    }

    ~Set() {
        delete[] array_;
    }

    int capacity() {
        return capacity_;
    }

    void print() {
        bitScale_.print();
    }

    void resize() {
        reserve_ *= 2;
        T **buf = new T*[reserve_];
        memcpy(buf, array_, (reserve_ / 2) * sizeof(T*));
        delete[] array_;
        array_ = buf;
        bitScale_.resize();
    }

    bool hasItem(const T& item)
    {
        return bitScale_.hasBit(item.id);
    }

    Set& operator |=(T& item)
    {
        while (item.id >= reserve_)
            resize();
        if (!hasItem(item)) capacity_++;
        bitScale_.setBit(item.id);
        array_[item.id] = &item;
        return *this;
    }

    Set& operator |=(Set& set)
    {
        while (set.reserve_ > reserve_)
            resize();
        addItems(set);
        bitScale_ |= set.bitScale_;
        capacity_ = countCapacity(bitScale_);
        return *this;
    }

    Set& operator -=(T& item)
    {
        if (hasItem(item)) capacity_--;
        bitScale_.clearBit(item.id);
        return *this;
    }

    Set& operator -=(const Set& set)
    {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        capacity_ -= countCapacity(bufBitScale);
        bitScale_ -= set.bitScale_;
        return *this;
    }

    Set& operator &=(const Set & set) {
        bitScale_ &= set.bitScale_;
        capacity_ = countCapacity(bitScale_);
        return *this;
    }

    bool operator<=(const Set& set) {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        return capacity_ == countCapacity(bufBitScale);
    }

    bool operator>=(const Set& set) {
        BitScale bufBitScale;
        bufBitScale = set.bitScale_;
        bufBitScale &= bitScale_;
        return set.capacity_ == countCapacity(bufBitScale);
    }

    bool operator==(const Set& set) {
        return ((*this >= set) && (*this <= set));
    }

    bool operator!=(const Set& set) {
        return !(*this == set);
    }

    template <class T2>
    Set<T2>* map(T2*(*f)(T *item)) {
        Set<T2> *bufSet = new Set<T2>;
        BitScale buf = bitScale_;
        int id;
        using Word = unsigned short;
        Word bufWord;
        for (int i = 0; i < buf.numWords_; i++) {
            bufWord = buf.words_[i];
            for (int j = 0; j < buf.WordBitSize_ - 1; j++) {
                if (bufWord & 1 == 1) {
                    id = i * buf.WordBitSize_ + j;
                    *(bufSet) |= *(f(array_[id]));
                }
                bufWord >>= 1;
            }
        }
        return bufSet;
    }

private:
    int countCapacity(const BitScale& arg) {
        using Word = unsigned short;
        int count = 0;
        Word buf;
        for (int i = 0; i < arg.numWords_; i++) {
            buf = arg.words_[i];
            for (int j = 0; j < arg.WordBitSize_ - 1; j++) {
                if (buf & 1 == 1)
                    count++;
                buf >>= 1;
            }
        }
        return count;
    }

    void addItems(const Set& set) {
        BitScale buf = set.bitScale_;
        buf -= bitScale_;
        int id;
        using Word = unsigned short;
        Word bufWord;
        for (int i = 0; i < buf.numWords_; i++) {
            bufWord = buf.words_[i];
            for (int j = 0; j < buf.WordBitSize_ - 1; j++) {
                if (bufWord & 1 == 1) {
                    id = i * buf.WordBitSize_ + j;
                    array_[id] = set.array_[id];
                }
                bufWord >>= 1;
            }
        }
    }
};

main.cpp с тестами.
#include <iostream>
#include <bitset>
#include "Set.h"
using namespace std;
typedef unsigned short Word;

struct B;

struct A {
    int id;
    B *b;
};

struct B {
    int id;
};

B* who(A *item) {
    return item->b;
}

int main()

{
    setlocale(LC_ALL, "");

    B b{ 1 };
    B bb{ 2 };
    A a{ 1, &b };
    A aa{ 2, &bb };
    Set<A> set1;
    cout << set1.capacity() << endl;
    set1 |= a;
    cout << set1.capacity() << endl;

    Set<A> set2;
    set2 |= aa;
    set1 |= set2;
    cout << set1.capacity() << endl;

    cout << "Has Item?" << endl;
    cout << set1.hasItem(a) << endl;
    cout << set1.hasItem(aa) << endl;

    cout << endl << "Current capacity:" << endl;
    cout << "set1: " << set1.capacity() << endl;
    cout << "set2: " << set2.capacity() << endl;

    cout << endl << "Which subset" << endl;
    cout << "set1 <= set2: " << (set1 <= set2) << endl;
    cout << "set2 <= set1: " << (set2 <= set1) << endl;
    cout << "set2 >= set1: " << (set2 >= set1) << endl;
    cout << "set1 >= set2: " << (set1 >= set2) << endl;
    cout << "set1 == set2: " << (set1 == set2) << endl;
    cout << "set1 != set2: " << (set1 != set2) << endl;

    cout << endl << "Copy constructor" << endl;
    Set<A> set3 = set1;
    cout << "Set<A> set3 = set1" << endl;
    cout << "set1 == set3: " << (set1 == set3) << endl;
    cout << "set1 != set3: " << (set1 != set3) << endl;

    cout << endl << "set3.capacity(): " << set3.capacity() << endl;
    set3 -= set2;
    cout << "set3 -= set2: " << endl;
    cout << "set3.hasItem(a): " << set3.hasItem(a) << endl;
    cout << "set3.hasItem(aa): " << set3.hasItem(aa) << endl;
    cout << "set3.capacity(): " << set3.capacity() << endl;
    cout << "set1.hasItem(a): " << set1.hasItem(a) << endl;
    cout << "set1.hasItem(aa): " << set1.hasItem(aa) << endl;
    cout << "set1.capacity(): " << set1.capacity() << endl;

    cout << endl << "Test map" << endl;
    Set<B> *set4 = set1.map(who);
    cout << "set4->capacity(): " << set4->capacity() << endl;
    cout << "set4->hasItem(b): " << set4->hasItem(b) << endl;
    cout << "set4->hasItem(bb): " << set4->hasItem(bb) << endl;

    cout << endl << "Copy operator=" << endl;
    set3 = set2;
    cout << "set3 = set2" << endl;
    cout << "set3 == set1: " << (set3 == set1) << endl;
    cout << "set3 == set2: " << (set3 == set2) << endl;

    cout << endl << "Difference sets" << endl;
    cout << "set1.capacity(): " << set1.capacity() << endl;
    set1 -= a;
    cout << "set1 -= a: " << endl;
    cout << "set1.hasItem(a): " << set1.hasItem(a) << endl;
    cout << "set1.hasItem(aa): " << set1.hasItem(aa) << endl;
    cout << "set1.capacity(): " << set1.capacity() << endl;
    set1 -= set2;
    cout << "set1 -= set2: " << endl;
    cout << "set1.hasItem(a): " << set1.hasItem(a) << endl;
    cout << "set1.hasItem(aa): " << set1.hasItem(aa) << endl;
    cout << "set1.capacity(): " << set1.capacity() << endl;

    //set4->print();
    //set1 -= set2;

    system("pause>nul");
    return 0;
}

BitScale.cpp - без изменений.


text: Q: how to create a query (with selection, insert, update and delete) with 3 tables or more? when I create a query with 2 tables, access allows me to do operations on this query (selection, insert, update and delete), but with 3 tables the query is only for selection. Is there a way to enable these features with 3 or more tables?


text:
Q: Validar token de Captcha tengo un problema con un sitio web, requiero validar el captcha del lado del servidor pero el desarrollador que implementó el captcha lo hizo hace tiempo y parece que no lo valida del lado del servidor y sale como vulnerabilidad en un test de seguridad.
El desarrollador backend me indica que se debe enviar el token del captcha para validar del lado del servidor pero el no logro enviarlo ni si quiera lo encuentro en el código.
Código de Validar captcha v2:

Código en php:

Me pueden ayudar para poder obtener el token y enviarlo al servidor para validar.


text:
Q: spring boot classnotfound org.springframework.boot.Bootstrapper while staring application I am just starting a spring boot project with eureka server as mentioned in https://dzone.com/articles/spring-boot-microservices-building-microservices-a , While running the project getting below exception and the application is stoped.
java.lang.ClassNotFoundException: org.springframework.boot.Bootstrapper

I am using Gradle with springboot 2.3.5.RELEASE version.
Does any one help me why i am seeing this error.

A: There is a conflict between SpringBoot starter web 2.3.5.RELEASE vs spring-cloud-starter-netflix-eureka-server:3.0.0
After changing SpringBoot starter web 2.4.2, all started working fine.

A: Create a new project with updated dependencies and copy this versions and add to your project


text:
Q: Edit/create nested resources in Formtastic (Rails) This question is regarding Rails 4/postgresql and the app is hosted on Heroku.
I am making a Quiz-functionality on a website and I am wondering on how to implement the forms (using Formtastic) best to make this is easy as possible. I have three models:

*

*Quiz (has_many :quiz_questions), e.g. "Test to see how awesome you are"

*QuizQuestion(belongs_to :quiz, has_many :quiz_options). e.g. "1. Which is your favorite color")

*QuizOption (belongs_to :quiz_question). e.g. "Blue"

I have set up the forms like this:
<%= semantic_form_for([:admin, @quiz], :url => admin_quiz_path(@quiz.id)) do |f| %>
  <%= render 'form' , :f => f %>
<% end %>

where the form looks like this:
<%= f.inputs %>

Quiz questions

<%= f.semantic_fields_for :quiz_questions do |qq_f| %>
    <%= qq_f.inputs %>

Quiz options

    <%= qq_f.semantic_fields_for :quiz_options do |qqo_f| %>
        <%= qqo_f.inputs %>
    <% end %>

<% end %>

<%= f.actions do %>
  <%= f.action :submit %>
  or go <%= link_to 'back', admin_quizzes_path %>
<% end %>

It seems, however, not to be working the way I want. I expect to be able to see the fields of QuizQuestion and QuizOptions in this form (there are objects for those) but I don't.
More importantly is that I would like to be able to create a New QuizQuestion and subsequently QuizOption in this form. It doesn't necessarily have to be jQuery/ajax or anything but I would like to do it all from this form.
Basically, I would like my workflow to be like:

*

*Create a Quiz and add values to it. Click Create.

*Add QuizQuestion number one and add the values to it (like "name label"). Click Create.

*Add QuizOption related to QuizQuestion number one, and its "name label". Click create.

*Repeat for QuizQuestion/QuizOption until the Quiz is done.

How can I do this?

A: For your workflow you might have to add accept_nested_attributes_for for the nested resources, this way when creating an object object you can actually create nested children (as long as they fulfill all the validations). This way:
# A quiz :has_many :quiz_questions
@quiz = Quiz.create(...)

with a declaration like:
has_many :quiz_questions
accepts_nested_attributes_for :quiz_questions

in your Quiz model you'll actually be able to create QuizQuestion from the quiz model like:
# using the previously quiz model
quiz.quiz_questions.create(...)

Doing the same for the deeply nested associations will do have the same effect.

Perhaps the reason why you don't see any field on the form is because there is not nested object created. Let me explain. When you create a new Quiz object, in your quizs_controller (or whatever the inflection for quiz is...) you need a:
def new
  quiz = Quiz.new()
end

and
def create
  Quiz.new(quiz_params)
end

private

def quiz_params
  # whitelisted parameters sent along with the form
  params.require(:quiz).permit(...)
end

if you actually want to be able to see the fields in the form you'll have to use the build method and actually populate that new object with respective the nested resources.
Note that for this to work with the form you will have to whitelist in the quizzes_controller the right attributes. You can debug the params you receive once you send the new quiz formulary and check that everything is right.
TIP! if you don't want to worry about the JS when adding nested resources dynamically, I recommend you using the cocoon gem


text:
Q: Any Possible way to add more than one favicon in a website how to add more than a singe favicon for different browser?
Reason:

[Google Chrome] favicon matches perfectly at horizontal axis with page title to make "AT Drive" a complete sentence!

[Mozilla Firefox] Now here you can see the "Same favicon" miss matched the horizontal axis, it shifted little downwards
 What i want:
To insert Multi-Favicon icons in a website with respect to browsers..

A: I can`t think of any pure html/css solution but You can change favicon for specify browser via JavaScript.
For example detect if browser is firefox (Detect all Firefox versions in JS) and then set diferent favicon for it (Changing website favicon dynamically) so final code should look something like this
<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

 <script type="text/javascript">

    if (/firefox/i.test(navigator.userAgent)) {
        document.getElementById("favicon").href = "favicon-firefox.png";
    }

</script>


text:
Q: How to disable generic @page rule in VF page rendered as PDF? I have following two requirements:
(1) Several single Visualforce pages rendered as PDF with a running header/footer as well as each VF page having a different "padding-top" value of it's content, i.e. spacing between header and content area, please see code for testPage1 and testPage2 below
(2) One single VF page rendered as PDF which includes all the single VF pages described in (1), please see code for testDoc below
Issue:
As the single VF pages each have different spacing between header and content, I assume having to use named @page rules. The header, footer and content get displayed as intended following this approach, however a single blank page before the actual header, footer and content is inserted. I assume it is because the generic @page rule gets applied (blank first page) as I am using only the named @page class for  tags in each single page. When applying body { page: page1; } the blank page is not shown in the single page but in the encompassing page.
Question:
I have scanned several documentation on W3 paged media, however can not find an attribute or tag to be set in order to hide the single first page. Would there be a solution or alternative approach?

<apex:page renderAs="advanced_pdf" showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">

    Header ("testPage1")

    Footer ("testPage1")

    Content ("testPage1")        *
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*

</apex:page>

<apex:page renderAs="advanced_pdf" showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">

     Header ("testPage2")

     Footer ("testPage2")

     Content ("testPage2")

</apex:page>

<apex:page renderAs="pdf" showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">

    <apex:include pageName="testPage1" />
    <apex:include pageName="testPage2" />

</apex:page>```