text:
Q: Is it possible to add new packages and run docker non-dev file? I have been working on Superset (cloned the code from superset github).Created new file under the folder superset/superset/ named db_access.py.
I have imported this file in the existing app.py file .Now have the following imports in the newly created file,
db_access.py
import boto3
import sys
import hvac
import pymysql
import psycopg2
import os
import io
import logging
from datetime import datetime, timedelta
import traceback
from timestream_reader import Timestream_reader
import json
from pathlib import Path
from zenpy import Zenpy

app.py
import logging
import os
import json
from flask import Flask
from flask import request,jsonify
from superset.initialization import SupersetAppInitializer
import sys
from superset.db_access import Db_access

I have included the hvac in requirements.txt and when I am composing docker dev file, it works with out any issue.
But when I try to compose the non-dev docker file with the above code, it shows error like hvac module not found (I tried pip install hvac and included that in requirements file too).Is there any other places that I need to customize based on new imports for non-dev?
docker-compose-non-dev.yml
x-superset-image: &superset-image apache/superset:${TAG:-latest-dev}
x-superset-depends-on: &superset-depends-on
  - db
  - redis
x-superset-volumes: &superset-volumes
  # /app/pythonpath_docker will be appended to the PYTHONPATH in the final container
  - ./docker:/app/docker
  - superset_home:/app/superset_home
  - ./superset:/app/superset
  - ./superset-frontend:/app/superset-frontend

version: "3.7"
services:
  redis:
    image: redis:latest
    container_name: superset_cache
    restart: unless-stopped
    volumes:
      - redis:/data

  db:
    env_file: docker/.env-non-dev
    image: postgres:10
    container_name: superset_db
    restart: unless-stopped
    volumes:
      - db_home:/var/lib/postgresql/data

  superset:
    env_file: docker/.env-non-dev
    image: *superset-image
    container_name: superset_app
    command: ["/app/docker/docker-bootstrap.sh", "app-gunicorn"]
    user: "root"
    restart: unless-stopped
    ports:
      - 8088:8088
    depends_on: *superset-depends-on
    volumes: *superset-volumes

  superset-init:
    image: *superset-image
    container_name: superset_init
    command: ["/app/docker/docker-init.sh"]
    env_file: docker/.env-non-dev
    depends_on: *superset-depends-on
    user: "root"
    volumes: *superset-volumes
    healthcheck:
      disable: true

  superset-worker:
    image: *superset-image
    container_name: superset_worker
    command: ["/app/docker/docker-bootstrap.sh", "worker"]
    env_file: docker/.env-non-dev
    restart: unless-stopped
    depends_on: *superset-depends-on
    user: "root"
    volumes: *superset-volumes
    healthcheck:
      test: ["CMD-SHELL", "celery inspect ping -A superset.tasks.celery_app:app -d celery@$$HOSTNAME"]

  superset-worker-beat:
    image: *superset-image
    container_name: superset_worker_beat
    command: ["/app/docker/docker-bootstrap.sh", "beat"]
    env_file: docker/.env-non-dev
    restart: unless-stopped
    depends_on: *superset-depends-on
    user: "root"
    volumes: *superset-volumes
    healthcheck:
      disable: true

volumes:
  superset_home:
    external: false
  db_home:
    external: false
  redis:
    external: false

docker-compose.yml (dev)
x-superset-image: &superset-image apache/superset:${TAG:-latest-dev}
x-superset-user: &superset-user root
x-superset-depends-on: &superset-depends-on
  - db
  - redis
x-superset-volumes: &superset-volumes
  # /app/pythonpath_docker will be appended to the PYTHONPATH in the final container
  - ./docker:/app/docker
  - ./superset:/app/superset
  - ./superset-frontend:/app/superset-frontend
  - superset_home:/app/superset_home
  - ./tests:/app/tests

version: "3.7"
services:
  redis:
    image: redis:latest
    container_name: superset_cache
    restart: unless-stopped
    ports:
      - "127.0.0.1:6379:6379"
    volumes:
      - redis:/data

  db:
    env_file: docker/.env
    image: postgres:14
    container_name: superset_db
    restart: unless-stopped
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - db_home:/var/lib/postgresql/data

  superset:
    env_file: docker/.env
    image: *superset-image
    container_name: superset_app
    command: ["/app/docker/docker-bootstrap.sh", "app"]
    restart: unless-stopped
    ports:
      - 8088:8088
    user: *superset-user
    depends_on: *superset-depends-on
    volumes: *superset-volumes
    environment:
      CYPRESS_CONFIG: "${CYPRESS_CONFIG}"

  superset-websocket:
    container_name: superset_websocket
    build: ./superset-websocket
    image: superset-websocket
    ports:
      - 8080:8080
    depends_on:
      - redis
    # Mount everything in superset-websocket into container and
    # then exclude node_modules and dist with bogus volume mount.
    # This is necessary because host and container need to have
    # their own, separate versions of these files. .dockerignore
    # does not seem to work when starting the service through
    # docker-compose.
    #
    # For example, node_modules may contain libs with native bindings.
    # Those bindings need to be compiled for each OS and the container
    # OS is not necessarily the same as host OS.
    volumes:
      - ./superset-websocket:/home/superset-websocket
      - /home/superset-websocket/node_modules
      - /home/superset-websocket/dist
    environment:
      - PORT=8080
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - REDIS_SSL=false

  superset-init:
    image: *superset-image
    container_name: superset_init
    command: ["/app/docker/docker-init.sh"]
    env_file: docker/.env
    depends_on: *superset-depends-on
    user: *superset-user
    volumes: *superset-volumes
    environment:
      CYPRESS_CONFIG: "${CYPRESS_CONFIG}"
    healthcheck:
      disable: true

  superset-node:
    image: node:16
    container_name: superset_node
    command: ["/app/docker/docker-frontend.sh"]
    env_file: docker/.env
    depends_on: *superset-depends-on
    volumes: *superset-volumes

  superset-worker:
    image: *superset-image
    container_name: superset_worker
    command: ["/app/docker/docker-bootstrap.sh", "worker"]
    env_file: docker/.env
    restart: unless-stopped
    depends_on: *superset-depends-on
    user: *superset-user
    volumes: *superset-volumes
    healthcheck:
      test: ["CMD-SHELL", "celery inspect ping -A superset.tasks.celery_app:app -d celery@$$HOSTNAME"]
    # Bump memory limit if processing selenium / thumbnails on superset-worker
    # mem_limit: 2038m
    # mem_reservation: 128M

  superset-worker-beat:
    image: *superset-image
    container_name: superset_worker_beat
    command: ["/app/docker/docker-bootstrap.sh", "beat"]
    env_file: docker/.env
    restart: unless-stopped
    depends_on: *superset-depends-on
    user: *superset-user
    volumes: *superset-volumes
    healthcheck:
      disable: true

  superset-tests-worker:
    image: *superset-image
    container_name: superset_tests_worker
    command: ["/app/docker/docker-bootstrap.sh", "worker"]
    env_file: docker/.env
    environment:
      DATABASE_HOST: localhost
      DATABASE_DB: test
      REDIS_CELERY_DB: 2
      REDIS_RESULTS_DB: 3
      REDIS_HOST: localhost
    network_mode: host
    depends_on: *superset-depends-on
    user: *superset-user
    volumes: *superset-volumes
    healthcheck:
      test: ["CMD-SHELL", "celery inspect ping -A superset.tasks.celery_app:app -d celery@$$HOSTNAME"]

volumes:
  superset_home:
    external: false
  db_home:
    external: false
  redis:
    external: false


text:
Q: Timing the runtime of a program via the Terminal I've written a C++ program of which i would like to time the length of time it takes to complete - is there some terminal command i could use?

A: You can use the "time" command available in most (maybe all) the linux distributions. It will print the time spent as system, as user, and the total time.
For example

bash-4.1$ time (sleep 1; sleep 1)

will output something like

real    0m2.020s
user    0m0.014s
sys 0m0.005s

As you can see with the parenthesis you can launch every command chain you wish.

A: It's called time in *nix

A: Iterate over the function several times (1000's probably) so you can get a large enough number.  Then use time.h to create two variables of type time_t - one before execution, one after.  Subtract the two and divide by the iterations.

A: Or Measure-Command in PowerShell.

A: I try to better explain :)
If you have compiled your code using g++, for example:
g++ -std=c++14 c++/dijkstra_shortest_reach_2.cpp -o dsq

In order to run it, you type:
./dsq

In order to run it with a file content as an input, you type:
./dsq < input07Dijkstra.txt

Now for the answer.
In order to get the duration of the program output to the screen, just type:
time(./dsq < input07Dijkstra.txt)

Or without an input:
time(./dsq)

For the first command my output is:
real    0m16.082s
user    0m15.968s
sys     0m0.089s

Hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What might be causing momentary system freezes? I just built a new PC with pretty solid specs, at least, more robust than most I've built in the past.
It's got a six-core AMD processor, 600watt power supply, 8GB RAM, etc.
I loaded up a fresh copy of the latest Ubuntu 11.10 and prepared to be blown away.
However, while it runs fine, I'm seeing frequent lag, where the mouse stops dragging momentarily, tabs freeze in the browser under both Firefox and Chromium (with only 4-5 tabs too, not a huge number of tabs), etc. The system monitor looks great, everything is almost at the baseline-- it's not like I'm loading the CPU or using tons of RAM.
Is there any common thing I'm overlooking that would affect this?
Specs, for those who want to know:
Motherboard: Gigabyte GA970A-UD3
Processor: (FX-6100)
RAM: Corsair 2x4GB DDRIII
Graphics: NVidia N550GTX-Ti (1GB RAM)

A: Hard to know, I have seen this sort of problem with video drivers and less often even wireless drivers.
Which driver are you using for your nvidia card ?
See also : https://wiki.ubuntu.com/X/Debugging

