text:
Q: H2 equivalent of Postgres `SERIAL` or `BIGSERIAL` column? In Postgres, defining a column with SERIAL/BIGSERIAL has a triple effect as discussed here:

*

*Define a int/bigint column.

*Create a sequence object to generate auto-incrementing numbers.

*Set the default of the column to call nextval() on the sequence.

Is there a similar shortcut command in H2 to get this related set of behavior?
If not, what would the long version of the SQL be?

A:
Where does the sequence live? How can you adjust its value or reset it?

If you create a column as auto_increment (or identity) H2 creates a sequence in the background. The name of that sequence can be obtained by looking at information_schema.columns:
create table foo
(
  id           integer auto_increment,
  other_column varchar(20)
);

If you then run:
select column_name, column_default
from information_schema.columns
where table_name = 'FOO'
and table_schema = 'PUBLIC';

You'll get something like this:
COLUMN_NAME  | COLUMN_DEFAULT
-------------+-----------------------------------------------------------------------------
ID           | (NEXT VALUE FOR PUBLIC.SYSTEM_SEQUENCE_C1C36118_ED1C_44D6_B573_6C00C5923EAC)
OTHER_COLUMN |

You can alter that sequence without problems:
alter sequence SYSTEM_SEQUENCE_C1C36118_ED1C_44D6_B573_6C00C5923EAC
   restart with 42;

This is essentially identical to Postgres' serial data type

If not, what would the long version of the SQL be?

create sequence foo_id_seq;

create table foo
(
  id           integer default foo_id_seq.nextval,
  other_column varchar(20)
);

The big difference between this and a Postgres serial is that H2 does not know that the sequence "belongs" to the column. You need to drop it manually when the table is dropped.
foo_id_seq.nextval will actually be converted to (NEXT VALUE FOR PUBLIC.FOO_ID_SEQ) when the table is created (and it will be stored like that in information_schema.columns.


text:
Q: DHCPD: permanently leased IP being offered (twice) to random node and assignee Greeting.
On a small LAN (< 20 networked devices) with a cento6 5.9 server/dhcp-3.0.5-33.el5_9). I am configuring permanent leases thusly (dhcpd.conf, partial):
  range 10.115.64.60 10.115.64.250;
  host vega.nouvelle.it      {hardware ethernet 00:1e:c9:47:f1:2d; fixed-address 10.115.64.6;    }
  host aldebaran.nouvelle.it {hardware ethernet 00:07:84:FB:55:40; fixed-address 10.115.64.66;   }

Which works pretty much OK most of the time. Occasionally, however, a lab machine (transient) will get a nailed IP. and, when the owner asks for it, it is then offered a second time leading to conflicts, etc.
I thought that fixing an address would reserve it and protect it from being allocatedo to othe MACs, but, regardless, I surely don't expect the server to offer the same IP twice.
Wrong configuration? Dhcpd bug?

A: I have always made it a practice to keep fixed addresses outside the DHCP range.  That should eliminate this issue.  DCHP will offer fixed addresses outside its dynamic range.   For fixed addresses, it is common to use infinite or at least very long leases.
Check the DHCP leases file to see if the server has an active lease.   They are normally configured not to use DHCP, and therefore would not have a lease.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The relation between eigenvalue and singular value of non-symmetric square matrix The problem bothers me for a long time.
Suppose, we have two matrix $A$ and $B$, where $A$ is a $m$ by $n$ complex matrix while $B$ is a $n$ by $m$ complex matrix.
Apparently, $AB$ and $BA$ have the same non-zero eigenvalues.
However, can we predict the non-zero eigenvalues just based on the information of singular values of $A$, $B$, $AB$ and $BA$.
Is there any relation between the singular values and eigenvalues?

A: We certainly can't predict phases: e.g. multiply $A$ by a complex number $\omega$ with $|\omega|=1$, and you don't change any of the singular values but you multiply the eigenvalues of $A$ and $AB$ by $\omega$.
Consider the case $A = I$, $B$ a unitary $n \times n$ matrix.  Then the singular values of $A$, $AB$, $BA$ are all $1$, but the eigenvalues of $B$ could be any $n$ points on the unit circle.
One relation you do have: the product of the eigenvalues of $AB$ (counted by algebraic multiplicity) is the determinant of $AB$, and its absolute value is the product of the singular values of $AB$.


text:
Q: Import data with CSV file, Don't know how to build task 'csv:import_movies' I am trying to populate my database with a CSV file. I have looked for other questions on SO and after trying everything I am stuck and was able come up with this:
# lib/tasks/import.rake
require 'csv'

desc 'Import Movies'
namespace :csv do
  task :import_movies => [:environment] do
    csv_file = '#{Rails.root}/lib/data/movie.csv'

    CSV.foreach(csv_file, headers: true) do |row|
      Movie.create! ({
        name: row[0],
        url: row[1],
        year: row[2],
        description: row[3],
        genre: row[4]
        })
    end

    # this was also a method others were recommending so I saved it
    #CSV.foreach(filename, :headers => true) do |row|
      #Movie.create!(row.to_hash)
    #end

  end
end

But when I run rake csv:import_movies I get this error running rake csv:import_movies --trace
rake aborted!
Don't know how to build task  'csv:import_movies'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/task_manager.rb:62:in`[]'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:149:in `invoke_task'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:106:in `each'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:106:in `block in top_level'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:115:in `run_with_threads'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:100:in `top_level'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:78:in `block in run'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:176:in `standard_exception_handling'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/lib/rake/application.rb:75:in `run'
/home/action/.rvm/gems/ruby-2.1.1/gems/rake-10.3.1/bin/rake:33:in `<top(required)>'
/home/action/.rvm/gems/ruby-2.1.1/bin/rake:23:in `load'
/home/action/.rvm/gems/ruby-2.1.1/bin/rake:23:in `<main>'
/home/action/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/home/action/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'

And I also tried doing it using this method
# db/seeds.rb
require 'csv'

csv_file_path = '#{Rails.root}/lib/data/movie.csv'
File.open(csv_file_path) do |movies|
  movies.read.each_line do |movie|
    title, url, year, description, genre = movie.chomp.split(",")
    Movie.create!( name: title, url: url, year: year, description: decription, genre: genre )
  end
end

And then ran rake db:seed --trace and then I got an error again which was:
** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:abort_if_pending_migrations

I ran rake db:migrate:status and got this, which is weird and I haven't come across before:
Status   Migration ID    Migration Name
--------------------------------------------------
up     20140407094349  ********** NO FILE **********
up     20140407094355  ********** NO FILE **********
up     20140407094405  ********** NO FILE **********
up     20140409112119  ********** NO FILE **********
up     20140409113144  ********** NO FILE **********

I hope someone has experience with this as this is my first time attempting to use rake and csv files in Rails. Thanks in advance!

A: try renaming your rake file to - 'csv.rake' and remove the [] around :environment
also put the description inside of the :namespace


text:
Q: Is it possible to approximate some PDE semigroups by explicit methods? I'm concerned with the numerical methods for the approximations of semigroup associated to following Cauchy problems (which typically involves unbounded operators):
$\begin{equation}
\begin{array}{ccc}
 \frac{du}{dt} + Au&  = & 0 \\
 u(0) &=& u_0.
\end{array}
\end{equation}$     (1)
When $A$ is an m-accretive operator, it is known [1] that, a solution $u(t)$ can be given by an exponential formula:
$
u(t) = \lim\limits_{n \rightarrow \infty} [(I + \frac{t}{n} A)^{-1}]^n u_0,
$ (2)
which can be seen as an implicit Euler discretization scheme in time for the Cauchy problem (1).
Question :
Is it possible for some operators A (typically a laplacian) to approximate the semigroup using an explicit scheme such as :
$U_{k+1} = U_k + hAU_k.$ (3)
Ref:
[1] Haïm Brezis "Analyse fonctionnelle et applications"

A: You can find some useful information in the manuscript:

P. Csomós, A. Bátkai, B. Farkas and A. Ostermann,
Operator Semigroups for Numerical Analysis 2013.


text:
Q: how to make view controller curved from top in swift i want to make white view controller which contain menu items  curved from top as shown in image below
i have implemented following code which making totally round edge view
not up from top
let maskLayer = CAShapeLayer()
         maskLayer.path = UIBezierPath(roundedRect: CGRectMake(0, 0, self.curvedView.frame.height, self.curvedView.frame.width+2), byRoundingCorners: UIRectCorner.TopLeft.union(.TopRight), cornerRadii: CGSizeMake(10,10)).CGPath
    self.curvedView.layer.mask = maskLayer

A: Here you go:
@IBOutlet weak var myRoundView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    let path = UIBezierPath(roundedRect:myRoundView.bounds, byRoundingCorners:[UIRectCorner.TopRight, .TopLeft], cornerRadii: CGSizeMake(70, 70))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    myRoundView.layer.mask = maskLayer

    // Do any additional setup after loading the view, typically from a nib.
}

Play with the number and UIView size to get it how you want it.


text:
Q: "NameError: name 'response' is not defined when i try to use the variable in Python3 import sys

def func2():
    print("1.Type a number ")
    print("2.Exit the program ")
    response = int(input())

func2()

def func1():
        print('Are you sure ? ')
        print("Yes or No")
        response = input()
        if response == 'Yes':
            sys.exit()
        elif response == "yes":
            sys.exit()
        else:
            func2()

if response == 1:
    secondresponse = input("Print a number ")
    print ("You typed in "+ secondresponse+ ".")
elif response == 2:
    func1()

Why does it give me the error NameError: name 'response' is not defined when I called the variable in the function. Or is that not allowed?

A: The variable response is only defined in the functions func1 & func2:
Right now you're trying to access the variable before it has been defined, therefore producing a NameError. Python doesn't know what response is as it's not in the same scope as your functions.
Instead, you should return the response from func2() and then check the value of response.
def func2():
    print("1.Type a number ")
    print("2.Exit the program ")
    response = int(input())
    return response

...

if func2() == 1:
  ...

I would recommend learning more about scope

A: because response is defined inside the function , use global that will solve it


text:
Q: Cannot parse date....in android here is the code
    public static final String KEY_DATE_TIME = "reminder_date_time";
    SimpleDateFormat datetimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT) ;

    try {
    String dateString = reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_DATE_TIME));

    Date date =  (Date) datetimeFormat.parse(reminder.getString(dateString);

    mCalendar.setTime(date);
    } catch (java.text.ParseException e) {
        Log.e("edit_activity", e.getMessage(), e);
    }

it is not parsing date as all the values are fetched but date is not parsed so logcat is showing an error...help me out


text:
Q: How can I set a value of a property without setter on a stub? Can I set a return value of a setter-less property of a stub that is created by Rhino.Mocks?
For example:
public interface IMyMachine { string myProperty { get; } }

...

IMyMachine m = MockRepository.GenerateMock<IMyMachine>();

// implement in a way so that m.myProperty will return "Ahoj!"
if (m.myProperty == "Ahoj!")
 //do something

A: m.Expect(x => x.myProperty).Return("abc");

or if you use a stub:
var m = MockRepository.GenerateStub<IMyMachine>();
m.Stub(x => x.myProperty).Return("abc");


text:
Q: Cifs share mount on a VPS without cifs module build in kernel It is possible to mount a samba share on a vps without cifs module buit in kernel?
I installed cifs-utils and smbclient, I can see samba shares with command
smbclient -L 192.168.5.1

I added in /etc/fstab
/192.168.5.1/Media /mnt/Media cifs credentials=/root/.mediacredentials,iocharset=utf8,sec=ntlm 0 0

But I get error:

mount error: cifs filesystem not supported by the system
  mount error(19): No such device
  Refer to the mount.cifs(8) manual page (e.g. man mount.cifs

There is an alternative to mount a samba share without cifs?
I tried with sshfs but get only errors:

remote host has disconnected
Connection reset by peer

Thanks

A: Not sure, how much Kernel support it actually needs and if that support is available to you, but the GNOME Virtual file system (GVfs) could be an option. Try something like:
gio mount 'smb://username@host/sharedfolder'

The mounted folder should show up within /run/user/$uid/gvfs. On older systems the executable might be gvfs-mount or gnome-mount.
Since GVfs uses the FUSE interface in order to run the file system driver in user space, there is a real possibility that it doesn't need Kernel support for the CIFS file system. However, it might rely on some other Kernel features necessary for the FUSE system. Let's hope your Kernel has it.
And, of course, it needs Gnome, or at least the GLib component - which is installed by default in most Desktop Unixes, but not necessarily on a server. So you may have to install GLib from the package manager of your distribution.
Also, be aware that the mounts that are created using FUSE drivers are only available to the user that mounted it. So this solution, even if it works, might not be good enough for your use case in a server, but that really depends on your exact use case.


text:
Q: How show a confirmation message at php form submit which contains a dynamic message text? I want to show a confirmation message at form submit with a confirmation message.
Confirmation message itself needs to do some php calls in order to do some validations and then show a message with ok and cancel buttons.
Upon pressing ok button, it should continue with submit flow and remain in the form otherwise.
I have taken following approach but it doesn't work. Even though it goes into else block it doesn't show the message. Seems like the second echo line is the problem.
Can you give me a clue on how to accomplish this task?
PHP code:
<?php
    if (!empty($_POST)){
        // read $_POST['item'] values and do the validation and construct validation message.
        // Because validation message is a dynamic one which is based on user inputs.
        // Some server calls are also needs to make within this validation phase.

        if(empty($validation_msg)) {
            saveData();
        }
        else {
            echo '<script type="text/javascript"> if (confirm("' . $validation_msg . '")) { ';
            echo saveData();
            echo ' } </script>';
        }
    }

    function saveData(){
        // Save function goes here.
    }
?>

HTML code:
<div class="form-group">
    <button type="submit" class="btn btn-primary" id="submit_button" disabled><?= _('Save') ?></button>
</div>


text:
Q: SELECT * FROM table WHERE * LIKE (SELECT * FROM table WHERE * = *) I have a separate table of Cities that have city codes in them and I also have a main table that contains a column 'address' which is only a short address. What I want is to select the city with code that is similar to the data in the 'address' column.
$cityCode=$db->query("SELECT city AS bot FROM city_table WHERE city LIKE (SELECT address FROM people WHERE people_id = $zz)");

$cityCode=$cityCode->num_rows > 0 ? $cityCode->fetch_array()['bot'] : "NOT LIKE";

city_table:

| province                | city                     |
| ----------------------- | ------------------------ |
| ILOCOS NORTE/012800000  | CITY OF BATAC/012805000  |

people:

| people_id               | address                  |
| ----------------------- | ------------------------ |
| 1                       | P-2, Brgy. 20, Batac City|

If the address contains "Batac", I want to echo it as 'CITY OF BATAC/012805000'

How to make this work?

A: You need to add the % wildcard characters around the city, and use that as the LIKE pattern to match with address.
$cityCode=$db->query("
    SELECT c.city AS bot
    FROM city_table AS c
    JOIN people AS p ON p.address LIKE CONCAT('%', c.city, '%')
    WHERE p.people_id = $zz");

A: Use Exists in where clause like this:
SELECT city AS bot FROM city_table c
WHERE EXISTS  (SELECT 1 FROM people WHERE people_id = $zz AND address LIKE '%'+c.city+'%' )

A: $cityCode=$db->query("SELECT city AS bot,

 FROM city_table WHERE city LIKE %(SELECT address FROM people WHERE
 people_id = $zz)%

I have updated the solution. Hope it works.


text:
Q: How to dynamically add wmode=opaque to already displaying embed elements? How to dynamically add wmode="opaque" to already displaying embed elements? Without reloading the elements, the embedded content should not lose its state.
Just setting the wmode attribute with javascript doesn't work.
Removing the element and then adding it again makes wmode take effect, but the flash element loses its state, among other problems. E.g if it's a video player its position/playback status resets. So that solution is no good.
Any other way of displaying content over the embedded element is acceptable as well.
(I'm doing this trough a content script in a Chrome extension if that is of any help.)

This is not a duplicated of How to dynamically add wmode=transparent to Youtube embed code? as there the parameter is added to a frame and not directly to the element it self.

A: It is possible but a bit tricky. If you don't mind using jQuery here is a nice way written by Jose Nobile http://www.nobilesoft.com/Scripts/fix_wmode2transparent_swf.js
If you want to stick to js then you can try something like shown here http://www.onlineaspect.com/2009/08/13/javascript_to_fix_wmode_parameters/
Hope it helps!

A: iframe masks out the part of the flash it's over, allowing other elements to display over it. At least in Chrome.
This is what YouTube uses for their play list bar (at the bottom of the view port).


text:
Q: Laravel route with multiple names Cant i have two names with one route?
Something like below:
Route::get('/', 'Admin\HomeController@index')->name(['admin.home', 'planner.home.index']);

Thanks!

A: This works only if you need the name, not the URL, although it's tricky and sloppy.
Route::get('/', 'Admin\HomeController@index')->name('admin.home');
Route::get('/2', function() {
    return redirect()->route('admin.home')
})->name('planner.home.index');

So if you use route('admin.home') or route('planner.home.index') it will redirects you to the method index in your HomeController.

A: You can make this, if you seek to have 2 version(route name) in the same app.
    <?php

    $routes = ['v1' => 'app.name1.', 'v2' => 'app.name2.'];
    foreach ($routes as $routeVersion => $routeName) {

        // Yours router app (i.e app/v1/pages or app/v2/pages)
        // Your router name (i.e app.name1 or app.name2)
        Route::prefix('app' . $routeVersion)
            ->middleware('auth')
            ->name($routeName)
            ->group(function(){

               # Your custom routes
               ...

            }
        }
    }

    ?>

This is an example of the response in the route list

I hope it serves you!

A: foreach($pages as  $key => $page){
    Route::any("/".$page, "Controller@index")->name($page);
}


text:
Q: Parallel Diode in RC charging circuit
When button is pushed , active low RES pin is activated till Vc reaches 2.5 Volts. I have two questions  here
1. What is the role of Diode which is connected reversed biased?
2. Which loop capacitor discharges when button is pushed ?
Thanks beforehand!

A: The diode is there so that when the supply switches off it discharges the capacitor C1 via the collapsing supply rail at the top of R3.

Which loop capacitor discharges when button is pushed ?

C1 is discharged by the switch and ideally (to prevent large current spikes potentially upsetting the MCU) there should be a 100 ohm resistor in series with the switch.


text:
Q: Django filter data using field in another model connected via foreign key I have two models; Sets and Cards. There are many cards in one set. I would like to get it so that I can filter the cards that are returned in my tables but the set code, which for the example below is khc.
I have manage to get it to work to an extent by adding filter(set__code__exact="khc") to the Card.objects but this does not allow the user to change that filtering on the web page.
I cannot seem to add a code filter to the CardFilter
models.py
class Set(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=64)
    ...

class Card(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...
    set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='Card')

views.py
def cards_page(request):
    card_list = Card.objects.filter(set__code__exact="khc").order_by('name')
    card_filter = CardFilter(request.GET, queryset=card_list)
    card_list = card_filter.qs

filters.py
class SetFilter(django_filters.FilterSet):
    code = CharFilter(field_name='code', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'}))
    name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': 'page-input', 'style': 'width: 150px;'}))
    type = CharFilter(field_name='type', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Type', 'class': 'page-input', 'style': 'width: 150px;'}))

    class Meta:
        model = Set
        fields = ''

class CardFilter(django_filters.FilterSet):
    # doesnt work # code = CharFilter(field_name='set', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'}))
    name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': 'page-input', 'style': 'width: 150px;'}))
    type = CharFilter(field_name='type_line', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Type', 'class': 'page-input', 'style': 'width: 150px;'}))

    class Meta:
        model = Card
        fields = ''

cards.html
<form method="get" class="" autocomplete="off">
    {{ card_filter.form.code }}
    {{ card_filter.form.name }}
    {{ card_filter.form.type }}
    <button class="page-btn-icon" type="submit">
    ...

screenshot of filters:

A: This was really simple when I manage to figure out how to do it.
I added set_id__code to the field_name variable in my filters.py file. set_id is the field that connects two tables together, followed by two underscores (__) and then the field name in the Set model I wanted to filter by.
code = CharFilter(field_name='set_id__code', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'}))


text:
Q: IOS : firing multiple segues from a prototype cell in storyboards Is there a way to connect a prototype cell to different scenes and on the didSelectRowAtIndexPath method call the [self performSegueWithIdentifier:@"NAMEOFTHESEGUE" sender:self] ?
I can't seem to drag multiple segues from the prototype cell to different scenes... I know it is possible with static cells because you can draw a segue from each cell to the scene but what if i'm using prototype cells?
I'm currently trying to implement this using the SWRevealViewController (https://github.com/John-Lluch/SWRevealViewController) plugin.
In the storyboard example project he's using a table with 3 static cells and connecting each cell to a different scene. But in my case static cells are not an option so if anyone knows the answer that would be great.
Oh and also embedding the "side panel view controller" which is a UIViewController inside a navigation controller so i can connect the navigation controller to different scenes is not an option because in that case the new scene opens inside the slide panel ...
Please take into consideration that i'm still a rookie in IOS programming.
Appreciate your time!
EDIT + solution : I had tried connecting the segues from the view controller to the scenes but it kept giving and exception "NSInvalidArgumentException - receiver has no segue with identifier..." The solution was in Xcode to go to "Product" then choose "Clean" : https://stackoverflow.com/a/14089463/1185133

A: Yes, the only thing is that you don't have to connect your prototype cell to multiple destinations, the origin of the multiple segue must be the view controller:
1 - create the segue from your Table View Controller (not the cell) to the destination VC and give to each segue an unique name.
2 - override didSelectRowAtIndexPath: and call [self performSegueWithIdentifier:@"NAMEOFTHESEGUE" sender:self]
That's all :-)

A: If you have you have put a table view within a View Controller, drag the segues from the Controller and not the cell, just as LombaX has explained above


text:
Q: How to label eyes detected using mediapipe How to label the person eye for a face detected via mp_face.process() of the mediapipe ?
I expect the output to be as below

Image taken from this link
One of alternate suggestion is given below. I save this as my and other future reference

A: To label the eye, first we need to find the left-right eye coordinate using
mp_face_detection.get_key_point()

Then, we need to get pixel coordinate of both eyes using
_normalized_to_pixel_coordinates()

The full code is as below
import cv2
import mediapipe as mp

from mediapipe.python.solutions.drawing_utils import _normalized_to_pixel_coordinates

dframe = cv2.imread("person.png")

image_input = cv2.cvtColor(dframe, cv2.COLOR_BGR2RGB)
# load face detection model
mp_face = mp.solutions.face_detection.FaceDetection(
    model_selection=1,  # model selection
    min_detection_confidence=0.5  # confidence threshold
)
results = mp_face.process(image_input)

image_rows, image_cols, _ = dframe.shape
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils

detection = results.detections[0]

eye_left=mp_face_detection.get_key_point(detection, mp_face_detection.FaceKeyPoint.LEFT_EYE)
#
eye_right=mp_face_detection.get_key_point(detection, mp_face_detection.FaceKeyPoint.RIGHT_EYE)

eye_r = _normalized_to_pixel_coordinates(eye_right.x,eye_right.y, image_cols,image_rows)
eye_l = _normalized_to_pixel_coordinates(eye_left.x,eye_left.y, image_cols,image_rows)
#
cv2.putText(image_input, 'R', eye_r,cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.putText(image_input, 'L', eye_l,cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

cv2.imwrite('this_output.png', image_input)

For list of facial keypoint
FACIAL_KEYPOINTS = mp.solutions.face_detection.FaceKeyPoint


text:
Q: NetServerEnum doesn't find computer I am using NetServerEnum() to discover computers in my network, the code is from here.
This is how I call the function to get the servers:
  var servers = GetServerList(SV_101_TYPES.SV_TYPE_ALL);

The function works, but it wont find 1 machine that is connected directly via ethernet cable to my computer. There is no switch or router in between the 2 machines.
I can see the machine if I go to Network in Windows.
Why wouldn't NetServerEnum() find the machine?


text:
Q: OpenCV Kalman filter I have three gyroscope values, pitch, roll and yaw. I would like to add Kalman filter to get more accurate values. I found the opencv library, which implements a Kalman filter, but I can't understand it how is it really work.
Could you give me any help which can help me? I didn't find any related topics on the internet.
I tried to make it work for one axis.
const float A[] = { 1, 1, 0, 1 };
CvKalman* kalman;
CvMat* state = NULL;
CvMat* measurement;

void kalman_filter(float FoE_x, float prev_x)
{
    const CvMat* prediction = cvKalmanPredict( kalman, 0 );
    printf("KALMAN: %f %f %f\n" , prev_x, prediction->data.fl[0] , prediction->data.fl[1] );
    measurement->data.fl[0] = FoE_x;
    cvKalmanCorrect( kalman, measurement);
}

in main
kalman = cvCreateKalman( 2, 1, 0 );
state = cvCreateMat( 2, 1, CV_32FC1 );
measurement = cvCreateMat( 1, 1, CV_32FC1 );
cvSetIdentity( kalman->measurement_matrix,cvRealScalar(1) );
memcpy( kalman->transition_matrix->data.fl, A, sizeof(A));
cvSetIdentity( kalman->process_noise_cov, cvRealScalar(2.0) );
cvSetIdentity(kalman->measurement_noise_cov, cvRealScalar(3.0));
cvSetIdentity( kalman->error_cov_post, cvRealScalar(1222));
kalman->state_post->data.fl[0] = 0;

And I call this everytime, when I receive data from gyro:
kalman_filter(prevr, mpe->getGyrosDegrees().roll);

I thought in kalman_filter the first parameter is the previous value and the second is the currect value. I'm not and this code doesn't work... I know I have a lot of work with it, but I don't know how to continue, what to change...

A: It seems like you are giving too high values to the covariance matrices.
kalman->process_noise_cov is the 'process noise covariance matrix' and it is often referred in the Kalman literature as Q. The result will be smoother with lower values.
kalman->measurement_noise_cov is the 'measurement noise covariance matrix' and it is often referred in the Kalman literature as R. The result will be smoother with higher values.
The relation between those two matrices defines the amount and shape of filtering you are performing.
If the value of Q is high, it will mean that the signal you are measuring varies quickly and you need the filter to be adaptable. If it is small, then big variations will be attributed to noise in the measure.
If the value of R is high (compared to Q), it will indicate that the measuring is noisy so it will be filtered more.
Try lower values like q = 1e-5 and r = 1e-1 instead of q = 2.0 and r = 3.0.


text:
Q: SwiftUI Navigation automatically closing/pop - Realm I'm populating a List with a Realm Result set.
When navigating from this list it opens a new view then automatically closes that view.
Using a struct presents no issue.
Why would the second view automatically close?
I have a screen recording but cant post here.
import SwiftUI
import Combine

struct TestStruct:Identifiable{

    let id = UUID()
    let firstname: String
}

extension TestStruct {
    static func all() -> [TestStruct]{
        return[
            TestStruct(firstname: "Joe"),
            TestStruct(firstname: "Jane"),
            TestStruct(firstname: "Johns")
        ]
    }
}

struct TestListView: View {
    let realmList = Horoscope.getHoroscopes() //Fetches from Realm
    let structList = TestStruct.all()

    var body: some View {
        NavigationView{
            // This owrks
            //            List(structList) { item in
            //                MyItemRow(itemTxt: item.firstname)
            //            }

            //This automatically closes the view
            List(realmList) { item in
                MyItemRow(itemTxt: item.firstname)
            }
            .navigationBarTitle("Charts", displayMode: .automatic)
            .navigationBarItems(trailing: EditButton())
        }
    }
}

struct MyItemRow: View {

    var itemTxt:String

    var body: some View {
        NavigationLink(destination: Text("Test")) {
            Text(itemTxt)
        }
    }
}

struct TestListView_Previews: PreviewProvider {
    static var previews: some View {
        TestListView()
    }
}

A: I think the answer can be found here
In short, do not generate the id of the collection on which the ForEach iterates. It would detect a change and navigate back.

Realm object has an auto generated id property with each reference, try replacing it with a consistent id

A: The following solution worked for me.
The code with an issue (specifying id: \.self is the root cause since it uses the hash calculated from all objects the Stream object consists of, including the data that lies in a subarray).
...
List(streams, id: \.self) { stream in
...

The code with no issues:
...
List(streams, id: \._id) { stream in

// or even List(streams) { stream in
...

The streams is a @ObservedResults(Stream.self) var streams and the object scheme is:
final class Stream: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var title: String
    @Persisted var subtitle: String?

    @Persisted var topics = RealmSwift.List<Topic>()

    // tags, etc.
}

The issue happened when I added new topic at the topics list in the first stack of the navigationView.


text:
Q: LDPC codes construction According to Google Scholar original Gallager's article Low-density parity-check codes is cited more than 10000 times. It looks scary for non-experts.
I suspect that the number of algorithms for constructing good sparse matrices for LDPC-codes is much less than 10000.  Is there any survey which contains description of such algorithms?
Basically I'm interested in explicit constructions based on number theory methods.

A: An overview of LDPC codes constructed using methods from combinatorial mathematics and finite geometry is given in Low Density Parity Check Codes Based
on Finite Geometries: A Rediscovery and New Results

In this paper, a geometric approach to the construction of LDPC codes
  is presented. Four classes of LDPC codes have been constructed based
  on the lines and points of the well known Euclidean and projective
  geometries over finite fields. Their performance is compared with that
  of randomly computer generated LDPC codes and irregular LDPC codes.

A: Ryan and Lin's Channel Codes has several chapters (computer-based, finite geometries, finite fields, combinatorial designs) devoted to various constructions of LDPC codes, as well as a chapter devoted to nonbinary codes that also details constructions for that case.


text:
Q: php numeric Variable Name I want to append some $variables automaticly and set their names numeric
I have a script look like this:
<?php
$i=0;
while($i<=100){

$variable_[$i]=$i;
$i++;
#with "[$i]" I mean their name will be $variable_1 , $variable_2, $variable_3 ...
#they will be automatic increased variables non manual!

}
?>

A: This is called variable variables.
You can set a variable variable by defining its name inside a variable, such as:
$name = 'variable_' . $i;

and then assign a value to it by doing:
$$name = $i;

Note that variable variables can easily be misused. Make sure you completely understand the repercussions of this feature on your code and the risk of having bugs, and ensure this is the only solution you have, i.e. you can't use an array ($variables[$i] = $i;) instead.

A: Its better to use Array with key=> value pair. You can build this array dynamically and then loop through it by using foreach.


text:
Q: Insert NVARCHAR string using LINQ to SQL Here is the problem. I have a table in a SQL Server database
CREATE TABLE Users
(
    [userID]        INT             PRIMARY KEY IDENTITY,
    [userName]      NVARCHAR(255)   NOT NULL,
    [userEmail]     VARCHAR(127)    NOT NULL,
    [userComment]   NVARCHAR(2083)  NOT NULL,
    [userLanguage]  VARCHAR(63)     NOT NULL,
    [regTime]       DATE            NOT NULL,
    [hash]          VARCHAR(255)    NOT NULL
);

The specific part I have problems with is NVARCHAR.
I have the following C# code:
UsersDataContext context = new UsersDataContext();
User u = new User() {
    userName = name,
    userEmail = email,
    userComment = story,
    userLanguage = lang,
    hash = hash,
    regTime = System.DateTime.Now
};
context.Users.InsertOnSubmit(u);
context.SubmitChanges();

The problem is that the row inserted into DB looks like this:
????    dbogatov@wpi.edu    ???

Russian (cyrillic) symbols are displaying as ???.
Any ideas how to make DataContext insert proper NVARCHAR?
Any help is appreciated.

A: I solved it! Shame on me for such a stupid mistake.
I turns out that I did not update my .DBML file when I changed my db SCHEME to support NVARCHAR. So Entity Framework still treated my text as VARCHAR.
When I updated it, everything worked.

A: Try adding character encoding "Charset=utf8" in your database connection string. Should look like below:
<add name="MyEntities" connectionString="metadata=res://*/Metadata;provider=Your Provide;provider connection string="server=ServerIP;User Id=UID;password=PASS;Persist Security Info=True;database=DB Name; Charset=utf8"" providerName="Provider Name" /></connectionStrings>

Should work in your case.

A: check the Collation of the Database by setting it to the proper value
take a look at this
i expect that this collation is what you need Latin1_General_CI_AI


text:
Q: Combinatorics, find all 10 length arrays of positive integers whose sum is equal to 100 At the beginning, I was trying to solve (apparently) another problem but it led me to this one.
"Find all 10 length arrays of non-negative integers whose sum is equal to 100."

Here are some examples:
10 - 35 - 0 - 0 - 0 - 55 - 0 - 0 - 0 - 0
1  - 2 - 3 - 96 - 0 - 0 - 0 - 0 - 0 - 0
12 - 0 - 12 - 26 - 0 - 1 - 1 - 38 - 10 - 0
...
Firstly, I tried to write a little program but it takes hours (it is 10 for-loop in a word). So I asked myself, if there were a better algorithm or even better a mathematical formula to do so?
Good luck and thank you.
PS: Of course, you can make the problem more general by changing "10" and "100" to "k" and "n" variables.

A: All the part of the arrays have as generating function $1+x+x^2+x^3+...=\frac{1}{1-x}$. So the total generating function is $(\frac{1}{1-x})^{k+1}=\frac{1}{(1-x)^{k+1}}$. Then notice $k$-th derivative of $\frac{1}{1-x}$ equals $k!\frac{1}{(1-x)^{k+1}}
$. Therefor $\frac{1}{k!}\left(\frac{1}{1-x}\right)^\text{k-th derivative}=\frac{1}{(1-x)^{k+1}}$
On the other hand the $k$-th derivative is also $k!+(k+1)!x+\frac{(k+2)!}{2!}x^2+...+\frac{(k+n)!}{n!}x^n+....$ So we get that $\frac{1}{(1-x)^{k+1}}=\sum_{n=0}^{\infty}{n+k\choose k}x^n$. We can see the coefficient in front of $x^{n}$ is ${n+k\choose k}$


text:
Q: Flutter & Firebase, passwordless email auth? I noticed that Firebase added passwordless email auth. I haven't been able to find a method in firebase_auth to do this. Is there a way to use passwordless email with firebase_auth today?
Cheers
https://firebase.google.com/docs/auth/web/email-link-auth

A: No not really, you can either wait for the team to update the plugin, or create your own implementation and write the respective hooks for android and iOS.
https://github.com/flutter/plugins/tree/master/packages/firebase_auth

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!


text:
Q: Multi-threading Julia shows error with enumerate iterator Why does this very simple code result in an error in Julia 1.1?
Threads.@threads for (index,value) in enumerate([0.1,0.2,0.3])
    println(value^index)

end

The error shown is:
Error thrown in threaded loop on thread 0: MethodError(f=typeof(Base.unsafe_getindex)(), args=(Base.Iterators.Enumerate{Array{Float64, 1}}(itr=Array{Float64, (3,)}[0.1, 0.2, 0.3]), 1), world=0x00000000000069dc)
Error thrown in threaded loop on thread 1: MethodError(f=typeof(Base.unsafe_getindex)(), args=(Base.Iterators.Enumerate{Array{Float64, 1}}(itr=Array{Float64, (3,)}[0.1, 0.2, 0.3]), 3), world=0x00000000000069dc)

I want to use Threads.@threads with more complicated codes where I use the enumerate iterator.

A: The Threads.@threads marco expects an array to iterate over only. Here you have a link to a topic on Discourse on it.
So currently you have to iterate over indices only using e.g. axes or e.g. collect eachindex (which is not ideal).
So in your case this would be:
vec = [0.1,0.2,0.3]
Threads.@threads for index in axes(vec, 1)
    println(vec[index]^index)
end

or
Threads.@threads for (index,value) in collect(enumerate([0.1,0.2,0.3]))
    println(value^index)
end


text:
Q: Finding the square root Newton Raphson convergence proof Upon a time, I found a formula that converged to the square root of a certain number $x $.
Where the square root  of the number you want to find is $x $, $\sqrt x $, $$a_{n+1}=\frac{\frac{x}{a_n}+a_n}{2}$$ for any $a_0$.
For example, you want to calculate $\sqrt 2$, then you would use the formula $$a_{n+1}=\frac{\frac{2}{a_n}+a_n}{2}$$ where $a_0$ is the unit guess (in this case probably $1.5$) and $\sqrt x = a_\infty $
How does this work?

A: This is a specific example of Newton's method. I believe the Babylonians also used this.
I'll provide more details when I am at a computer.

A: For a simple proof see robjohn's Proof of Convergence: Babylonian Method
(uses opposite notation than yours, with $x$ and $a$ reversed)
I want to present how the Babylonian method might be 'discovered', leading into robjohn's proof. Here we do not assume the existence of real numbers, only the rational numbers. We will also flip your notation.
You know that taking the multiplicative inverse of a positive number, not equal to one,  gives you a number that is kind of 'folded over' into one of two disjoint intervals:
$(0, 1)$ or $(1, +\infty)$
And of course $1$ is right in the 'center' and is its own inverse.
As you think about the number pairs $x$ and $x^{-1}$, you wonder if taking the average will 'get you' to $1$. So you examine the function $f(x) = .5\; (x^{-1}+x)$ and start plugging in numbers. You are not surprised to  see that $f(x) \ge 1\;$ -you are taking a number from an interval of infinite length and averaging it with a number from an interval of length $1$. You learn that if you iterate $f$ starting with any point you'll converge to $1$ from the right.
Now you wonder it you can make this more interesting by 'nudging' the number that is less than $1$ on each $f$ iteration, but with everything working the same, i.e. convergence to a number from the right. So you perturb your function,  redefining it as
$f(x) = .5\; (a x^{-1}+x)$
So, if this works as before, you want a $k>0$ such that for all $x>0$,
$f(x) \ge k$
Solving by setting the discriminant of a quadratic equation to zero, you'll see that the inequality will be true iff $k^2 = a$.
So we have,
(1) ${f(x)}^2 \ge a$
But this is all you need in the (1) inequality of the nice proof mentioned at the top; you can proceed from that point with the @robjohn demonstration.

SUMMARY: If you ever forget the Babylonian Method, you can get it back
  by remembering your $(x^{-1}+x)\;$ 'game' and then the 'nudge'.
We assume that you can't possibly forget the quadratic formula and some simple
  facts about graphs of parabolas and taking limits.

A: I find it easy to see why it works thinking about attractive fixed points. The sequence corresponds to iterating the function
$$
y = \frac{x}{2z}+\frac{z}{2}
$$
and finding its fixed points means finding the intersections with
$$ y=z $$
So, solving for $z$:
$$
z = \frac{x}{2z}+\frac{z}{2}\\
\frac{z}{2} = \frac{x}{2z}\\
z^2=x\\
z=\pm\sqrt x
$$
If you choose a positive starting point, you'll land on the positive attractor. The closer your initial guess, the fewer steps you need to reach the target approximation level.
Here an example, with $x=3$ and a not-so-good initial guess:

A: Another way:
Since
$a_{n+1}=\frac{\frac{x}{a_n}+a_n}{2}
$,
$\begin{array}\\
a_{n+1}-\sqrt{x}
&=\frac{\frac{x}{a_n}+a_n}{2}-\sqrt{x}\\
&=\frac{\frac{x}{a_n}-2\sqrt{x}+a_n}{2}\\
&=\frac{x-2a_n\sqrt{x}+a_n^2}{2a_n}\\
&=\frac{(\sqrt{x}-a_n)^2}{2a_n}\\
\text{so that}\\
\frac{a_{n+1}-\sqrt{x}}{\sqrt{x}-a_n}
&=\frac{\sqrt{x}-a_n}{2a_n}\\
\end{array}
$
Therefore
once
$|\sqrt{x}-a_n|
\lt a_n
$,
the iteration will converge.

A: Consider the fraction $θ_n=\frac{a_n-\sqrt{x}}{a_n+\sqrt{x}}$, $a_n=\frac{1+θ_n}{1-θ_n}\sqrt{x}$. Then it is easy to show $θ_{n+1}=θ_n^2$ and so $θ_n=θ_0^{2^n}$. As $|θ_0|<1$ for all positive $a_0$, you get quadratic convergence from everywhere, which translates into convergence in $a_n$ at the same speed.

A: I believe I have found the answer:
If you have a terms $a_n,a_{n+1},a_{n+2}$, as '$n$' goes higher, it may converge towards a certain number. You are heading for $a_n$ equal to $a_m$, where the $m-n$ is as big as possible.
So, lets say that: $$a_n=a_{n+1}=z$$ so that you have $$z=\frac{\frac{x}{z}+z}{2}$$ $$2z=\frac{x}{z}+z$$ $$z=\frac{x}{z}$$ $$z^2=x$$


text:
Q: Decoding delay in vlc player client when transmitting RTP + h264 packet I developed an rtsp server to communicate with the vlc client.
The role of the server is as follows:
Connect the vlc client to the rtsp session.
It is to get the h264 payload from a specific pcap file and send it to the client with an rtp header.
It is well implemented, but there is one problem.
This means that the rtsp session must be terminated (TEARDOWN), but the decoding is initiated.
I hope to see the video in real time.
I want you to suggest a wise solution.
Attempted to raise the cache of the vlc client (30000ms)
The problem is still not solved, but I feel that the quality of the decoded image has improved.
I hope for a solution for real-time image decoding.

A: I solved the problem.
Turns out to be a timestamp issue in rtp packets.
When I sent the packet, I sent it as a realtime, but the interval was too short and the decoding was delayed.
When sending a packet, the problem is solved by forcing a suitable interval.


text:
Q: SystemJS import "base script" from directory, like in Python Is it possible to import a "base script" from a module-like directory with SystemJS, like a Python's __init__.py?
Example:
Directory structure
app/
  module1/
    __init__.js       // or module1.js
    module1.weeble.js
    module1.thingy.js
  module2/
    __init__.js       // or module2.js
    module2.weeble.js
    module2.thingy.js
  bootstrap.js

module1/__init__.js
import Weeble from "./module1.weeble"
import Thingy from "./module1.thingy"

class Module1 {
  constructor() {
    this.weeble = new Weeble();
    this.thingy = new Thingy();
  }
}

export default Module1

bootstrap.js
Import directory to import the base script (__init__.js or module1.js) or something:
import Module1 from "./module1"
import Module2 from "./module2"

let module1 = new Module1();
let module2 = new Module2();

// INSTEAD OF
// import Module1 from "./module1/__init__"
// OR
// import Module1 from "./module1/module1"

Is this possible? Python imports a directory as a module if __init__.py is present in that directory
# so one doesn't have to type
from module/__init__.py import module_part

# but only
from module import module_part

# or to import the entire module
import module

A: Yup it's possible. Use a index.js file for that:
module1/index.js
Then you can import "./module1";

A: JavaScript itself isn't a module-based language language (not yet). In order to do this you will need to include another library like RequireJS


text:
Q: Vuejs build/render component inside a method and output into template I have a string (example, because it's an object with many key/values, want to loop and append to htmloutput) with a component name. Is it possible to render/build the component inside a method and display the html output?
Is that possible and how can i achieve that?
     <template>

     </template>

A: You might be looking for dynamic components:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html
Example:
<template>
    <component :is="changeableComponent">
    </component>
</template>

A: Yes you can use the render function for that here is an example :

Vue.component('CompnentTest', {
  data() {
    return {
      text: 'some text inside the header'
    }
  },
  render(createElement) {
    return createElement('h1', this.text)
  }
})

new Vue({
  el: '#app',

})

  <Compnent-test />

Or :
if you are using Vue-cli :
on your componentTest component :
export default {
  render(createElement) {
    return createElement('h1', 'sometext')
  }
  // Same as
  // <template>
  //
sometext

  // </template>
  //
}

and on your root element (App.vue as default) :
export default {
   ....
  component: {
    ComponentTest
  }
}

<template>

      ....
     <Component-test />

</template>

example  : codesandbox
you can read more about
Render Functions & JSX

A: Maybe this will help - https://forum.vuejs.org/t/how-can-i-get-rendered-html-code-of-vue-component/19421
StarRating is a sample Vue component. You can get it HTML code by run:
new Vue({
  ...StarRating,
  parent: this,
  propsData: { /* pass props here*/ }
}).$mount().$el.outerHTML

in Your method. Remember about import Vue from 'vue'; and of course import component.

A: What you're trying to do really isn't best practice for Vue.
It's better to use v-if and v-for to conditionally render your component in the <template> section.


text:
Q: When can we omit the preposition "of" in such cases? I'm struggling to understand when we can omit the preposition "of" in cases when we use determiners in English (distributives and quantifiers).
I mean we all know that both "half the students were absent" and "half of the students were absent" are correct as well as "all my friends are there" and "all of my friends are there".
I would like to know the rule - when can we or can't we omit the "of"?
Scrolling through various examples online I've noticed that even with "all" and "half" it doesn't always apply and sometimes we can use it with other determiners and other times - not:

*

*Both of the cars were stolen. (can we omit "of"?)

*Half of every apple on the table was bitten. (can we omit "of"?)

*All of it was a lie. (can we omit "of"?)

*Several of my books were printed in Canada. (can we omit "of"?)

*Most of the people living in our town are teenagers. (can we omit "of"?)

A:
All of the cars were stolen.
Both of the cars were stolen.
Half of the  cars were stolen.
Several of the cars were stolen.
Some of the cars were stolen.
Few of the cars were stolen.
Most of the cars were stolen.
Many of the cars were stolen.

Or this:

All cars were stolen.
All the cars were stolen.
Both cars were stolen.
Both the cars were stolen.
Half cars were stolen.no
Half the cars were stolen.ok
Several the cars were stolen. no
Several cars were stolen.
Some the cars were stolen. no
Some cars where stolen.
Few the cars were stolen. no
Few cars were stolen.
Most the cars were stolen. no
Most cars were stolen.
Many the cars were stolen. no
Many cars were stolen.

{Several, some, few, most, many} do not accept another determiner. They must be used alone with the noun, or in a partitive construction with of.

A: There are no hard and fast rules which would apply in all situations. In English generally, many rules have exceptions, which often makes them practically useless as rules.  Anyway, I can answer the rest of your question.
Both of the cars were stolen. (can we omit "of"?)
Yes, you could say "Both the cars were stolen." or "Both cars were stolen"
Half of every apple on the table was bitten. (can we omit "of"?)
Yes, but I'd say this is acceptable in colloquial English - but not everyone will agree, and according to some here it's rather controversial. Better to leave the "of" in there.
All of it was a lie. (can we omit "of"?)
- No, but you could say "Everything was a lie."  I suppose you could say "All was a lie" but it sounds a bit archaic/literary, although it might be OK in a poem. The "it" can't remain however.
Several of my books were printed in Canada. (can we omit "of"?)
No, but you could say "Several books were printed in Canada", but then if you do that, you can't put "my" in there.
Most of the people living in our town are teenagers. (can we omit "of"?)
No, but if you also omit "the", then you can say "Most people living in our town are teenagers"

A: The omission of "of" when used as in your question is slang, so it's unlikely to make much sense. I'm going to try to make up some rules anyway. Please tear them down; if they're too wrong I'll improve them.

The meaning numbers below (e.g. 1.4) are referencing Wiktionary.
If the meaning is 1.3, 1.4, 2.1, 2.2, 2.3 (where it would change the meaning), 3.1 (where it might change the meaning), 3.2, 3.3 (where it might change the meaning), all of 4, all of 5 (especially 5.5, where its omission can cause any following indefinite article ("a" / "an") to mean "each" or "per"), all of 6, 7.2, 7.4, 8.2, 10.2 (you can't really... but it'd be interesting to see if the "exceptions" have a rule-like pattern)
Rule-like assertions:
If the meaning is 7.1, like in your question, you can omit "of" if:

*

*(colloquial) The word following "of" is an article and the word preceding "of" is an indefinite pronoun in this list:

*

*both

*all

*half

*there are probably more...

*The noun following the article is plural and you remove the article.

If the meaning is 8.1, 8.3 or 9.1, you can omit "of" if:

*

*You reverse the two noun phrases either side of "of" and it remains grammatically correct.

If the meaning is 10.1, you can omit "of" if:

*

*You convert the second noun to its adjectival form (e.g. "body" → "bodied," "leg" → "legged") and put a hyphen ("-") in between.

If the meaning is 10.3, you can omit "of" if:

*

*You remove the noun phrase preceding "of" (e.g. "at a speed of 40 m/s" → "at 40 m/s").
CAVEATS:

*

*This removes information.

*This can be confused with 8.3 (e.g. "at the speed of sound").

You can always remove it without changing anything else if the meaning is:

*

*7.3

Conclusions:

*

*There are no complete rules about that can be described using English itself.

*English is horrible. What were we thinking?!

A: The general rule is actually simple. If you strike of, the noun in the prepositional phrase becomes the sentence noun and the old noun becomes an adjective. So the rule is when the original subject noun can convert to an adjective.


text:
Q: Moving the position of a caret? Basically what I'm trying to do is move this caret up and I wouldn't even know where to start, so here's a picture of what I'm trying to move up. (the caret is the little down arrow just in case you didn't know).

Sorry about the title of this question, it's not very clear but I didn't know what else to call it...
Here's the CSS for the caret in bootstrap
.caret {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 2px;
  vertical-align: middle;
  border-top: 4px solid;
  border-right: 4px solid transparent;
  border-left: 4px solid transparent;
}

A: I changed the the vertical align which is seen in the code. Instead of
vertical-align: middle;

I used
vertical-align: super;

which raised it up to the height of the text.


text:
Q: looking for a way to save a Task List items to either the device or a database in Flutter I created a task list where you can add tasks and then long press them to delete the item
there maybe some confusion since i deleted some irrelevant pages from the app to the question asked
so if any error pops up i can help you with it
i wanna save the list that i created either locally on my phone or through a database(Mango db)
and thanks for the help
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';

void main() => runApp(new TodoApp());

class TodoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Todo List',
      home: new TodoList(),

      debugShowCheckedModeBanner: false,
    );
  }
}

class TodoList extends StatefulWidget {

  @override
  createState() => new TodoListState();
}

class TodoListState extends State<TodoList> {
  List<String> _todoItems = [];
  int _counter;
  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

  }
  void _addTodoItem(String task) {
    if(task.length > 0) {

      setState(() => _todoItems.add(task));
    }
  }

  void _removeTodoItem(int index) {
    setState(() => _todoItems.removeAt(index));
  }

  void _promptRemoveTodoItem(int index) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text('Mark "${_todoItems[index]}" as done?'),
          actions: <Widget>[
            new FlatButton(
              child: new Text('CANCEL'),
          onPressed: () => Navigator.of(context).pop()
        ),
        new FlatButton(
          child: new Text('MARK AS DONE'),
          onPressed: () {
            _removeTodoItem(index);
            Navigator.of(context).pop();
              }
            )
          ]
        );
      }
    );
  }

  Widget _buildTodoList() {
    return new ListView.builder(
      itemBuilder: (context, index) {

        if(index < _todoItems.length) {
          return _buildTodoItem(_todoItems[index], index);
        }
      },
    );
  }

  Widget _buildTodoItem(String todoText, int index) {
    return new ListTile(
      title: new Text(todoText),
      onLongPress: () => _promptRemoveTodoItem(index)
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Test List')
      ),
      drawer: Drawer(
        child: ListView(
      padding: EdgeInsets.zero,

      children:  <Widget>[
     Container(
       height: 88,

       child: DrawerHeader(
      decoration: BoxDecoration(
        color: Colors.blue,

      ),

        child: Text(
        'options',
        style: TextStyle(
          color: Colors.black,
          fontSize: 28,
        ),
        textAlign: TextAlign.center,

      ),

    ),
    ),

    ListTile(
      leading: Icon(Icons.message),
      title: Text('inbox'),
      subtitle: Text('A sub test'),

    ),
    ListTile(
      leading: Icon(Icons.account_circle),
      title: Text('tasks'),
      subtitle: Text('A sub test'),

    ),
    ListTile(
      leading: Icon(Icons.settings),
      title: Text('Settings'),
      subtitle: Text('A sub test'),

    ),
  ],
),
  ),
      body: _buildTodoList(),
      floatingActionButton: new FloatingActionButton(
        onPressed: _pushAddTodoScreen,
        tooltip: 'Add task',
        child: new Icon(Icons.add)
      ),
    );
  }

  void _pushAddTodoScreen() {

Navigator.of(context).push(

  new MaterialPageRoute(
    builder: (context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('Add a new task')
        ),
        body:  TextField(
          autofocus: true,

          onSubmitted: (val) {
            _addTodoItem(val);
            Navigator.pop(context); // Close the add todo screen
          },
          decoration: new InputDecoration(
            hintText: 'Enter something to do...',
            contentPadding: const EdgeInsets.all(16.0)
          ),
        )

      );
    }
      )
    );
  }
}

class ThirdPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new ThirdPageState();
  }
}

class ThirdPageState extends State<ThirdPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("New Task"),
        actions: <Widget>[
          new IconButton(icon: const Icon(Icons.save), onPressed: () {

          })
        ],
      ),
      body: new Column(
        children: <Widget>[
          new ListTile(
            leading: const Icon(Icons.person),
            title: new TextField(
              decoration: new InputDecoration(
                hintText: "Task Name",
                contentPadding: const EdgeInsets.all(15.0),
              ),
            ),
          ),
      new ListTile(
        leading: const Icon(Icons.person),
        title: new TextField(
          decoration: new InputDecoration(
              hintText: "Responsable",
              contentPadding: const EdgeInsets.all(15.0)),
          keyboardType: TextInputType.phone,
          maxLength: 10,
        ),
      ),
      new ListTile(
        leading: const Icon(Icons.email),
        title: new TextField(
          decoration: new InputDecoration(
            hintText: "GroupName",
            contentPadding: const EdgeInsets.all(15.0),
          ),
        ),
      ),
        new ListTile(
          leading: const Icon(Icons.email),
          title: new TextField(
            decoration: new InputDecoration(
              hintText: "Project",
              contentPadding: const EdgeInsets.all(15.0),
            ),
          ),
        ),

      ],
    ),
  );
}

}


text:
Q: ways to detect data redundancy between tables with different structures I'm working on a problem that involves multiple database instances, each with different table structures. The problem is, between these tables, there are lots and lots of duplicates, and i need a way to efficiently find them, report them, and possibly eliminate them.
Eg. I have two tables, the first table, CustomerData with the fields:
_countId, customerFID, customerName, customerAddress, _someRandomFlags

and I have another table, CustomerData2 (built later) with the fields:
_countId, customerFID, customerFirstName, customerLocation, _someOtherRandomFlags.

Between the two tables above, I know for a fact that customerName and customerFirstName were used to store the same data, and similarly customerLocation and customerAddress were also used to store the same data.
Lets say, some of the sales team have been using customerData, and others have been using customerData2. I'd like to have  a scalable way of detecting the redundancies between the tables and report them. It can be assumed with some amount of surety that customerFID in both tables are consistent, and refer to the same customer.
One solution I could think off was, to create a  customerData class in python, map the records in the two tables to this class, and compute a hash/signature for the objects within the class that are required (customerName, customerLocation/Address) and store them to a signature table, which has the columns:
sourceTableName, entityType (customerData), identifyingKey (customerFID), signature

and then for each entityType, I look for duplicate signatures for each customerFID
In reality, I'm working with huge sets of biomedical data, with lots and lots of columns. They were created at different people (and sadly with no standard nomenclature or structure) and have been duplicate data stored in them
EDIT:
For simplicity sake, I can move all the database instances to a single server instance.

A: If I couldn't care for performance, I'd use a high-level practical approach. Use Django (or SQLAlchemy or...) to build your desired models (your tables) and fetch the data to compare. Then use an algorithm for efficiently identifying duplicates (...from lists or dicts,it depends of "how" you hold your data). To boost performance you may try to "enhance" your app with the multiprocessing module or consider a map-reduce solution.


text:
Q: Webforms Upload de múltiplos arquivos Tenho uma aplicação WebForms que precisa receber múltiplos arquivos que estarão associados com um tipo específico do meu sistema.
Ex:
Tipo: [Carteira de motorista] | Arquivo: img001.png
Tipo: [Comprovante de residência] | Arquivo: comp001.pdf
Preciso receber essas informações em uma página WebForm .aspx.
Se fosse só para pegar os arquivos, podeira pegar usando o Request.Files, porém preciso saber o Tipo do documento para poder salvar no banco.
Imaginei em fazer algo do como utilizar o nome dos campos de arquivos como um array utilizando arquivos[0], arquivos[1] e associar com o de tipos (tipos[0], tipos[1]). Fazendo assim poderia utilizar os index que eu poderia garantir que o tipo seria relacionado ao arquivo. Porém não sei como acessar essas informações na páginas .aspx.
Com MVC consigo fazer isso de boa, mas como não tenho o domínio com o WebForms acabo me batendo um pouco com isso.
Como eu poderia fazer isso de uma forma sem "Gambiarras"?

A: Basta user múltiplos componentes do tipo asp:FileUpload e acessá-los usando seus respectivos nome no evento desejado seguindo o exemplo abaixo;
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="false"/>
<asp:FileUpload ID="FileUpload2" runat="server" AllowMultiple="false"/>

protected void btnUpload_Click(object sender, EventArgs e)
{
    if(FileUpload1.HasFile)
    {
        var file1info = FileUpload1.FileName + " - " + FileUpload1.PostedFile.ContentLength + " Bytes.";
        //logica para salvar
    }

    if(FileUpload2.HasFile)
    {
        var file2info = FileUpload2.FileName + " - " + FileUpload2.PostedFile.ContentLength + " Bytes.";
        //logica para salvar
    }
}

A: Acredito que nesse caso um Repeater seja o ideal. Com o Repeater você poderá criar vários controles (FileUpload), tem um índice de cada item e depois efetuar a validação.

*

*Criar update Panel para ter um melhor controle do conteudo e evitar refresh na página toda;

*Criar um botão de upload para validar e enviar os arquivos;

*Criar um repeater para mostrar dinamicamente os controles;

*Colocar os controle de FileUpad dentro do repeater;

*Criar um HiddenField pra aguardar o Índice do item;

*Criar trigger para o botão de upload (evitar que o arquivo inserido no FileUpload perca a informação no postback);

Segue um exemplo funcional. Espero que ajude.
Página ASPX
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:LinkButton Text="Enviar" ID="lblEnviar" OnClick="lblEnviar_Click" runat="server" />

            <asp:Repeater runat="server" ID="rpt">
                <ItemTemplate>
                    File Upload <%# Eval("TipoDocumento") %>
                    <asp:HiddenField runat="server" ID="hdnIndex" Visible="false" Value='<%# Eval("Index") %>' />
                    <asp:FileUpload runat="server" ID="fuArquivos" AllowMultiple="false" />
                </ItemTemplate>
            </asp:Repeater>

        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="lblEnviar" />
        </Triggers>
    </asp:UpdatePanel>

    <asp:Literal ID="ltlResultado" runat="server" />

Arquivo ASPX.CS
       //Objeto para fazer o transporte das informações
    public class DTO
    {
        public int Index { get; set; } //armazenar a posicao
        public string TipoDocumento { get; set; } //Descritivo do tipo do documento
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        //Simula uma chamada ao banco e carrega uma lista com os tipos necessários a serem enviados
        List<DTO> lst = new List<DTO>();

        lst.Add(new DTO() { Index = 0, TipoDocumento = "CNH" });
        lst.Add(new DTO() { Index = 1, TipoDocumento = "CPF" });

        //Popula o Repeater
        rpt.DataSource = lst;
        rpt.DataBind();
    }

    protected void lblEnviar_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        //verifica cada linha gerada no repeater
        foreach (RepeaterItem item in rpt.Items)
        {
            //Procurar o controle FileUpload
            FileUpload fuTemp = (FileUpload)item.FindControl("fuArquivos");

            //Procurar identificador
            HiddenField hdnIndex = (HiddenField)item.FindControl("hdnIndex");

            //Verifica se tem arquivo
            if (fuTemp.HasFile)
            {
                string s = String.Format("O arquivo na posição {0}, tem o seguinte arquivo {1}", hdnIndex.Value, fuTemp.FileName);
                sb.Append(s);
                sb.Append("
");
            }
        }

        //Imprime o resultado em um label apenas para teste.
        ltlResultado.Text = sb.ToString();
    }


text:
Q: How many endpoint and topic need for Direct ,Group,Channel in Spring Websocket? I want to write application that make messaging between users,
Messages that send  between users is in 3 types

*

*Direct

*Channel: just send from admin

*Group

My application will save messages in RDBMS. When new message send and receiver user is online ,my app will notify to user that new message receive , I decided to write my application using Spring Websocket and Stomp .My application using spring security and and i want show online users in group and direct for each other member
my question is  know how many endpoint and broker i need ? and how can do that.
Update:
My application is similar gitter and slack , when user login  messages may receive from direct or group or channel. when i switch between users and group or channel i will unsubscribe from last and subscribe to user or group that i chat in .i dont know subscribe and unsubscribe is correct or just one subscribe for all .
is this usage correct or not?
chatSocket.subscribe("/user/exchange/direct/chat.message/{userId}", function(message) {});

chatSocket.subscribe("/topic/group/chat.message/{groupId}", function(message) {});

A: *

*For direct messages, use user destinations.

*For messages that can only be sent by admins, restrict publishing to users with that role and allow other users to subscribe (with Spring Security)

*If you want to broadcast messages, use broker destinations (or app destinations if you need to add some login)

An option to store messages could be adding a channel interceptor. Make users subscribe to an app destination when the websocket connection is established and send the stored messages sent while he was online.
This sample application could give you some hints: https://github.com/salmar/spring-websocket-chat


text:
Q: How to find vtiger customer port login code In customer port has issue, google captcha working without fill, so I haven't able to find customer portal login file

A: I recommend you to ask in the Telegram VTigerCRM support forum. There are quite a few experienced users there.


text:
Q: Media changed: please insert the disk labeled 'Debian GNU/Linux I installed Debian 7 using a USB flash drive "burned" from the first DVD ISO of the Debian installation CD/DVD.
I did a very minimal install without Debian desktop environment, Print server and Standard system utilities.
After installation and a reboot, I was presented with a console with the words Debian GNU/Linux 7 hostname tty1. I supplied the login username and password.
After I typed the command sudo apt-get install xorg, an error message popped up stating:
Media changed: please insert the disk labeled 'Debian GNU/Linux 7.4.0 _Wheezy_ - Official amd64 DVD Binary-1 20140208-13:47' in the drive and press Enter

I inserted the same USB flash drive into the same port and after waiting for a few seconds, I pressed Enter.
The same error message popped up.
I have tried the following steps on the advice of some of my colleagues:

*

*remove/delete all the entries in /etc/apt/sources.list and reboot the computer

*dmesg and fstab show that the USB thumb drive is mounted on /dev/sdb1

*sudo mount /dev/sdb1 /media/usb0

*sudo apt-cdrom -m -d /media/usb0 add
After doing the above, the following error message appears:
Using CD-ROM mount point /media/cdrom/
Identifying.......{a long string of alphanumeric characters}
Scanning disc for index files...............
Found 0 package indexes, 0 source indexes, 0 translation indexes and 0 signatures
W: Failed to mount '/dev/sr0' to '/media/cdrom/'
E: Unable to locate any package files, perhaps this is not a Debian disc or the wrong architecture

I prefer to install Xorg (60MB) and gnome-core (400MB) from the USB stick. The NGO that I am working with is in a developing country with a very basic internet access infrastructure. Internet access is very patchy and the average download speed is less than 2 Mbps.

A: I found that this problem was very similar to my own.  Debian installed from USB stick but then when I try to use apt-get install I am prompted for a CdROM.
After much fuss I found part 14.3.1 of the Debian tutorial valuable because it explains the syntax for instructing the system to look for source content in a file location.
Here's what i did:
I ensured the usb stick was mounted and I took note of its location in the filesystem.  For me that was /media/Debian 7.5 64 Copyleft FM
As su I edited sources.list so that the line with "deb cdrom" was commented-out.
Then I added a new first line of that file using the tutorial info and my usb stick file location:
deb file:/media/"Debian 7.5 64 Copyleft FM" wheezy contrib local main non-free
#deb cdrom:[Debian GNU/Linux 7.5 _Wheezy_ - Copyleft amd64 Full Monty amd64 DLBD Binary-1 20140427-09:14]/ wheezy contrib local main non-free

For newbies such as me, note the use of quotes in the URI to protect the enclosed spaces from being misunderstood. (See Nixcraft forum: Howto cd to folder name with spaces blank names (white space)
Then I ran sudo apt-get update as advised above (thx). That's all I did.
This solved my problem - I was able to run sudo apt-get install vim and I was no longer asked to insert a CD.

A: so in line with the previous answer, I just told my system to not even bother to use the cdrom as a source for updates at all.
I first had to change the file permissions of sources.list so I could change it
change to directory it was in
    cd /etc/apt

then change permissions
    chmod 666 sources.list

(read/write for owner, root, and user)
then I could open the file in text editor, and with new basic user read and write permissions, and stuck # in front of the line looking at the cdrom as a source.
    #deb file:/media/"Debian 7.5 64 Copyleft FM" wheezy contrib local main non-free

then changed permissions back to only owner and root could write as well as read, but user could not
    chmod 664 sources.list

apt-get now installs programs.
someone might tell me later there is a problem with this, but hey. it worked :)

A: Thank You so much, this was my fastest fix:
Open Terminal and :`$su
Password: mypassword
name# pluma
menu File/Open:  (browse to Filesystem root) etc/apt/sources.list
Add a # in front of the line looking at the cdrom as a source.
Menu: File/Save
Close
Open System/Administration/Synaptic Package Manager
I wanted VLC so scrolled down to Video and selected the first vlc,,, the rest is history :-)
Again Thank You