A: Well, I had issues with the performance on my machine too and it turned out to be the twitter service each time it refreshed. Check disabling: gwibber-service
and you can check also this answer.


text:
Q: Jquery UI Slider, Slider Handle image problems I have the following problem:
I've taken the example for the slider from the Jquery UI website (from here: http://jqueryui.com/demos/slider/side-scroll.html), and need to modify it so that the slider's handle shows a different graphic, but I can't get things to show up properly.
It should be as simple as pointing the background: property in ".scroll-bar-wrap .ui-slider-handle" to my image, or at least I thought so.  The functionality is working properly, and clicking in the general area of the scroll bar and moving left and right will make things scroll just fine.  The problem is that no matter what I try I can't get any sort of image (or CSS properties, for that matter) to show up with regards to the scroll bar and its handle!
Here is a directory with the mock-up I've been working with: Edit: Well that's embarrasing, I posted a bad page.  More below.
I've searched through Stack Overflow's jquery UI threads, and googled in general, but I can't seem to hit upon a solution.  At this point I'm thinking that it's some simple CSS thing that's messing with me and making the handle invisible, but leaving the functionality intact.  Please, what am I doing wrong?
Edit:
Ok, I apologize for posting a link to a page that wasn't showing the proper mockup.  Sorry for wasting anyones time.

A: Try overriding this class's in your css file.. Check if this works
.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default {
background:green url(slider.png) 50% 50% repeat-x !important;
}


text:
Q: paper-dialog not opening on click of an button Higuys,
as per the polymer documentation on paper dialog i did this
<paper-card elevation=3 align="center" id="question-ask-card">

          Got a question ?

    <paper-button data-dialog="Qdialog" id="askit" raised >
Write on Blackboard
</paper-button>

</paper-card>

and the dialog is
  <paper-dialog id="Qdialog">

sdjafadsfasdfjhg

      aouaouwghsefjgzskdcghizbskk

 </paper-dialog>

So how to link that dialog on click of that button,please help me!!!!!!!!
Thanks in advance.

A: Assuming your code is just sitting in the main document, this can be as easy as adding onclick="Qdialog.open()" to your button.

<!doctype html>

  <meta name="description" content="Polymer Example">
  <meta charset="utf-8">
  <base href="http://polygit.org/components/">

  <link href="paper-elements/paper-elements.html" rel="import">

  <paper-card elevation=3 align="center" id="question-ask-card">

Got a question ?

    <paper-button data-dialog="Qdialog" id="askit" raised onclick="Qdialog.open()">
Write on Blackboard
</paper-button>
  </paper-card>
  <paper-dialog id="Qdialog">

sdjafadsfasdfjhg

      aouaouwghsefjgzskdcghizbskk

  </paper-dialog>


text:
Q: IsolatedStorageSettings and NavigationService Error So I took a break and went from C# to VB in developing Windows Phone 8 apps. It's just more of a test and I have this really strange problem.
First off all my basic scenario is that I have Page A and Page B. The user has to fill in a few details before going to Page B. Page B will only be shown if the user has already filled out the information in Page A, sort of like a first time run.
What I've done is that I've added this code:
Private Sub createbtn_Click(sender As Object, e As RoutedEventArgs) Handles createbtn.Click
    '...
    IsoSettings.Add("AccountCreated", Nothing)
    NavigationService.Navigate(New Uri("/MainMenu.xaml", UriKind.Relative))
    NavigationService.RemoveBackEntry()
End Sub

Once the user clicks on the "create account" button. He will be navigated to Page B and hereafter the user will not have to go through filling out the information in Page A. The "AccountCreated" is a sort of Check. In here:
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
    If IsoSettings.Contains("AccountCreated") Then
        NavigationService.Navigate(New Uri("/MainMenu.xaml", UriKind.Relative)) 'Page B
        NavigationService.RemoveBackEntry()
    Else
        NavigationService.Navigate(New Uri("/MainPage.xaml", UriKind.Relative)) 'Page A
    End If
End Sub

So basically that checks and sees if IsoSettings contains "AccountCreated" then take the user to Page B, if not take him to Page A. Now this way works fine. No problems. Works the way I want it to.
Now I've added a settings page. There is one setting where the user can decide whether to show the Login page or not. If it's "off" then obviously it's not going to be shown and On...
I've added this:
If IsoSettings.Contains("AccountCreated") Then
        Try
            Dim ShowLoginPage As Byte = CByte(AppSettings("StartupLogin"))
            If ShowLoginPage = 0 Then
                NavigationService.Navigate(New Uri("/LoginPage.xaml", UriKind.Relative))
                NavigationService.RemoveBackEntry()
            ElseIf ShowLoginPage = 1 Then
                NavigationService.Navigate(New Uri("/MainMenu.xaml", UriKind.Relative))
                NavigationService.RemoveBackEntry()
            End If
        Catch ex As KeyNotFoundException
            AppSettings.Add("StartupLogin", 0)
        End Try
    Else
        NavigationService.Navigate(New Uri("/MainPage.xaml", UriKind.Relative))
End If

Now this is where the problem occurs. So when the user first runs this app. He has to go through Page A. He fills the information and then get's navigated to the Login page. Now once the user logs in or just closes the app while in the login page and re-opens it, the users gets navigated to Page A, to fix this the user has to close the app and re-open it.
Can someone please clear things for me?
Thanks!

A: I'm not sure if I had understood correctly and what is in the rest of the code, but from provided one it turns out for me that:

*

*the first time your App runs. the line Dim ShowLoginPage As Byte = CByte(AppSettings("StartupLogin")) throws the exceptions - there is no StartupLigin in AppSettings, so it is adding it but Navigation follows as exception is handeled.

*for the second time StartupLigin exists so it goes thru the if statements

I think it will be suitable if you had checked for the first run in Application_Launching() in App.xaml.cs.
I also don't see where you save your AppSettings - if you want your data to be preserved you should do it.


text:
Q: Facebook Tokens - I created a never-expiring token, but how? I have been trying to create a never-expiring Facebook Token (ideally programatically) and have not been able to do so, then, without really trying, on a different Facebook Application, I managed to create a token which, according to
https://developers.facebook.com/tools/debug/accesstoken?version=v2.5&q={TOKEN}
will never expire and I can't replicate it on any other Facebook Apps or for any other Facebook Tokens.
I can programatically (PHP) take the short lived token (1/2 hours) and extend it to 60 days, but I wanted to ideally get a never-expire token.
I guess I'm not asking how I managed to do it, but I can't find any explanation or documentation nor reason as to why I was able to achieve this for one token, but not any others.
Is it something in the App itself while it was created? Is there actually a way to get a never-expiring token, even though I've followed many of the guides online yet can only get a 1/2 hour token converted to 60 days?

A:
Is there actually a way to get a never-expiring token

No, not really. Even what you think is a never-expiring token can expire - f.e. if the user who created it changes their account password.

I guess I'm not asking how I managed to do it, but I can't find any explanation or documentation nor reason as to why I was able to achieve this for one token, but not any others.

It is not documented, because Facebook wants you to use the 60 day tokens, when you app is acting on behalf of a personal user profile. They removed offline_access permission ages ago, specifically so that apps the user has long forgotten about can't act on their behalf or still access their data any more.
So if you are writing an app that acts on behalf of users, you should really rather make do with the 60 day token - that should be enough for most cases.

Now what you are seeing with your token here, is a side effect of how Facebook has implemented extended page access tokens. Those do not have a default expiry - but they need to be invalidated when the user is removed as a page admin. Therefor, they are internally tied to the user token that was used to request the page token. User token gets invalidated - page access token becomes invalid together with it. And that in turn requires that the user token does not automatically expire after 60 days.
So, when you extend a user token that includes manage_pages permission, you will get an extended token with "unlimited" validity. But, again, that is a side effect of current implementation only, and can change in the future.


text:
Q: automatically activates a profile when another is actived I know it's impossible to "chain" profile declaration.
It's possible to do what I want (but not completely) with System properties in command line like mvn -Dvar=value .
And then use this:
  <activation>
    <property>
      <name>var</name>
      <value>value</value>
    </property>
  </activation>

or to activate simultaneously several profiles with -P profile1, profile2
In fact I have 4 profiles and I want to create a fifth profile with all the aspectj part (plugins, dependencies, ...) which should be activated only if profile 1, 2 or 3 is activated. Like that I don't have redundant plugins and dependencies declarations.
<profile>
  <id>profile1</id>
  <activation>
    <activeByDefault>true</activeByDefault>
  </activation>
  <build>
    ...
  </build>
</profile>

<profile>
  <id>profile2</id>
  <build>
    ...
  </build>
</profile>

<profile>
  <id>profile3</id>
  <build>
    ...
  </build>
</profile>
<profile>
  <id>profile4</id>
  <build>
    <plugins>
      <plugin>
        ...
      </plugin>
    </plugins>
  </build>
</profile>

<profile>
  <id>aop</id>
  <build>
    <plugins>
      <plugin>
        ...
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      ...
    </dependency>
    <dependency>
      ...
    </dependency>
  </dependencies>
</profile>

The problem is that profile 1 is the default profile and even it should be possible to do it without command line args. I tried with defining a value but it doesn't work because activation property only works with system properties.
Am I wrong? Is there another way to do it?
Thanks

A: Maven won't help you there, you can have no dependencies or inheritance between profiles, see also my recent answer to a related question.
You can explicitly turn profiles on or off, but there is no way to define any relation between them. Maven is not ant, which is usually a good thing, but this is one of the cases where I think it should be more like ant.
From Introduction to Build Profiles:

A profile can be triggered/activated
  in several ways:

*

*Explicitly

*Through Maven settings

*Based on environment variables

*OS settings

*Present or missing files

None of these is helpful to define any relation between the profiles (Project properties can't be used because Profiles are evaluated while the Project is built). So your only options are to

*

*live with the restrictions and explicitly activate the profiles you need using the -P syntax

*write a shell script that encapsulates the maven call and automatically adds missing profiles

*Build your own replacement for DefaultProfileSelector, as outlined in my previous answer


text:
Q: Async method to return true or false on React component I'm working on a React component that handles a form submit.
<form
    name="theForm"
    ref={(el) => { this.theForm = el }}
    onSubmit={this.handleSubmit}
    noValidate
>

On the submit event handler I perform validation, using HTML5 form checkvalidity() calling another function, validateForm();
handleSubmit(e) {
    e.preventDefault();
    if (this.validateForm()) {
        //Call the api to post data
    }
}

If the validity on validateForm is false, I populate a list on state called dirtyFormInputs that is passed to the form's child components.
Due to setState async behaviour, I changed my code to handle the updates to dirtyFormInputs list with async/await as follows:
async validateForm() {
    const formLength = this.theForm.length;

    if (this.theForm.checkValidity() === false) {
        this.setState({ dirtyFormInputs: [] });
        for(let input of this.theForm){
            input.nodeName.toLowerCase() !== 'button'
                && await this.validateInput(input);
        }
        return false;
    }
    return true;
}

But since I changed the validateInput method to properly update dirtyFormInputs, the return false statement on validateForm() is not effective anymore and my form is submitted even when failing on valitidy check.
validateInput(input) {
    if (!input.validity.valid) {
        return new Promise((resolve) => {
            this.setState({
                dirtyFormInputs: [...this.state.dirtyFormInputs, input.name]
            }, resolve)
        });
    }
}

A: validateForm returns a promise since it's declared async.
You need to wait for the promise to resolve:
handleSubmit(e) {
  e.preventDefault();
  this.validateForm().then(result => { // or use `async` + `await`
    if (!result) return;
    //Call the api to post data
  });
}

A: Async effect infects everything it touches. So you need to handle async nature of your validation inside handleSubmit
async handleSubmit(e) {
    e.preventDefault();
    if (await this.validateForm()) {
        //Call the api to post data
    }
}


text:
Q: Opening a specific PDF sharepoint-document in Chrome Edge is not good in handling PDF's. I have a PDF where I link in that document between the different pages (from 1 to 3 to 2 to 1 to 4, etc.). Edge can not do this, Chrome can.
I want this one specific document to open with Chrome, NOT default opening all PDF's in Chrome. Is there any way to achieve this? I prefere to open that link from either sharepoint or a sharepoint-page (within a textblok?) but opening it from wihtin an Office-document (perferably Word) is also fine with me.
Thank you

A: Sasa, this isn't SharePoint question. This is more of a HTML question. "Edge is not good in handling PDF's." isn't true. It just handles them differently. The new chromium Edge works just like Chrome.
If you are trying to control an application launch via a link you use a specific URL schema in the href. But again, this is dependent on the user's system, and it isn't guaranteed to work. i.e. you may have to create a link for iOS devices that is different for andriod devices that is different for Windows Devices. etc
Here is information on using the  tag and you need to specific a customer URL Scheme in the href property.
https://www.w3schools.com/tags/att_a_href.asp
https://www.freecodecamp.org/news/the-a-href-attribute-explained/
Here is one example on how to do this for iOS devices:
https://apple.stackexchange.com/questions/142834/creating-a-url-that-always-opens-in-chrome


text:
Q: Symfony2 Form handler check changes before persist I'd like to check changes of my hydrated entity before the persist.
I've tryed to get a new entity into the onSuccess (after bindRequest) with DB values using a find, but this object have the hydrated values instead of DB values !
This is what i've tryed :
public function onSuccess(TachesDetails $detail) {
    $tache_new = $detail->getTache();
    $tache_old = $this->em->getRepository('NomDuBundle:Taches')->find($tache_new->getId());
    var_dump($tache_old);
    // ...
    $this->em->persist($detail);
    $this->em->persist($detail->getTache());
    $this->em->flush();
}

Var_dump of $tache_old give me hydrated values.
EDIT :
I've find the solution after hours.
To resolve this problem, you'll have to create a clone of your entity in the controller and send it trough formHandler parameters.
In the onSuccess function, you can access it like this :
$this->entityCloned

A: First of all, you could use prePersist event for checking what changed. It's more suitable than onSuccess.
There's also more native way to check changes, using UnitOfWork object:
$unitOfWork = $entityManager->getUnitOfWork();
$unitOfWork->computeChangeSets();
$changes = $unitOfWork->getEntityChangeSet($yourEntity);


text:
Q: Simple Square Wave Amplification Technique? I have a square wave that is 5v peak-to-peak. I need a circuit that can amplify this square wave up to any given supply voltage between 9 and 50v. I don't need much current, nothing more than 100ma certainly, 20-50ma would work. My preference is to use components as cheap as I can get. How can I amplify this square wave for minimal component cost? Is there a way to achieve a square wave with a high peak-to peak voltage without in input pwm?
Edit:
The 0-Vsupply square wave will be fed into the following circuit:

simulate this circuit – Schematic created using CircuitLab
Vout will always float 10v above the supply, minus a few diode drops. The part I am stuck on is how to get a square wave at the supply voltage.

A: If you don't mind burning up power, but want simple.  You need to size your resistors to match whatever you choose for C1 (so if C1 = 1uF, choose R = 100 ohms, which means that Q1 needs to be a power transistor, not a cheezy little 3904).

simulate this circuit – Schematic created using CircuitLab
If you want to be more efficient, but can stand more drop (the output will pull down to about 0.9V, and up to 50V - 0.7V).

simulate this circuit

A: I found a simple circuit that works for me. Just tested on my oscilloscope. I had originally overlooked this one because power dissipation goes up with supply voltage, but in my application a very small on-time duty cycle will suffice. This will decrease the average power dissipation through the collector resistor to within an acceptable range.

Schematic by Herbert Weidner


text:
Q: async await returning Task> instead of List on calling aync method I am trying to understand the usage of async await and i studied few blog posts and now i have made a testing code but it is not working the way i am expecting it to work.
I have a method which returns List:
private List<Employee> GetEmployees()
{

 IList<Employee> list = new List<Employee>();
 list.Add(new Employee() { Id = 1, Age = 20, Name = "Kavin" });
 list.Add(new Employee() { Id = 2, Age = 30, Name = "Alen" });
 list.Add(new Employee() { Id = 3, Age = 20, Name = "Suresh" });
 list.Add(new Employee() { Id = 4, Age = 30, Name = "Jay" });
 list.Add(new Employee() { Id = 5, Age = 20, Name = "Nanda" });
 list.Add(new Employee() { Id = 5, Age = 20, Name = "Kavin" });
 list.Add(new Employee() { Id = 5, Age = 20, Name = "Kavin" });
 list.Add(new Employee() { Id = 1, Age = 23, Name = "Test" });

 return list;
}

Then i wrote my async method:
private async Task<List<Employee>> TestEmployeesGetAsync()
{

  var result = await Task.Run(() => GetEmployees());

  return result;
}

When i call this method :
var Result = TestEmployeesGetAsync();

The visual studio is telling me that it returns Task<List<T>> and it usage is:
List<Employee> result = await TestEmployeesGetAsync();

Why i need to put await on the calling method if i put await it gives compiler error of course because await should have async as well. Can somebody clear my mind how to call it so that i can get List<T> instead of Task<List<T>>

A:
Why i need to put await on the calling method if i put await it gives
  compiler error of course because await should have async as well.

There are a few dependencies the compiler needs in order to understand you're running an async method. The signal is the async modifier on the method declaration. Once you mark it as async, you can use the await keyword. That is why async propagates "all the way" down the call stack, as when you call one async method and need to await its result, you'll need to mark the consuming method with the async modifier.
In order to make your method work, you'll need to do the following:
public async Task GetEmployeesAsync()
{
   List<Employees> result = await TestEmployeesGetAsync();
}

As a side note, be aware that you should not expose async wrappers over sync methods.

A: You essentially need to wait for the result of the task returned by TestEmployeesGetAsync. You can do that asyncrhonously with await which unwraps the result for you to List<Employee> or you can get the result from the task with the Result property. However that can cause a deadlock so you need to be careful.
With async-await it tends to make its way up the call chain, i.e. awaiting an async method requires you to do that in another async method ( as you have found out), and awaiting that method requires you to be in yet another async method, and so the async methods spread through the code base until you reach an event handler or Main (which cannot be marked async).
This proliferation of async methods is not unusual, and to avoid it, you can wait for the task to complete with Task.Wait and Task.Result but these are blocking method and can cause the aforementioned deadlock. It is also an anti-pattern called sync over async and it defeats the purpose of doing the work asynchronously as you'll end up blocking waiting for it to finish anyway.
As pointed out by @BenVoigt, one exception is when you kick off multiple asynchronous requests and then  block waiting for all the tasks to complete with Task.WaitAll.


text:
Q: this keyword differs in Runtime and compile time 1.Can Some one illustrate how it works? Why it prints 1 instead of 2?
2.From the Oracle Official Java tutorial, the definition of this: Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
    // Base Class
    class A {

        public int m = 1;

        public void view(){
            // Print variable m
            System.out.println(this.m);

            //print the current class name
            System.out.println(this.getClass());
        }

    }

    // Subclass extends Base Class
    public class B extends A{

        // Define another variable m
        public int m = 2;

        public static void main(String[] args) {
            B b = new B();
            b.view();
        }

    }

Below is the debug of the view(){}:

My Question is:
You can see the current object is B, when we usethis, it represents the B, m = 1 in base class A, m = 2 in derived class B, then use the this.m, it should print 2, isn't it?

A: Variables are not polymorphic in Java; they do not override one another.


text:
Q: how to set value float in C#? i want to set 20770897 to C# float type but this is changed to 20770896 ! why?
for example:
float test = 20770897;

value automatic changed to 20770896 ? help please.
i am getting id from web service . these is return a float value but it is not true value from web service method!

A: The precision of a float (System.Single) is only 7 significant digits

A: It's a rounding error, these are common in very large or very small values with 32-bit floating types. Use a more precise type like double if you need floating point support. If you to not explicitly need floating point support I recommend using an int, long, uint, or ulong to store the value (which appears to be an integer value).
http://en.wikipedia.org/wiki/Round-off_error

A: The issue is one of a rounding error - because of the precise way values are stored under the hood, noninteger types are incapable of string certain values, and will instead be slightly above or below the actual value. This can result in apparent errors when rounding versus truncating, and you should carefully determine which to use - presumably, you code is producing 20770896.99999... and truncating to 20770896 when you print it.
Note that errors become more frequent the higher your value gets. If you need more accuracy, consider turning up to double or even decimal types.


text:
Q: Attaching  in GROUP_CONCAT() I want to attach  string to GROUP_CONCAT function using CONCAT().
I tried the following :
$str1 = "";
$str2 = "";
$query = "select count(cbm.bug_id) as count,(select concat(round((count(cbm.bug_id)/(select count(*) from techzilla.category_bug_map cbm,techzilla.bugs b where b.assigned_to =$userId  and cbm.bug_id=b.bug_id) * 100 ),2),'%')) as Percentage ,GROUP_CONCAT(CONCAT('$str1', bug_id,'$str2') separator ',') as BugIds from techzilla.bugs b left join techzilla.category_bug_map cbm on cbm.bug_id = b.bug_id where b.assigned_to = $userId and b.creation_ts >= '$fromDate 00:00:00' and b.creation_ts <= '$toDate 00:00:00' and cbm.os IN ('$opess')";

But when i printed the query, i got the following error :
select count(cbm.bug_id) as count,(select concat(round((count(cbm.bug_id)/(select count(*) from techzilla.category_bug_map cbm,techzilla.bugs b where b.assigned_to =1078 and cbm.bug_id=b.bug_id) * 100 ),2),'%')) as Percentage ,GROUP_CONCAT(CONCAT('', bug_id,'') separator ',') as BugIds from techzilla.bugs b left join techzilla.category_bug_map cbm on cbm.bug_id = b.bug_id where b.assigned_to = 1078 and b.creation_ts >= '2013-05-01 00:00:00' and b.creation_ts <= '2013-06-06 00:00:00' and cbm.os IN ('Windows')
Bad query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'show_bug.cgi?id ='>', bug_id,'') separator ',') as BugIds from techzilla.bug' at line 1

can anyone please help in fixing this??

A: You are getting the error because of the quote in your $str1, i would suggest to escape them
$str1 = "";

This should prevent query to split string and > as your error is pointing

A: I took the part of the query where you are using $str1 and $str2 and tried in my local machine and instead of using variables i directly passed href in query like below
select GROUP_CONCAT(CONCAT(\"< a href=show_bug.cgi?id=>\",id,\"</a>\") separator ',') as BugIds
from table_name

It's working here. Hope it works for you.


text:
Q: C# Multi Level Generics with inheritance/polymorphism I've been stumped on this for a while now but wanted to know if it was possible via another approach or I'm just missing a step.
Here are the base classes.
public class StartType0<T1, T2>
    where T1 : StartType1
    where T2 : StartType2
{}

public class StartType1 {}

public class StartType2 {}

public class EndType0 : StartType0<EndType1, EndType2> {}

public class EndType1 : StartType1 {}

public class EndType2 : StartType2 {}

I want to create a holder/container class to hold an array of my EndType0 class which will be used in Unity to draw a generic custom property drawer for my StartType0 class.
Any suggestions or pointers in the right direction would be amazing as I've tried tackling this issue several times over the past few months.
I thought I could try providing every parameter but I can't convert the StartType0 to my EndType0.
public class TypeContainer<T0, T1, T2>
    where T0 : StartType0<T1, T2>
    where T1 : StartType1
    where T2 : StartType2
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<StartType0<EndType1, EndType2>, EndType1, EndType2> container = new TypeContainer<StartType0<EndType1, EndType2>, EndType1, EndType2>();

    public Tester()
    {
        EndType0 instance = (EndType0)container.array[0];
    }
}

I thought I could try providing EndType0 to the StartType0 parameter but I'm guessing it has issues due to not taking polymorphism into account.
public class TypeContainer<T0, T1, T2>
    where T0 : StartType0<T1, T2>
    where T1 : StartType1
    where T2 : StartType2
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<EndType0, EndType1, EndType2> container = new TypeContainer<EndType0, EndType1, EndType2>();

    public Tester()
    {
        EndType0 instance = container.array[0];
    }
}

I would ideally love to approach it something like this way with some yummy polymorphism involved.
public class TypeContainer<T>
    where T : StartType0<StartType1, StartType2>
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<EndType0> container = new TypeContainer<EndType0>();

    public Tester()
    {
        EndType0 instance = container.array[0];
    }
}