A: mount your drive on /media/cdrom, then
apt-cdrom add -m --cdrom /media/cdrom
apt-get update
apt-get install your_desired_package


text:
Q: WorkManager doesn't work in library when client calls WorkManager.initialize() I am writing an Android library that uses WorkManager. Somewhere in the code I call something like this:
val uploadTripRequest = OneTimeWorkRequest.Builder(UploadTripWorker::class.java)
    .setConstraints(someConstraints)
    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
    .build()

WorkManager.getInstance(context)
    .enqueueUniqueWork(WORKER_NAME, ExistingWorkPolicy.REPLACE, uploadTripRequest)

In my build.gradle I have: implementation 'androidx.work:work-runtime:2.2.0'
Normally, everything works perfectly. Problems come when the client app calls https://developer.android.com/reference/kotlin/androidx/work/WorkManager.html#initialize, for example:
WorkManager.initialize(context, Configuration.Builder().setWorkerFactory(myWorkerFactory).build())

When this is called, WorkManager from my library is not working as expected. doWork method is not called on my UploadTripWorker, but it is executed on the worker provided by client's myWorkerFactory.
From my perspective, the WorkManager is unusable in the library, since it is a singleton and someone can change its behaviour via initialize method. But I hope I am wrong.
Is there any way I can solve this problem? Of course, I can't say to all my clients not to use WorkManager.initialize() method.

A: WorkManager v2.1 introduced the DelegatingWorkerFactory class that can help in these cases.
It's still requires that the application developer implements it in the right way, as you said WorkManager is a singleton.
The key point is that, if an application requires a custom initialization and a custom WorkerFactory, it should use a DelegatingWorkerFactory and then add it's own WorkerFactory to it.
The key point here is that the application's WorkerFactory should check the worker class name to be sure that it's the correct one (usually injecting some parameters in the constructor). If the class name is not what it's expected by the application it can just return null and the DelegatingWorkerFactory will take care to find the correct worker class to instantiate.
Something like (in the application code):
class MyWorkerFactory(
    private val myInjectedParam: InjectedParam
) : WorkerFactory() {

    override fun createWorker(
        appContext: Context,
        workerClassName: String,
        workerParameters: WorkerParameters
    ): ListenableWorker? {

        return when (workerClassName) {
            MyWorker::class.java.name ->
                MyWorker(appContext, workerParameters, myInjectedParam)
            else ->
                // Return null, so that the base class can delegate to the default WorkerFactory.
                null
        }
    }
}

The app needs then to add this WorkerFactory to the DelegatingWorkerFactory that it has setup as custom WorkerFactory using:
private fun initializeWorkManager (myInjectedParam: MyInjectedParam): WorkManager
{
    val appContext = getApplication<MyApplication>()
    val factory = appContext.workManagerConfiguration.workerFactory
            as DelegatingWorkerFactory
    factory.addFactory(MyWorkerFactory(myInjectedParam))

    return WorkManager.getInstance(appContext)
}