-EDIT 1-
After following @JohnathanBarclay's comment I manage to make the following.
public class StartType0<out T1, out T2>
    where T1 : StartType1, IStartType1
    where T2 : StartType2, IStartType2
{}

public interface IStartType1 {}

public class StartType1 : IStartType1 {}

public interface IStartType2 {}

public class StartType2 : IStartType2 {}

public class EndType0 : StartType0<EndType1, EndType2> {}

public class EndType1 : StartType1 {}

public class EndType2 : StartType2 {}

which then allows me to do the following and complete a compile.
public class TypeContainer<T0, T1, T2>
    where T0 : IStartType0<T1, T2>
    where T1 : IStartType1
    where T2 : IStartType2
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<EndType0, EndType1, EndType2> container = new TypeContainer<EndType0, EndType1, EndType2>();

    public Tester()
    {
        EndType0 instance = container.array[0];
    }
}

This has issues being drawn into the unity editor though.
-EDIT 2-
After some play around I found my current ideal setup so far
public interface IStartType0<out T1, out T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{}

public class StartType0<T1, T2>
    IStartType0<T1, T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{}

public interface IStartType1<out T> where T StartType1 {}

public class StartType1 : IStartType1<StartType1> {}

public interface IStartType2<out T> where T StartType2 {}

public class StartType2 : IStartType2<StartType2> {}

public class EndType0 : StartType0<EndType1, EndType2> {}

public class EndType1 : StartType1 {}

public class EndType2 : StartType2 {}

public class TypeContainer<T0, T1, T2>
    where T0 : IStartType0<T1, T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<EndType0, EndType1, EndType2> container = new TypeContainer<EndType0, EndType1, EndType2>();

    public Tester()
    {
        EndType0 instance = container.array[0];
    }
}

Having the 'more or less' guaranteed base types I am able to run my CustomPropertyDrawer over these and generate custom inspectors and even utilise 'Activator' for messing with the generic types.

A: After some play around with variance in generics I found my current ideal setup so far
public interface IStartType0<out T1, out T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{}

public class StartType0<T1, T2>
    IStartType0<T1, T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{}

public interface IStartType1<out T> where T StartType1 {}

public class StartType1 : IStartType1<StartType1> {}

public interface IStartType2<out T> where T StartType2 {}

public class StartType2 : IStartType2<StartType2> {}

public class EndType0 : StartType0<EndType1, EndType2> {}

public class EndType1 : StartType1 {}

public class EndType2 : StartType2 {}

public class TypeContainer<T0, T1, T2>
    where T0 : IStartType0<T1, T2>
    where T1 : IStartType1<StartType1>
    where T2 : IStartType2<StartType2>
{
    public T0[] array = new T0[1];

    public TypeContainer()
    {
        array[0] = Activator.CreateInstance(typeof(T0));
    }
}

public class Tester
{
    public TypeContainer<EndType0, EndType1, EndType2> container = new TypeContainer<EndType0, EndType1, EndType2>();

    public Tester()
    {
        EndType0 instance = container.array[0];
    }
}

Having the 'more or less' guaranteed base types I am able to run my CustomPropertyDrawer over these and generate custom inspectors and even utilise 'Activator' for messing with the generic types.


text:
Q: Rolling Up Multiple Rows Into Single Row With Same Number Of Columns and Different Values I have a ID column with different values in it for a particular attribute.
I wish to convert the 4 rows into 1 row. There are multiple records
UNIQID    | NAME | AGE | SOURCE
123       | John | 25  | StoreA
928       | John | 25  | StoreB
456       | John | 25  | StoreC
528       | John | 25  | StoreD

I need the output as below -
UNIQID_A    | UNIQID_B | UNIQID_C | UNIQID_D | NAME | AGE
123         | 928      | 456      | 528      | John | 25

I manged to reach the below result by using the sql query but I am not sure how to roll up these values into 1
SELECT  CASE WHEN Source = 'StoreA' THEN UNIQID END AS UNIQID_A,
        CASE WHEN Source = 'StoreB' THEN UNIQID END AS UNIQID_B,
        CASE WHEN Source = 'StoreC' THEN UNIQID END AS UNIQID_C,
        CASE WHEN Source = 'StoreD' THEN UNIQID END AS UNIQID_D ,
        ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY AGE) AS ROWNO,
        *
FROM Table

Output of the above query as
UNIQID_A     | UNIQID_B | UNIQID_C | UNIQID_D | NAME | AGE | ROWNO
123          | NULL     | NULL     | NULL     | John | 25  | 1
NULL         | 928      | NULL     | NULL     | John | 25  | 2
NULL         | NULL     | 456      | NULL     | John | 25  | 3
NULL         | NULL     | NULL     | 528      | John | 25  | 4

Appreciate your help.

A: You can use max on your conditional statements to aggregate into a single row, and group by the remaining columns
SELECT  Max(CASE WHEN Source = 'StoreA' THEN UNIQID END) AS UNIQID_A,
        Max(CASE WHEN Source = 'StoreB' THEN UNIQID END) AS UNIQID_B,
        Max(CASE WHEN Source = 'StoreC' THEN UNIQID END) AS UNIQID_C,
        Max(CASE WHEN Source = 'StoreD' THEN UNIQID END) AS UNIQID_D,
        NAME, AGE
FROM Table
Group By NAME, AGE

A: SELECT SUM(UNIQID_A) UNIQID_A, SUM(UNIQID_B) UNIQID_B, SUM(UNIQID_C) UNIQID_C, SUM(UNIQID_D) UNIQID_D, NAME, AGE FROM (
    SELECT CASE WHEN Source = 'StoreA' THEN UNIQID END AS UNIQID_A,
    CASE WHEN Source = 'StoreB' THEN UNIQID END AS UNIQID_B,
    CASE WHEN Source = 'StoreC' THEN UNIQID END AS UNIQID_C,
    CASE WHEN Source = 'StoreD' THEN UNIQID END AS UNIQID_D,
    NAME, AGE
    FROM Table) AS A
GROUP BY NAME, AGE


text:
Q: How to exclude values in excel I have a simple excel problem:
I have columns A, B, C, D how can I get all the values that are in column A that are not in column B +C +D together in excel?

A: Add a calculated column E that is set to 1 if A <> B and A <> C and A <> D, else is set to 0.
Using the Auto-Filter function on the Data Ribbon select only those rows that have a value of 1 in column E.


text:
Q: react horizontal scroll to section mouse wheel Есть небольшой проект на react:

Есть горизонтальное меню и контент.
По клику на пункт меню - скролл к соответствующей секции.
При скролле контента - переключается активный пункт меню.
Меню:

    {list.map((item, i) => (

        <a
          href={`#s-${i}`}
          className={`nav-link text-nowrap ${
            active === i ? "text-danger" : ""
          }`}
          onClick={scrollTo(i)}
        >
          {item}

    ))}

Контент:

    {list.map((item, i) => (
      <li id={`s-${i}`} ref={scrollRefs.current[i]} className="py-100 px-3">

{item}

          Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi,
          dicta.

    ))}

>>>:
  const scrollRefs = useRef([]);
  const scrollNavRefs = useRef();

  const [active, setActive] = useState(0);

  const list = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"];

  scrollRefs.current = [...Array(list.length).keys()].map(
    (_, i) => scrollRefs.current[i] ?? createRef()
  );

  const scrollTo = (index) => () => {
    scrollRefs.current[index].current.scrollIntoView({ behavior: "smooth" });
    setActive(index);
  };

  const scrollHandler = () => {
    const scrollRefsElements = scrollRefs.current;

    scrollRefsElements.forEach((el, i) => {
      const rect = el.current.getBoundingClientRect();

      const elemTop = rect.top;
      const elemBottom = rect.bottom;

      const isVisible = elemTop >= 0 && elemBottom <= window.innerHeight;

      if (isVisible) {
        setActive(i);
      }
    });
  };

  const onWheel = (e) => {
    if (e.deltaY === 0) return;
    e.preventDefault();

    const scrollNavRefsElement = scrollNavRefs.current;
    const scrollNavRefsElementLeft = scrollNavRefs.current.scrollLeft;

    scrollNavRefsElement.scrollTo({
      left: scrollNavRefsElementLeft + e.deltaY,
      behavior: "smooth"
    });
  };

  useEffect(() => {
    window.addEventListener("scroll", scrollHandler, true);
    return () => {
      window.removeEventListener("scroll", scrollHandler, true);
    };
  }, []);

  useEffect(() => {
    scrollNavRefs.current.addEventListener("wheel", onWheel, true);
    return () => {
      scrollNavRefs.current.removeEventListener("wheel", onWheel, true);
    };
  }, []);

Вопрос: Как связать меню и контент, так чтобы при скролле основного контента, когда меняется активный класс пункта меню - меню скроллилось, так чтобы активный пункт меню был видимым? И при скролле меню, чтобы переключался активный класс пункта меню и скроллился основной контент к соответствующей секции По аналогии с приемером?

A: Cразу скажу, что задача не тривиальная, хотя с виду кажется простой. Решать ее можно по разному. Я получил удовольствие решая эту задачу (больше бы таких), надеюсь Вы получите пользу от моего решения. Ниже я постарался как можно подробнее прокомментировать свой подход.
Я не очень люблю использовать useRef в своих проектах, конечно бывают случаи когда без него не обойтись. Дело в том, что не то чтобы я не умею им пользоваться просто иногда он пораждает глюки которые сложно понять. И в принципе, я сокращаю все что можно сократить, даже если это не глючит.
Так же я отказался от навешивания события scroll через useEffect. Оказалось что scroll нужно было навесить именно на контент а не все окно так как иначе при попытке прокрутки меню порождалось еще одно событие скрола, в итоге одно стопорило результат другого т.е. обрубался скрол контента.
Функцию onWheel я переделал просто на изменение индекса (active) и эмуляцию click - нажатия на ссылку.
Для скрола я решил использовать scrollLeft если посмотреть исходники вебкомпонента в приведенном Вами проекте со Vue там тоже его используют, однако кода там гораздо больше, поэтому я даже не стал его рассматривать как вариант ответа и решил все писать самостоятельно, Если будет интересно посмотрите в проекте node_modules/vant/lib/tabs/utils.js там тоже есть свои фишки.
current.scrollLeft += rect.left - (width - rect.width)/2
Эта формула позволяет прокрутить начало элемента влево, затем на середину страницы и после чуть левее чтобы центр элемента был по центру страницы:

Обратите внимание, что я использую += вместо обычного = так как тут нужно учитывать смещение, которое было уже сделано до этого.
Функция getElementIndex занимается тем, что берет родителя элемента и после по нему ищет индекс элемента. Таким образом через нее я поулчаю в функции scrollToIndex активный индекс и устанавливаю его.
Еще один момент не давал мне покоя - это цикл forEach для поиска индекса элемента в контенте. Поэтому я решил воспользоваться сразу фунцией которая по позиции в документе может найти элемент elementFromPoint(x,y), а далее я снова получал его индекс с помощью getElementIndex. Чтобы определится с позицией по которой стоит искать элемент я воспользовался известной Вам функцией getBoundingClientRect для меню после чего брал точку чуть ниже середины после меню.
Ну и на последок, я поиграл немного со стилями (.content и .smooth-scroll ), прежде всего приcпустил контент и добавил через стили плавный скрол для обоих частей.
PS: К сожалению выяснилось уже после того как я дал ответ, что стиль .smooth-scroll в Chrome ломает функционал, если это произойдет у Вас попробуйте заккоментировать этот стиль. Как вариант можно попробовать использовать анимацию css с переменными. Я еще посмотрю как это можно будет решить.

const {useRef, useState, useEffect} = React