While in the application class you have:
class MainApplication : Application(), Configuration.Provider {

    val delegatingWorkerFactory: DelegatingWorkerFactory

    // Setup custom configuration for WorkManager with a DelegatingWorkerFactory
    override fun getWorkManagerConfiguration(): Configuration {
        return Configuration.Builder()
            .setMinimumLoggingLevel(android.util.Log.INFO)
            .setWorkerFactory(delegatingWorkerFactory)
            .build()
    }
}

A: If you have your Worker and WorkerFactory in a library project, disabling the default initializer in library's manifest seems to do the trick. Because library will have a different package than the application, default initializer seems to get triggered, unless you disable it.
<provider android:name="androidx.work.impl.WorkManagerInitializer"
          android:authorities="<library's package>.analytics.workmanager-init"
          tools:node="remove" />

Setup that worked for me.
My App contains:

*

*Configuration/Provider

*DelegatingWorkerFactory() being set to the above Configuration

My Library contains:

*

*Worker

*WorkerFactory

*WorkRequestBuilder

*Enqueing the workrequest

But what intrigues me is this annotation in WorkerFactory source code:
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)

Not sure if this should've warned me that this method is being called from a different package.


text:
Q: Problem with setting indent of bullet items in textframe I am trying to port some existing VBA code to C#. One routine controls the indentation of bullet items, and is roughly:
indentStep = 13.5
For Each parag In shp.TextRange.Paragraphs()
    parag.Parent.Ruler.Levels(parag.IndentLevel).FirstMargin = indentStep * (parag.IndentLevel - 1)
    parag.Parent.Ruler.Levels(parag.IndentLevel).LeftMargin = indentStep * (parag.IndentLevel)