function App() {
  const scrollNavRefs = useRef();
  const [active, setActive] = useState(0);
  const list = new Array(20).fill().map((e, i) => `Item ${i+1}`)

  const scrollNav = (i) => {
    if (!scrollNavRefs.current) return
    const { current } = scrollNavRefs
    const rect = current.children[i].getBoundingClientRect();
    const width = window.innerWidth;
    current.scrollLeft += rect.left - (width - rect.width)/2
  }

  const getElementIndex = (element) => {
    const parent = element.parentNode;
    return [...parent.children].indexOf(element);
  }

  const scrollToIndex = (event) => {
    const navLi = event.target.parentNode;
    const index = getElementIndex(navLi);
    setActive(index);
  };

  const scrollHandler = (event) => {
    if (!scrollNavRefs.current) return
    const rectNav = scrollNavRefs.current.getBoundingClientRect();
    const el = document.elementFromPoint(rectNav.width / 2, rectNav.height + 10)
    if(!el || el.tagName !== 'LI') return
    const newIndex = getElementIndex(el)
    const rect = el.getBoundingClientRect();
    setActive(newIndex);
    scrollNav(newIndex)
  };

  const onWheel = (e) => {
    if (e.deltaY === 0 || !scrollNavRefs.current ) return;
    const {length} = scrollNavRefs.current.children;
    const delta = e.deltaY < 1 ? -1 : 1;
    const lastIndex = active;
    const nextIndex = delta + lastIndex;
    const newIndex = nextIndex >= 0 && nextIndex < length
        ? nextIndex
        : lastIndex;
    const link =  scrollNavRefs.current.children[newIndex].children[0];
    link.click();
    setActive(newIndex);
    scrollNav(newIndex);
  };
  return (

        {list.map((item, i) => (

            <a
              onClick={scrollToIndex}
              href={`#s-${i}`}
              className={`nav-link text-nowrap ${
                active === i ? "text-danger" : ""
              }`}
            >
              {item}

        ))}

          {list.map((item, i) => (
            <li key={i} id={`s-${i}`}  className="py-100 px-3">

{item}

                Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi,
                dicta.

          ))}

  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
h1,
p {
  font-family: Lato;
}
/*
html {
  scroll-behavior: smooth;
}
*/
.nav {
  overflow: hidden;
  overflow-x: auto;
  z-index: 1000;
  background: #fff;
}

.py-100 {
  padding-top: 100px;
  padding-bottom: 100px;
  border: 1px solid;
}

.mb-100 {
  margin-bottom: 200px;
}

.smooth-scroll{
  scroll-behavior: smooth;
}

.content{
  height: calc(100vh - 55px);
  margin-top: 55px;
  overflow-y: scroll;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>

    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

A: Попробуй использовать отсчет от отступа скрола + высота элемента.

const scrollHandler = () => {
  const scrollRefsElements = scrollRefs.current;

  const elementsInViewport = scrollRefsElements
    .filter((el, i) => {
      const rect = el.current.getBoundingClientRect();

      const elemTop = rect.top;

      return (
        window.pageYOffset + rect.height >= el.current.offsetTop + elemTop
      );
    })
    .map((_, i) => i);

  setActive(elementsInVievport[elementsInVievport.length - 1]);
};


text:
Q: scrollview will not scroll when android:softinputmode="adjustpan" enabled The situation:
I have an activity which at the moment has 5 "screens" wrapped in a ViewFlipper; below the ViewFLipper I have a blue bar which acts as a navigation bar showing what screen you are on.
The Problem:
When the soft keyboard appears, that blue nav bar shows up above it. So, I added android:softinputmode="adjustpan" to keep the nav bar at the bottom and now I can not scroll the view and some of my inputs are being blocked... Any help would be greatly appreciated.
    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:orientation="horizontal"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_marginBottom="20dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ViewFlipper android:layout_width="fill_parent"
        android:id="@+id/CreateNewAccountViewFlipper"
        android:layout_height="fill_parent">

        <com.appname.UI.Shared.CreateNewAccount.NextBackScrollView
            android:layout_width="fill_parent"
            android:id="@+id/NextBackScrollView1"
            android:layout_height="fill_parent"
            android:fillViewport="true">

            <LinearLayout
                android:orientation="vertical"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">

                <TextView
                    android:padding="10dp"
                    android:text="@string/CreateNewAccountWelcomeMessage"
                    android:layout_width="fill_parent"
                    android:id="@+id/createNewAccountMessage"
                    android:layout_gravity="center"
                    android:layout_height="wrap_content"
                    android:layout_margin="20px"
                    android:gravity="center">
                </TextView>
            </LinearLayout>
        </com.appname.UI.Shared.CreateNewAccount.NextBackScrollView>

        <com.appname.UI.Shared.CreateNewAccount.NextBackScrollView
            android:layout_width="fill_parent"
            android:id="@+id/NextBackScrollView2"
            android:layout_height="fill_parent"
            android:fillViewport="true">

            <LinearLayout
                android:orientation="vertical"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">

                <TextView
                    android:padding="10dp"
                    android:gravity="center"
                    android:text="@string/CreateNewAccountEmailMessage"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:id="@+id/createNewAccountEmailMessage"
                    android:layout_height="wrap_content">
                </TextView>

                <EditText
                    android:inputType="textEmailAddress"
                    android:hint="Email Address"
                    android:id="@+id/newEmail"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </EditText>

                <EditText
                    android:inputType="textEmailAddress"
                    android:hint="Confirm Email Address"
                    android:id="@+id/newEmailConfirm"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </EditText>
            </LinearLayout>
        </com.appname.UI.Shared.CreateNewAccount.NextBackScrollView>

        <com.appname.UI.Shared.CreateNewAccount.NextBackScrollView
            android:layout_width="fill_parent" android:id="@+id/NextBackScrollView3"
            android:layout_height="fill_parent" android:fillViewport="true">

            <LinearLayout
                android:orientation="vertical"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">

                <TextView android:padding="10dp" android:gravity="center"
                    android:text="@string/CreateNewAccountPersonalInfoMessage"
                    android:layout_marginTop="20px" android:layout_width="match_parent"
                    android:id="@+id/createNewAccountPersonalInfoMessage"
                    android:layout_height="wrap_content">
                </TextView>

                <EditText
                    android:inputType="textPersonName"
                    android:hint="First Name"
                    android:id="@+id/newAccountFirstName"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </EditText>

                <EditText
                    android:inputType="textPersonName"
                    android:hint="Last Name"
                    android:id="@+id/newAccountLastName"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </EditText>

                <EditText
                    android:inputType="textPostalAddress"
                    android:hint="Street Address"
                    android:id="@+id/newAccountStreetAddress"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </EditText>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_gravity="center"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="10dp">

                    <EditText
                        android:layout_weight="3"
                        android:maxLength="20"
                        android:hint="City"
                        android:id="@+id/newAccountCity"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress">
                    </EditText>

                    <EditText
                        android:layout_weight="1"
                        android:maxLength="2"
                        android:hint="St"
                        android:id="@+id/newAccountState"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress">
                    </EditText>

                    <EditText
                        android:layout_weight="2"
                        android:maxLength="5"
                        android:hint="Zip"
                        android:id="@+id/newAccountZipCode"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress">
                    </EditText>
                </LinearLayout>
            </LinearLayout>
        </com.appname.UI.Shared.CreateNewAccount.NextBackScrollView>

        <com.appname.UI.Shared.CreateNewAccount.NextBackScrollView
            android:layout_width="fill_parent"
            android:id="@+id/NextBackScrollView4"
            android:layout_height="fill_parent"
            android:fillViewport="true">

            <LinearLayout
                android:orientation="vertical"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">

                <TextView
                    android:padding="10dp"
                    android:gravity="center"
                    android:text="@string/CreateNewAccountBusinessMessage"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:id="@+id/createNewAccountBusinessMessage"
                    android:layout_height="wrap_content">
                </TextView>

                <CheckBox
                    android:text="Is business account"
                    android:contentDescription="Is business account? Click for yes"
                    android:id="@+id/isNewBusinessAccountCheck"
                    android:layout_gravity="center"
                    android:layout_marginTop="20px"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </CheckBox>

                <EditText
                    android:inputType="textPersonName"
                    android:hint="Business Name"
                    android:id="@+id/newAccountBusinessName"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:visibility="invisible">
                    <requestFocus></requestFocus>
                </EditText>

                <EditText
                    android:inputType="textPostalAddress"
                    android:hint="Mailing Address"
                    android:id="@+id/newAccountBusinessAddress"
                    android:selectAllOnFocus="true"
                    android:layout_marginTop="20px"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:visibility="invisible">
                </EditText>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_gravity="center"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="10dp">

                    <EditText
                        android:layout_weight="3"
                        android:maxLength="20"
                        android:hint="City"
                        android:id="@+id/newAccountBusinessCity"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress"
                        android:visibility="invisible">
                    </EditText>

                    <EditText
                        android:layout_weight="1"
                        android:maxLength="2"
                        android:hint="St"
                        android:id="@+id/newAccountBusinessState"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress"
                        android:visibility="invisible">
                    </EditText>

                    <EditText
                        android:layout_weight="2"
                        android:maxLength="5"
                        android:hint="Zip"
                        android:id="@+id/newAccountBusinessZipCode"
                        android:selectAllOnFocus="true"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:inputType="textPostalAddress"
                        android:visibility="invisible">
                    </EditText>
                </LinearLayout>
            </LinearLayout>
        </com.appname.UI.Shared.CreateNewAccount.NextBackScrollView>

        <com.appname.UI.Shared.CreateNewAccount.NextBackScrollView
            android:layout_width="fill_parent"
            android:id="@+id/NextBackScrollView5"
            android:layout_height="fill_parent"
            android:fillViewport="true">

            <LinearLayout
                android:orientation="vertical"
                android:gravity="center_horizontal"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">
                <TextView
                    android:gravity="center"
                    android:text="@string/CreateNewAccountCompleteMessage"
                    android:layout_marginTop="20px"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </TextView>

                <Button
                    android:gravity="center"
                    android:text="Create Account"
                    android:id="@+id/createAccountButton"
                    android:layout_marginTop="20px"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </Button>
            </LinearLayout>
        </com.appname.UI.Shared.CreateNewAccount.NextBackScrollView>
    </ViewFlipper>

    <LinearLayout
        android:id="@+id/pager"
        android:background="@drawable/new_account_navbar_background"
        android:layout_alignParentBottom="true"
        android:layout_height="50dp"
        android:layout_width="fill_parent">
    </LinearLayout>
</RelativeLayout>

A: We have also run into this, seems like an Android bug.

A: if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_YES)

problem solved!!
EDIT:
I don't believe this was ever actually solved but I am no longer involved in this project.


text:
Q: How to speed up GET requests when using a Queue I'm using Huey/Hueyx as a queue to buffer resources I need to GET with pythons requests library. Credentials (a token) are stored in Redis and the task executor calls the function, gets the resource and then indexes it to elastic search. Because I need to request millions of different resources and my solution is quite slow (around 5k requests per minute) the queue backs up very quickly and the performance takes a hit.
def get_raw_resource(url, token, id):
        try:
                url = f"{url}/api/v2/{id}"

                headers = {
                    'Accept': "application/json",
                    'Authorization': f"Bearer {token}",
                    'Cache-Control': "no-cache"
                }
                response = requests.get(url, headers=headers)
        [snip]

@res_q.task(delay=10, retries=3, retry_delay=180)
def get_resource_es(client_id, id):
        [snipped redis stuff]
        try:
                res = get_raw_resource(url, token, id)
                parsed = parse_res(res)
                es.index(index=es_index, body=parsed, id=id)
        except Exception as e:
                raise e

My question is: how can I make this whole ordeal faster with some easy steps? Adding more consumers is always an option, but it's not something I want to do right now before exploring other options. I've read about async code, however it looks like it would quadruple the complexity of the code. Also, I know nothing about the async programming model.


text:
Q: Gap between horizontal image and embed video There is a gap between the image and embedded video.There is no problem in mobile view.

A: add class 'nopadding' with col-sm-6 ... That will solve your problem.

CSS file add following code :
.nopadding {
   padding: 0 !important;
   margin: 0 !important;
}


text:
Q: (windows) raw write to file without involving win32api I would like to know if there is an option, and if so - how exactly, to be able to write raw bytes to a file without using WIN32API file handling calls, while in Windows.
I tried to use a stright-forward approach using x86asm direct file calls, but without success in the meantime.

A: You can try using the native API from ntdll or even direct syscalls (int 2eh or systenter instruction), but it's quite tricky - you need to use kernel-style filenames, for one.

A: Before answering your question let me mention that writing to a file using API in Windows consists of following (simplified) stages:

*

*You call WriteFile (kernel32.dll)

*WriteFile calls NtWriteFile (ntdll.dll)

*NtWriteFile calls SYSENTER and operation proceeds to kernel mode

*In kernel mode NtWriteFile function of Ntoskrnl.exe is called

*This sends IRP_MJ_WRITE to file system driver

*File system driver determines which sectors should be written and passes to storage driver

*Storage driver sends a command to the hard drive to actually write data to specified sectors

*Hard drive writes the data

All operations 1 to 7 are very fast compared to 8 (unless you are working with a RAM drive or extremely fast SSD)
Method 1 - You can skip Step 1 easily (by calling NtWriteFile), and Step2 (by calling SYSENTER - not easy). However you will not gain any performance improvement, so no point in doing it. Consider WriteFile just a wrapper for those (I don't think you are after eliminating one extra function call).
Method 2 - you can find out which sectors the file occupies and write to them directly (effectively skipping all steps down to Step 7). To do that you will need to open and lock the volume, find the clusters that the target file occupies by FSCTL_GET_RETRIEVAL_POINTERS call, and call WriteFile on volume handle.
But it will be unfair comparison, because file system driver not only writes to the data sectors, but also updates file system metadata when you call WriteFile.
Bottom line is - "Testing efficiency over win32 API" doesn't make much sense. You can skip some of the stuff that OS does, but either won't give you any difference in speed (method 1), or there will be unfair comparison (method2).


text:
Q: How to change the color of reference numbers in my dissertation? The color of numbers for references is green . I need to change it to black. Any help is massively appreciated .

A: Assuming that these links are set by hyperref you can put this at the end of your preamble (or anywhere after hyperref has been loaded):
    \hypersetup{citecolor=black}


text:
Q: drawing balls from urn calculated using combinations An urn contains seven red balls, seven white balls, and seven blue balls. A sample of five balls is drawn at random without replacement. Compute the probability that The sample contains four balls of one colour and one ball of another colour.
Correct answer is $\dfrac{\dbinom31\dbinom74\dbinom21\dbinom71}{\dbinom{21}{5}}$
however I do not understand how it was reached

A: First, pick one of the 3 colors to be the color with four balls -- $3\choose1$
Then from that color pick 4 balls from the 7 -- $7\choose4$
Next pick one of the remaining two colors to be the one with 1 ball -- $2\choose1$
Then pick the 1 ball from that color -- $7\choose1$
Finally, the total number of sets of 5 you could have picked is just 5 from 21 -- $21\choose5$
So you get $$\frac{{3\choose1}{7\choose4}{2\choose1}{7\choose1}}{21\choose5}$$


text:
Q: Changing my paypal from 1 time payment to paypal sub So i have a membership site were users need to pay x amount each month to use it at the moment i have coded it so that they need to checkout each month them self of course users are asking me to change this so it takes the payments on auto. The user needs to go to my membership page pick one which then takes 1 payment . I have gone to paypal and made a sub button but wanted some help to add it into my current payment coding
      Select
                                <?php

            if (isset($_GET['Popular'])) {

// Setup class
require_once('paypal.class.php');  // include the class file
$p = new paypal_class;             // initiate an instance of the class
$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';   // testing paypal url
//$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url

// setup a variable for this script (ie: 'http://www.domain.com/paypal.php')
$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

// if there is not action variable, set the default action of 'process'
if (empty($_GET['action'])) $_GET['action'] = 'process';

switch ($_GET['action']) {

   case 'process':      // Process and order...

      // There should be no output at this point.  To process the POST data,
      // the submit_paypal_post() function will output all the HTML tags which
      // contains a FORM which is submited instantaneously using the BODY onload
      // attribute.  In other words, don't echo or printf anything when you're
      // going to be calling the submit_paypal_post() function.

      // This is where you would have your form validation  and all that jazz.
      // You would take your POST vars and load them into the class like below,
      // only using the POST values instead of constant string expressions.

      // For example, after ensureing all the POST variables from your custom
      // order form are valid, you might have:
      //
      // $p->add_field('first_name', $_POST['first_name']);
      // $p->add_field('last_name', $_POST['last_name']);

      $p->add_field('business', 'admin@mydomain.com');
      $p->add_field('return', $this_script.'?action=success');
      $p->add_field('cancel_return', $this_script.'?action=cancel');
      $p->add_field('notify_url', $this_script.'?action=ipn');
      $p->add_field('item_name', 'mydomain.com Popular Account Upgrade');
      $p->add_field('amount', '2.00');

      $p->submit_paypal_post(); // submit the fields to paypal
      //$p->dump_fields();      // for debugging, output a table of all the fields
      break;

   case 'success':      // Order was successful...

      // This is where you would probably want to thank the user for their order
      // or what have you.  The order information at this point is in POST
      // variables.  However, you don't want to "process" the order until you
      // get validation from the IPN.  That's where you would have the code to
      // email an admin, update the database with payment status, activate a
      // membership, etc.

      echo "<title>Success</title>
Thank you for your order.
";
      foreach ($_POST as $key => $value) { echo "$key: $value
"; }
      echo "";

      // You could also simply re-direct them to another page, or your own
      // order status page which presents the user with the status of their
      // order based on a database (which can be modified with the IPN code
      // below).

      break;

   case 'cancel':       // Order was canceled...

      // The order was canceled before being completed.
 echo "sorry ";
      echo "<title>Canceled</title>
The order was canceled.
";
      echo "";

      break;

   case 'ipn':          // Paypal is calling page for IPN validation...

      // It's important to remember that paypal calling this script.  There
      // is no output here.  This is where you validate the IPN data and if it's
      // valid, update your database to signify that the user has payed.  If
      // you try and use an echo or printf function here it's not going to do you
      // a bit of good.  This is on the "backend".  That is why, by default, the
      // class logs all IPN data to a text file.

      if ($p->validate_ipn()) {

         // Payment has been recieved and IPN is verified.  This is where you
         // update your database to activate or process the order, or setup
         // the database with the user's order details, email an administrator,
         // etc.  You can access a slew of information via the ipn_data() array.

         // Check the paypal documentation for specifics on what information
         // is available in the IPN POST variables.  Basically, all the POST vars
         // which paypal sends, which we send back for validation, are now stored
         // in the ipn_data() array.

         // For this example, we'll just email ourselves ALL the data.
         echo"  worked";
         $subject = 'Instant Payment Notification - Recieved Payment';
         $to = 'myemail@live.co.uk';    //  your email
         $body =  "An instant payment notification was successfully recieved\n";
         $body .= "from ".$p->ipn_data['payer_email']." on ".date('m/d/Y');
         $body .= " at ".date('g:i A')."\n\nDetails:\n";

         foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
         mail($to, $subject, $body);
      }
      break;
 }

            }

paypalclass
class paypal_class {

   var $last_error;                 // holds the last error encountered

   var $ipn_log;                    // bool: log IPN results to text file?

   var $ipn_log_file;               // filename of the IPN log
   var $ipn_response;               // holds the IPN response from paypal
   var $ipn_data = array();         // array contains the POST values for IPN

   var $fields = array();           // array holds the fields to submit to paypal

   function paypal_class() {

      // initialization constructor.  Called when class is created.

      $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';

      $this->last_error = '';

      $this->ipn_log_file = '.ipn_results.log';
      $this->ipn_log = true;
      $this->ipn_response = '';

      // populate $fields array with a few default values.  See the paypal
      // documentation for a list of fields and their data types. These defaul
      // values can be overwritten by the calling script.

      $this->add_field('rm','2');           // Return method = POST
      $this->add_field('cmd','_xclick');

   }

   function add_field($field, $value) {

      // adds a key=>value pair to the fields array, which is what will be
      // sent to paypal as POST variables.  If the value is already in the
      // array, it will be overwritten.

      $this->fields["$field"] = $value;
   }

   function submit_paypal_post() {

      // this function actually generates an entire HTML page consisting of
      // a form with hidden elements which is submitted to paypal via the
      // BODY element's onLoad attribute.  We do this so that you can validate
      // any POST vars from you custom form before submitting to paypal.  So
      // basically, you'll have your own form which is submitted to your script
      // to validate the data, which in turn calls this function to create
      // another hidden form and submit to paypal.

      // The user will briefly see a message on the screen that reads:
      // "Please wait, your order is being processed..." and then immediately
      // is redirected to paypal.

      echo "\n";
      echo "<title>Processing Payment...</title>\n";
      echo "\n";
      echo "
Please wait, your order is being processed and you";
      echo " will be redirected to the paypal website.
\n";
      echo "<form method=\"post\" name=\"paypal_form\" ";
      echo "action=\"".$this->paypal_url."\">\n";

      foreach ($this->fields as $name => $value) {
         echo "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n";
      }
      echo "

If you are not automatically redirected to ";
      echo "paypal within 5 seconds...

\n";
      echo "<input type=\"submit\" value=\"Click Here\">\n";

      echo "</form>\n";
      echo "\n";

   }

   function validate_ipn() {

      // parse the paypal URL
      $url_parsed=parse_url($this->paypal_url);

      // generate the post string from the _POST vars aswell as load the
      // _POST vars into an arry so we can play with them from the calling
      // script.
      $post_string = '';
      foreach ($_POST as $field=>$value) {
         $this->ipn_data["$field"] = $value;
         $post_string .= $field.'='.urlencode(stripslashes($value)).'&';
      }
      $post_string.="cmd=_notify-validate"; // append ipn command

      // open the connection to paypal
      $fp = fsockopen($url_parsed[host],"80",$err_num,$err_str,30);
      if(!$fp) {

         // could not open the connection.  If loggin is on, the error message
         // will be in the log.
         $this->last_error = "fsockopen error no. $errnum: $errstr";
         $this->log_ipn_results(false);
         return false;

      } else {

         // Post the data back to paypal
         fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n");
         fputs($fp, "Host: $url_parsed[host]\r\n");
         fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
         fputs($fp, "Content-length: ".strlen($post_string)."\r\n");
         fputs($fp, "Connection: close\r\n\r\n");
         fputs($fp, $post_string . "\r\n\r\n");

         // loop through the response from the server and append to variable
         while(!feof($fp)) {
            $this->ipn_response .= fgets($fp, 1024);
         }

         fclose($fp); // close connection

      }

      if (eregi("VERIFIED",$this->ipn_response)) {

         // Valid IPN transaction.
         $this->log_ipn_results(true);
         return true;

      } else {

         // Invalid IPN transaction.  Check the log for details.
         $this->last_error = 'IPN Validation Failed.';
         $this->log_ipn_results(false);
         return false;

      }

   }

   function log_ipn_results($success) {

      if (!$this->ipn_log) return;  // is logging turned off?

      // Timestamp
      $text = '['.date('m/d/Y g:i A').'] - ';

      // Success or failure being logged?
      if ($success) $text .= "SUCCESS!\n";
      else $text .= 'FAIL: '.$this->last_error."\n";

      // Log the POST variables
      $text .= "IPN POST Vars from Paypal:\n";
      foreach ($this->ipn_data as $key=>$value) {
         $text .= "$key=$value, ";
      }

      // Log the response from the paypal server
      $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response;

      // Write to log
      $fp=fopen($this->ipn_log_file,'a');
      fwrite($fp, $text . "\n\n");

      fclose($fp);  // close file
   }

   function dump_fields() {

      // Used for debugging, this function will output all the field/value pairs
      // that are currently defined in the instance of the class using the
      // add_field() function.

      echo "
paypal_class->dump_fields() Output:
";
      echo "

               Field Name
               Value

";

      ksort($this->fields);
      foreach ($this->fields as $key => $value) {
         echo "
$key	".urldecode($value)."
";
      }

      echo "

";
   }
}

so i just noticed in the paypal class all i need to do is change it to
  $this->add_field('rm','2');           // Return method = POST
  $this->add_field('cmd','_xclick-subscriptions');

but now getting the error
Invalid Regular period. You must specify valid values for the A3, P3 and T3 parameters for a subscription.

A: I fixed it by editing the paypal class and adding this
  $this->add_field('rm','2');           // Return method = POST
  $this->add_field('cmd','_xclick-subscriptions');
   $this->add_field('a3','2');
       $this->add_field('p3','1');
          $this->add_field('t3','M');
                $this->add_field('src','1');


text:
Q: Can't connect to router after turning off DHCP So I was playing around with my router and dynamic/static IP addresses and after I tuned off the DHCP server of the Router I am no longer able to connect to the routers web interface even with a static IP.
The IP of the router is 10.0.0.138 and I also can configure a static IP on my Win7 like:
IP: 10.0.0.50
Netmask: 255.255.255.0
Gateway: 10.0.0.138
DNS: 10.0.0.138
so I can connect to the internet and ask a question on superuser.com but I am no longer able to connect to my router (connection refused) and undo my configurations?
Or is this a feature of thos cheap routers from the internet providers?
NOTE: I am connected via WLAN

A: The solution for me was to reset the router.
There was no way for me to gain access to the router again after I disabled the router's DHCP server. Not via WLAN, cable, telepathy or all the known standard router IP addresses I have found on the web.


text:
Q: How do I get the type of a variable in MySQL? I'm trying to change a table field that contains decimal numbers from varchar(255) to decimal(12,2). And before I do that, I'd like to find out if there is information that would get deleted in the process: are there any rows where this field contains something other than a decimal(12,2).
I'm stumped how to do this. Apparently there isn't a string function like is_numeric() in PHP. I already tried casting the field to decimal and then comparing it with the original string, but this returns TRUE even for obvious cases where it should not:
select ('abc' = convert('abc', decimal(12,2)));

returns 1
Any help? How do I find out if a string contains something other than a decimal in MySQL? Thanks.

A: Stupid me, I have to cast twice (to decimal and back to char), which makes it work:
select ('abc' = convert(convert('abc', decimal(12,2)), char(255)));
returns 0
Thanks.

A: If you want to examine if the strings are actually floating points numbers, you could also use a regular expression. The following regex can help :)
SELECT '31.23' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 1
SELECT '31' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 1
SELECT 'hey' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 0


text:
Q: How to add more actions to a column in Magento grid? In Magento 1.9 I add a column to Sales Grid using an observer. I want to show more actions instead only one action.
With my code, in my column I see a select box, with the two actions. Instead I want to see the two actions, one under the other.
This is my observer:
class VendorName_ModuleName_Model_ObserverAddColumn
{
    public function addColumnToGrid(Varien_Event_Observer $observer)
    {
        $block = $observer->getEvent()->getBlock();

        if (!($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid) || $block->getNameInLayout() != 'sales_order.grid')
            return $this;

        // Add a new column rigth after the "view" column
        $block->addColumnAfter('view', [
        'header' => $block->__('Header'),
        'width' => '60px',
        'index' => 'index_example',
        'type'   => 'action',
        'sortable' => false,
        'getter'   => 'getId',
        'actions'   => array(
                array(
                        'caption'   => Mage::helper('ModuleName')->__('One'),
                        'url'       => array('base'=> 'routerName/controllerName/actionName'),
                        'field'     => 'id'
                ),
                array(
                        'caption'   => Mage::helper('ModuleName')->__('Two'),
                        'url'       => array('base'=> 'routerName/controllerName/actionName2'),
                        'field'     => 'id'
                    )
        ),
        'filter' => false
        ], 'entity_id');

       return $this;
   }

}

A: This plugin will solve all grid related problems. Please test it on development 1st. https://www.magentocommerce.com/magento-connect/enhanced-admin-grids-editor.html


text:
Q: why is this code not giving the desired output? #include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<int> parseInts(string str) {
    istringstream ss(str);
    vector<int> integ;
    int val;
    while(ss){

        if(ss>>val){
            integ.push_back(val);
        }
    }

    return integ;
}
vector<int> parseInts2(string str)
{
    vector<int> vec;
    stringstream ss(str);
    char ch;
    int temp;

    while(ss)
    {
        ss>>temp>>ch;   >> operator
        vec.push_back(temp);
    }

    return vec;
}
int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }

    return 0;
}

i want to create a stream,to a string,read integers to the stream from the string and insert it in a vector and display its elements while the output is displaying nothing.what is wrong with the code?
EDIT
basically the question ask inputs in the form of integers that are separated by commas and asks us to print the integers after parsing it. i find no significant difference between the 2 functions but parseInt2 still works(while calling the function in main,of course instead of parseInt). Why?

A: I fear that your question will be closed by people on SO.
But let me give you the answer.
Basically everything set already in the comments. Why not in an answer? I do not know.
Before you can read something from an std::istringstream, you need to put something in it. You need to initialize it. That is usually done by using its constructor:
istringstream ss(str);

In main, you have the problem, that you read only one value from std::cin with cin >> str;. You want to use std::getline instead, which reads a complete line. And not only "something" up to the next space. So
getline(cin, str);

will help you further.
In modern C++, with keeping the std::istringstream approach, you would probably write
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>

int main() {

    // Read a line and check, if that worked
    if (std::string str; std::getline(std::cin, str)) {

        // Create and initialize a std::istringstream
        std::istringstream iss(str);

        // Define a variable integers, use its range constructor with iterators
        std::vector integers(std::istream_iterator<int>(iss), {});

        // Range based for loop
        for (const int& i : integers) {
            std::cout << i << "\n";
        }
    }

    return 0;
}