Next parag

The code works, but appears to be spooky black magic. In particular, each time a particular ruler's margins are set ALL NINE rulers margins are actually set.
But somehow the appropriate information is being set. Unfortunately, when you do the same thing in C#, the results change. The following code has no visible effect:
const float kIndentStep = 13.5f;
foreach (PowerPoint.TextRange pg in shp.TextFrame.TextRange.Paragraphs())
{
pg.Parent.Ruler.Levels[pg.IndentLevel].FirstMargin = kIndentStep * (pg.IndentLevel - 1);
pg.Parent.Ruler.LevelS[pg.IndentLevel].LeftMargin = kIndentStep * pg.IndentLevel;
}

A: This appears to be a limitation/bug when automating PowerPoint from C#. I confirm it works with VBA.
I do see an effect after the code runs: it changes the first level with each run so that, at the end, the first level has the settings that should have been assigned to the last level to be processed, but none of the other levels appear to be affected, visibly. I do see a change in the values returned during code execution, but that's all.
If the code changes only one, specific level for the text frame, it works. The problem occurs only when attempting to change multiple levels.
I tried various approaches, including late-binding (PInvoke) and putting the change in a separate procedure, but the result was always the same.
Here's my last iteration
Microsoft.Office.Interop.PowerPoint.Application pptApp = (Microsoft.Office.Interop.PowerPoint.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Powerpoint.Application"); // new Microsoft.Office.Interop.PowerPoint.Application();
//Change indent level of text
const float kIndentStep = 13.5f;
Microsoft.Office.Interop.PowerPoint.Shape shp = pptApp.ActivePresentation.Slides[2].Shapes[2];
Microsoft.Office.Interop.PowerPoint.TextFrame tf = shp.TextFrame;
object oTf = tf;
int indentLevelLast = 0;
foreach (Microsoft.Office.Interop.PowerPoint.TextRange pg in tf.TextRange.Paragraphs(-1, -1))
{
    int indentLevel = pg.IndentLevel;
    if (indentLevel > indentLevelLast)
    {
        Microsoft.Office.Interop.PowerPoint.RulerLevel rl = tf.Ruler.Levels[indentLevel];
        object oRl = rl;
        System.Diagnostics.Debug.Print(pg.Text + ": " + indentLevel + ", " + rl.FirstMargin.ToString() + ", " + rl.LeftMargin.ToString()) ;
        object fm = oRl.GetType().InvokeMember("FirstMargin", BindingFlags.SetProperty, null, oRl, new object[] {kIndentStep * (indentLevel - 1)});
        //rl.FirstMargin = kIndentStep * (indentLevel - 1);
        object lm = oRl.GetType().InvokeMember("LeftMargin", BindingFlags.SetProperty, null, oRl, new object[] { kIndentStep * (indentLevel) });
        //rl.LeftMargin = kIndentStep * indentLevel;
        indentLevelLast = indentLevel;
        System.Diagnostics.Debug.Print(pg.Text + ": " + indentLevel + ", " + tf.Ruler.Levels[indentLevel].FirstMargin.ToString() + ", " + tf.Ruler.Levels[indentLevel].LeftMargin.ToString()) ;
        rl = null;
    }
}

FWIW neither code snippet provided in the question compiles. The VBA snippet is missing .TextFrame. The C# snippet doesn't like Parent.Ruler so I had to change it to TextFrame.Ruler.


text:
Q: gevent.patch_all() and third-party libraries gevent library documentation suggests to use gevent.monkey.patch_all() function to make standard library modules cooperative.
As I understand this method only works for my code (written by me), because I can explicitly monkey-patch standard library before importing standard library modules.
What about third-party libraries (websocket client for example), which import threading, socket modules internally. Is there a way for this libraries to use patched version of threading and socket modules ?

A: Monkey patch at the earliest possible moment in your code (i.e. before any of your third party modules have been imported).
Then, when the third party modules are imported, they will use the monkey-patched versions of the standard libraries.


text:
Q: Excel VBA Using wildcard to replace string within string I have a difficult situation and so far no luck in finding a solution.
My VBA collects number figures like $80,000.50. and I'm trying to get VBA to remove the last period to make it look like $80,000.50 but without using right().
The problem is after the last period there are hidden spaces or characters which will be a whole lot of new issue to handle so I'm just looking for something like:
replace("$80,000.50.",".**.",".**")
Is this possible in VBA?

A: I cant leave a comment so....
what about InStrRev?
Private Sub this()
    Dim this As String
    this = "$80,000.50."
    this = Left(this, InStrRev(this, ".") - 1)
    Debug.Print ; this
End Sub

A: Mid + Find
You can use Mid and Find functions. Like so:

The Find will find the first dot . character. If all the values you are collecting are currency with 2 decimals, stored as text, this will work well.
The formula is: =MID(A2,1,FIND(".",A2)+2)
VBA solution
Function getStringToFirstOccurence(inputUser As String, FindWhat As String) As String
    getStringToFirstOccurence = Mid(inputUser, 1, WorksheetFunction.Find(FindWhat, inputUser) + 2)
End Function

Other possible solutions, hints
Trim + Clear + Substitute(Char(160)): Chandoo -
Untrimmable Spaces – Excel Formula
Ultimately, you can implement Regular expressions into Excel UDF: VBScript's Regular Expression Support

A: How about:
Sub dural()
    Dim r As Range
    For Each r In Selection
        s = r.Text
        l = Len(s)
        For i = l To 1 Step -1
            If Mid(s, i, 1) = "." Then
                r.Value = Mid(s, 1, i - 1) & Mid(s, i + 1)
                Exit For
            End If
        Next i
    Next r
End Sub

This will remove the last period and leave all the other characters intact.  Before:

and after:

EDIT#1:
This version does not require looping over the characters in the cell:
Sub qwerty()
    Dim r As Range

    For Each r In Selection
        If InStr(r.Value, ".") > 0 Then r.Characters(InStrRev(r.Text, "."), 1).Delete
    Next r
End Sub

A: Shortest Solution
Simply use the Val command. I assume this is meant to be a numerical figure anyway? Get rid of commas and the dollar sign, then convert to value, which will ignore the second point and any other trailing characters! Robustness not tested, but seems to work...
Dim myString as String
myString = "$80,000.50.   junk characters     "

' Remove commas and dollar signs, then convert to value.
Dim myVal as Double
myVal = Val(Replace(Replace(myString,"$",""),",",""))

' >> myVal = 80000.5

' If you're really set on getting a formatted string back, use Format:
myString = Format(myVal, "$000,000.00")

' >> myString = $80,000.50

From the Documentation,

The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized.

This is why we must first remove the dollar sign, and why it ignores all the junk after the second dot, or for that matter anything non numerical at the end!
Working with Strings
Edit: I wrote this solution first but now think the above method is more comprehensive and shorter - left here for completeness.
Trim() removes whitespace at the end of a string. Then you could simply use Left() to get rid of the last point...
' String with trailing spaces and a final dot
Dim myString as String
myString = "$80,000.50.    "

' Get rid of whitespace at end
myString = Trim(myString)

' Might as well check if there is a final dot before removing it
If Right(myString, 1) = "." Then

    myString = Left(myString, Len(myString) - 1)

End If

' >> myString = "$80,000.50"


text:
Q: HTML JavaScript CSS - Parallax Issues with outsourced code? So my issue that I have right now is that I've created an HTML page with a parallax effect with a menu that moves with the page. Creating a sort of fixed menu browsing the page.
I ran into some issues while trying to continue the project. The menu itself I believe should blur out the pictures behind it whilst it covers it, however, what I've noticed now is that my other texts & boxes shine right through the menu.
This is my project on GitHub: https://github.com/oksmantv/HTML_Page_Public/tree/master
This is the original script/code from https://codepen.io/Oksmantv/pen/PooyGyJ. It consists out of 3 parts, CSS, JavaScript & HTML. This below is the JavaScript part
var $content = $('header .content')
  , $blur    = $('header .overlay')
  , wHeight  = $(window).height();

$(window).on('resize', function(){
  wHeight = $(window).height();
});

window.requestAnimFrame = (function()
{
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

function Scroller()
{
  this.latestKnownScrollY = 0;
  this.ticking            = false;
}

Scroller.prototype = {

  init: function() {
    window.addEventListener('scroll', this.onScroll.bind(this), false);
    $blur.css('background-image',$('header:first-of-type').css('background-image'));
  },

  onScroll: function() {
    this.latestKnownScrollY = window.scrollY;
    this.requestTick();
  },

  requestTick: function() {
    if( !this.ticking ) {
      window.requestAnimFrame(this.update.bind(this));
    }
    this.ticking = true;
  },

  update: function() {
    var currentScrollY = this.latestKnownScrollY;
    this.ticking       = false;

    var slowScroll = currentScrollY / 2
      , blurScroll = currentScrollY * 2
      , opaScroll = 1.4 - currentScrollY / 400;
   if(currentScrollY > wHeight)
     $('nav').css('position','fixed');
   else
     $('nav').css('position','absolute');

    $content.css({
      'transform'         : 'translateY(' + slowScroll + 'px)',
      '-moz-transform'    : 'translateY(' + slowScroll + 'px)',
      '-webkit-transform' : 'translateY(' + slowScroll + 'px)',
      'opacity' : opaScroll
    });

    $blur.css({
      'opacity' : blurScroll / wHeight
    });
  }
};

var scroller = new Scroller();
scroller.init();

To illustrate what I'm talking about:

So here I am asking you what it is, that doesn't make this tick!


text:
Q: stdout output is not saved to list when I execute command with paramiko Before the code below, I make a ssh connection to a server and I try to get some output. Here is the code:
a = [('one','oneFC'),('two','twoH')]
b = [None] * len(a)
for i, item in enumerate(a):
    command = r"ls /home/aaa/ | grep " + item[0] #I need one and two here
    stdin, stdout, stderr = client.exec_command(command)
    print stdout.read()
    b[i] = stdout.read()
    print b[i]

When I print the output (with stdout.print()) it looks good, but when I print b[i], the variable is empty.
What am I doing wrong? Please help me
Thank you

A: You've already read everything after print stdout.read(). You should omit the first  print statement and directly assign to b[i].
a = [('one','oneFC'),('two','twoH')]
b = [None] * len(a)
for i, item in enumerate(a):
    command = r"ls /home/aaa/ | grep " + item[0] #I need one and two here
    stdin, stdout, stderr = client.exec_command(command)
    b[i] = stdout.read()
    print b[i]


text:
Q: why i cannot update details in this form sorry for disturbing all of you..but can you help me with this...because i want to complete my work...i really do appreciate that..almost half day im doing this function..but i couldnt see whats its wrong..
this is page that display all details...this page name updatepernternak.php

$idprofil = $_GET['idprofil']; $result = mysql_query("SELECT * FROM
  penternak WHERE id = '$idprofil'"); $row = mysql_fetch_array($result);
?>
  Untitled Document

  " method="post">

      ID :

        " />
      Nama :

        " />
      No I/C :

        "/>
      Alamat :

        "/>

        "/>

      Poskod :

        "/>      No
  Telefon Rumah:

        "/>
          No Telefon Bimbit:

        "/>
       E-mel:

        "/>

Nama Projek :

  <input type="text" name="nmprojek" id="nmprojek" width="539" value="<?php echo $row['nprojek']; ?>"/>

 Lokasi :

  <textarea name="lokasi" id="lokasi" width="539" col="30" row="6" ><?php echo $row['lokasi']; ?></textarea>

 Tahun Mula:

  <input type="text" name="tmula" id="tmula" width="539" value="<?php echo $row['tmula']; ?>" />

   <input type="submit" name="submit" value="Kemaskini" />  <input type="reset" />

then if i click update button i will go this page name updatepenternak1.php

?>
  Untitled Document
 <

  if($submit=="Kemaskini") {        $id = $_POST["id"];
        $nama = $_POST["nama"];         $ic = $_POST["ic"];         $lorong1 = $_POST["lorong1"];       $lorong2 = $_POST["lorong2"];       $telrumah =
  $_POST["telrumah"];       $henset = $_POST["telbimbit"];      $emel =
  $_POST["emel"];       $lokasi = $_POST["lokasi"];         $tmula =
  $_POST["tmula"];
  $sql= "UPDATE penternak SET nama ='$nama',ic='$ic', lorong1='$lorong1', lorong2='$lorong2', telrumah='$telrumah',

henset='$henset', emel='$emel', lokasi='$lokasi', tmula='$tmula',WHERE
  id = '$id'";
  $result = mysql_query($sql);        echo "BACK";        }

?>

but i dont whats wrong because i doesnt update at all...can anyone please help me with this...thank you...

A: Try this, In update query You have added extra , before WHERE clause.
 $sql= "UPDATE penternak SET nama ='$nama',ic='$ic', lorong1='$lorong1', lorong2='$lorong2', telrumah='$telrumah',
        henset='$henset', emel='$emel', lokasi='$lokasi', tmula='$tmula' WHERE id = '$id'";


text:
Q: ouput in brower differs from output in terminal char>128 python3 apache2 Trying to print euro sign in browser: Prints successfully on terminal but not on browser
Same behavior in python 2.7 and 3 : would prefer python 3.4 solution
Browsers tested fire fox and opera: url localhost/cgi-bin/test2.py
Browser shows page information with correct encoding so header must be working
Some incompatibility perhaps with decode instruction in python
Can produce Chinese characters by mixing encodings deliberately but cannot get them to match.
running usual LAMP set up; no issues using PHP
Seems to find correct binaries
Need to accept input in any language
how to isolate issue?
Could someone post correct minimalist code for python 3 for headers and print say euro sign without using html entities please? My current code below
#!/usr//bin/env python3
import cgi
#cgi.test()

import locale
import sys
import os
import io

import codecs

import cgitb
cgitb.enable() #this does not work properly either!!!

lf = chr(10)
cr  = chr(13)

h = "Content-Type: text/html; charset=utf-8 "
#h.encode("ascii")
print(h)
print(' Cache-Control: "no-cache, no-store, must-revalidate"'.encode('utf-8'))
#print(' Pragma: no-cache')
#print(' Expires: 0')
print(cr)
print(lf)

print()
print(lf)
print(cr)
print('<DOCTYPE! html>')
print('<meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=utf-8">')
print('')
hw = "Hello World!"
hw.encode('utf-8')
#hw.encode('utf-16le')
print(hw)

euro = "€"
euro.encode('utf-8')
#euro.encode('utf-16')
print(euro) #THIS PRINTS OKAY

u = chr(8364)
u=u'This string includes a \u20AC sign'
u.encode('utf-8')
#u.encode('utf-16le')
print(u) #THIS PRINTS IN TERMINAL, BUT NOT IN BROWSER AND GENERATES FATAL ERROR

end = "end"
end.encode('utf-8')
#end.encode('utf-16')
print(end)

Terminal output:
Content-Type: text/html; charset=utf-8
b' Cache-Control: "no-cache, no-store, must-revalidate"'

<DOCTYPE! html>
<meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=utf-8">

Hello World!
€
This string includes a € sign
end

Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux

A: Probably not the best solution but the following at least works:
u = chr(8364)
#u='This string includes a \u20AC sign'
u=u+'This string includes a \u673A sign'
out = ''

for ch in u:
    out = out+'&#'+str(ord(ch))+';'
print(out)

A: Python3 strings are unicode by default, but it seems that the console has to support unicode too. For example: print("€") works on the linux terminal, but not on the windows command line. Apparently Apache has a similar problem. You can try to send the bytes directly:
#!/usr/bin/python3

import sys
import cgitb
cgitb.enable()

print("Content-Type: text/html;charset=utf-8")
print()
sys.stdout.flush()
print(
    "<!DOCTYPE html>"
    ""
    "")
sys.stdout.buffer.write(bytes("€", "utf-8"))
print(
    ""
    "")

Or you could just use print("€"):
#!/usr/bin/python3

import cgitb
cgitb.enable()

print("Content-Type: text/html;charset=utf-8")
print()
print(
    "<!DOCTYPE html>"
    ""
    ""
    "€"
    ""
    "")

This is much saner.
You don't have to use the encode method like you did in your script. Of course it won't look right in the terminal, but your browser will display it correctly.
Keep in mind that you have to print an empty line to seperate the header from the rest. After that you just print regular html.