That will save the subfunction.

EDIT:
OK, you want to read csv and you must use ">>".
If you want to read data separated by comma from a stream, then you need to extract:

*

*an integer value from the stream

*then a comma

*then a integer

*then a comma

*then a integer

*. . .

The extractor operator, or the functionality behind it, will always extract characters from a stream and convert it to a requested type (e.g. an integer), until it reaches a space or the conversion can not be continued any longer (for example, a "," is a separator).
That is the reason, why your 2nd function works.
It is important that you alwys check the status of the extraction operation. In the below example you will see that, at the end of the string, we try to read a comma, where there is none. The extraction fails, but we do not care. We ignore it by intent. To understand the functionality better, please see.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main() {
    // Source or test data. We put it directly into the stream;
    std::istringstream ss{ "1,2,3,  4  ,  5,6" };
    std::vector<int> integers{};
    char comma{};
    int integer{};

    while (ss)  {

        // Read integer and check, if it could be read
        if (ss >> integer) {
            integers.push_back(integer);
            std::cout << "Read Integer " << integer << "\n";
        }
        else
            std::cerr << "Error: Could not read integer\n";

        // Now read the comma
        if (ss && (ss >> comma))
            std::cout << "Read Comma: " << comma << "\n";
        else
            std::cerr << "Error: Could not read comma\n";
    }
    // SHow all values
    for (const int i : integers) std::cout << i << "\n";

    return 0;
}

If you have questions, I am happy to answer.


text:
Q: Compress/decompress string on .NET server that was encoded with lz-string.js on client I am using the LZString.compressToBase64 function of lz-string.js and need to decompress/compress the data on the server side.
The obvious solution seems to be lz_string_csharp  but I am concerned about
this statement:

If you use just the regular Javascript 'compress' function then depending on the data in the string, it will not decompress correctly on the C# side.
However, if you are using the 'compress' function built into this C# version, then you should be ok to use the regular 'decompress' function included.

and about this reported issue:  possible bug in c# version of compressToBase64

A: The full description in the link you give says that you should be able to use 'compressToUTF16' and it will always work, rather than just 'compress', which won't always work.
I've tested it personally and seen that it works.
(Though I changed the Context_Compress_Data.str field from a string to a StringBuilder in the C# file, because it was too slow to run. After that it took only 8 seconds for an 8 MB JSON file and compressed to 7% of the original size.)

A: We fixed this by adding  enc1 = enc2 = enc3 = enc4 = 0; between the two rows below  (line 580 in original file before stringbuilder version)
From what I remember, the bug was caused by  the values of enc1, enc2, etc... not being reset at the start of each loop, so sometimes a new iteration of the loop had wrong values from the previous round.
  i += 3;

                    enc1 = enc2 = enc3 = enc4 = 0;

                    enc1 = (int)(Math.Round(chr1)) >> 2;