text:
Q: Rails4: Saving a model from a different controller (with a form and POST) I'm new with Ruby on Rails and this is my first question on SO, I hope someone will be able to help me.
I have a controller Main with a view home, in this view I have a form to create a new entry with a model Mail. My problem is that the entries in my DB are empty (I check with rails c, Mail.all), all the fields are set to nil (except the usuals like id). I could probably simplify my life by using a model and a controller with the same name but I'm pretty sure RoR should be able to handle this.
Model Mail:
class Mail < ActiveRecord::Base
end

Corresponding schema.rb:
ActiveRecord::Schema.define(version: 20140217160636) do

  create_table "mails", force: true do |t|
    t.string   "address"
    t.string   "type"
    t.boolean  "confirmed"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

Controller Main:
class MainController < ApplicationController

  def home
    @mail = Mail.new
  end

  def create
    @mail = Mail.new(params[:main])
    if @mail.save
      redirect_to :root
    end
  end

end

Form from _form.html.erb shown in the view home through <%= render 'main/form' %> in application.html.erb:
<%= form_for @mail do |f| %>
  <%= f.text_field :address %>
  <%= f.select :type, [['Early adopter','early_adopter'],['Investisseur','investisor'],['Journaliste','journalist']] %>
  <%= f.hidden_field :confirmed, :value => false %>
  <%= f.submit("S'inscrire") %>
<% end %>
<%= debug(params) if Rails.env.development? %>

The debug line always shows:
--- !ruby/hash:ActionController::Parameters
controller: main
action: home

Which doesn't help me much here.
Finally routes.rb:
LandingPage::Application.routes.draw do

  root 'main#home'
  resources :mails, controller: :main, :path => "/"

end

To sum up: everything almost works like a charm: the form is visible and functional, the post method re-routes to the root as wanted, a mail entry is created in the DB. My only problem is that the post info seems lost in the routing and the DB entry is empty.
In case it helps here is my install info.
Gemfile:
source 'https://rubygems.org'

gem 'rails', '4.0.2'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'

group :doc do
  gem 'sdoc', require: false
end

gem 'i18n', '~> 0.6.9'

As I'm new to RoR I hope someone will just notice something I'm missing and explain it so that I can further my RoR education. Sorry if you get confused with Main/Mail, I'll try to differentiate my names better in the future.
EDIT:
I changed every instance of mail into mail_info, mails into mail_infos and did a successful db:migrate. I have the same problem, my mail_infos entries are empty (nil fields). So it's not about the name.

A: Have u tried strong parameters? Rails does not allow all values of your Model to be saved in DB. It will allow security vulnerabilities. So, you should use strong parameters which was called attr_accessible before RoR 4.
def create
  @mail = Mail.new(mail_params)
  if @mail.save
   redirect_to :root
  end
end

private

def mail_params
 params.require(:mail).permit(:address, :type, :confirmed)
end

A: Do not use "type" name for column because it is used for single table inheritance.


text:
Q: How to get count or records returned from json_agg() query? I am dynamically building up some queries that look like this
select array_to_json(array_agg(t)) from (
select
a.field_1,
a.field_2,
jsonb_agg(distinct jsonb_build_object('id',g.id,'data',g.fullname)) as field_4,
jsonb_agg(distinct jsonb_build_object('id',i.optionid,'data',i.option)) as field_9,
jsonb_agg(distinct jsonb_build_object('id',c.id,'data',c.fullname)) as field_6,
jsonb_agg(distinct jsonb_build_object('id',k.id,'data',k.fullname)) as field_8,
jsonb_agg(distinct jsonb_build_object('id',m.id,'data',m.field_20)) as field_21,
l.field_5,
jsonb_agg(distinct jsonb_build_object('id',e.optionid,'data',e.option,'attributes',e.attributes)) as field_23,
n.data as field_13,
jsonb_agg(distinct jsonb_build_object('id',bb.id,'data',bb.fullname)) as field_12

from schema_1.tbl_342 a
left join schema_1.tbl_342_to_tbl_329_field_10 b on a.id=b.tbl_342_id
left join schema_1.tbl_329_customid c on b.tbl_329_id=c.id
left join schema_1.tbl_329 m on m.id=b.tbl_329_id
left join schema_1.tbl_329_field_23_join d on c.id=d.id
left join schema_1.tbl_329_field_23 e on d.optionid = e.optionid
left join schema_1.tbl_342_to_tbl_312_field_4 f on a.id=f.tbl_342_id
left join schema_1.tbl_312_customid g on f.tbl_312_id = g.id
left join schema_1.tbl_342_field_9_join h on h.id=a.id
left join schema_1.tbl_342_field_9 i on i.optionid=h.optionid
left join schema_1.tbl_343_to_tbl_342_field_6 j on j.tbl_342_id=a.id
left join schema_1.tbl_343_customid k on j.tbl_343_id=k.id
left join schema_1.tbl_343 l on l.id=j.tbl_343_id
left join schema_1.tbl_342_field_13_max n on n.id=a.id
group by a.field_1,a.field_2,l.field_5,m.field_23,n.data
) t

an Example of output comes back as follows
[{"field_1":"Billy","field_2":null,"field_4":[{"id": 4, "data": "Senior Javascript Engineer"}, {"id": 5, "data": "Recruiter"}],"field_9":[{"id": 1, "data": "Blue"}],"field_6":[{"id": 32, "data": "Nancy - 32"}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": 32, "data": "ggñ@cnn.com"}],"field_5":null,"field_23":[{"id": 5, "data": "Expert", "attributes": {"text": "#FFFFFF", "color": "#448AFF"}}],"field_13":"Expert"},{"field_1":"Jackson","field_2":null,"field_4":[{"id": 2, "data": "Marketing Manager M1004"}, {"id": 4, "data": "Senior Javascript Engineer"}, {"id": 5, "data": "Recruiter"}],"field_9":[{"id": 3, "data": "Red"}],"field_6":[{"id": 36, "data": ",Mike - 36"}],"field_8":[{"id": 2, "data": "Henry"}],"field_21":[{"id": 36, "data": "PtereSwanson@gmail.com"}],"field_5":"CA","field_23":[{"id": 6, "data": "Guru", "attributes": {"text": "#FFFFFF", "color": "#0D47A1"}}],"field_13":"Guru"},{"field_1":"Jacob","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": null, "data": null}],"field_6":[{"id": null, "data": null}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": null, "data": null}],"field_5":null,"field_23":[{"id": null, "data": null, "attributes": null}],"field_13":null},{"field_1":"John","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": 2, "data": "Green"}],"field_6":[{"id": 32, "data": "Nancy - 32"}, {"id": 35, "data": "Bobby - 35"}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": 32, "data": "ggñ@cnn.com"}, {"id": 35, "data": "Oliver@yahoo.com"}],"field_5":null,"field_23":[{"id": 4, "data": "Experienced", "attributes": {"text": "#FFFFFF", "color": "#C79702"}}, {"id": 5, "data": "Expert", "attributes": {"text": "#FFFFFF", "color": "#448AFF"}}],"field_13":"Expert"},{"field_1":"Todd","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": 4, "data": "Yellow"}],"field_6":[{"id": 1, "data": "Bobbie - 1"}, {"id": 4, "data": "bobby - 4"}],"field_8":[{"id": 1, "data": "Please stand up"}],"field_21":[{"id": 1, "data": "paul@sonos.com"}, {"id": 4, "data": "ggñ@cnn.com"}],"field_5":"MA","field_23":[{"id": 2, "data": "Novice", "attributes": {"text": "#000000", "color": "#FFEB3B"}}, {"id": 3, "data": "Intermediate", "attributes": {"text": "#000000", "color": "#F5F5F5"}}],"field_13":"Intermediate"}]

Here is output I want to get.
{count: 5, data:[{"field_1":"Billy","field_2":null,"field_4":[{"id": 4, "data": "Senior Javascript Engineer"}, {"id": 5, "data": "Recruiter"}],"field_9":[{"id": 1, "data": "Blue"}],"field_6":[{"id": 32, "data": "Nancy - 32"}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": 32, "data": "ggñ@cnn.com"}],"field_5":null,"field_23":[{"id": 5, "data": "Expert", "attributes": {"text": "#FFFFFF", "color": "#448AFF"}}],"field_13":"Expert"},{"field_1":"Jackson","field_2":null,"field_4":[{"id": 2, "data": "Marketing Manager M1004"}, {"id": 4, "data": "Senior Javascript Engineer"}, {"id": 5, "data": "Recruiter"}],"field_9":[{"id": 3, "data": "Red"}],"field_6":[{"id": 36, "data": ",Mike - 36"}],"field_8":[{"id": 2, "data": "Henry"}],"field_21":[{"id": 36, "data": "PtereSwanson@gmail.com"}],"field_5":"CA","field_23":[{"id": 6, "data": "Guru", "attributes": {"text": "#FFFFFF", "color": "#0D47A1"}}],"field_13":"Guru"},{"field_1":"Jacob","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": null, "data": null}],"field_6":[{"id": null, "data": null}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": null, "data": null}],"field_5":null,"field_23":[{"id": null, "data": null, "attributes": null}],"field_13":null},{"field_1":"John","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": 2, "data": "Green"}],"field_6":[{"id": 32, "data": "Nancy - 32"}, {"id": 35, "data": "Bobby - 35"}],"field_8":[{"id": null, "data": null}],"field_21":[{"id": 32, "data": "ggñ@cnn.com"}, {"id": 35, "data": "Oliver@yahoo.com"}],"field_5":null,"field_23":[{"id": 4, "data": "Experienced", "attributes": {"text": "#FFFFFF", "color": "#C79702"}}, {"id": 5, "data": "Expert", "attributes": {"text": "#FFFFFF", "color": "#448AFF"}}],"field_13":"Expert"},{"field_1":"Todd","field_2":null,"field_4":[{"id": null, "data": null}],"field_9":[{"id": 4, "data": "Yellow"}],"field_6":[{"id": 1, "data": "Bobbie - 1"}, {"id": 4, "data": "bobby - 4"}],"field_8":[{"id": 1, "data": "Please stand up"}],"field_21":[{"id": 1, "data": "paul@sonos.com"}, {"id": 4, "data": "ggñ@cnn.com"}],"field_5":"MA","field_23":[{"id": 2, "data": "Novice", "attributes": {"text": "#000000", "color": "#FFEB3B"}}, {"id": 3, "data": "Intermediate", "attributes": {"text": "#000000", "color": "#F5F5F5"}}],"field_13":"Intermediate"}]}

I'd like to have the total records returned in a top level attribute, separate from the data results.
How would I do that, I tried adding count(a.id) which is the base table, but it doesn't return total records.

A: Use json_array_length as your final out put is in JSON Array format.
select jsonb_build_object('count',json_array_length(data),'data',data) from (
select array_to_json(array_agg(t)) data from (
select
a.field_1,
a.field_2,
jsonb_agg(distinct jsonb_build_object('id',g.id,'data',g.fullname)) as field_4,
jsonb_agg(distinct jsonb_build_object('id',i.optionid,'data',i.option)) as field_9,
jsonb_agg(distinct jsonb_build_object('id',c.id,'data',c.fullname)) as field_6,
jsonb_agg(distinct jsonb_build_object('id',k.id,'data',k.fullname)) as field_8,
jsonb_agg(distinct jsonb_build_object('id',m.id,'data',m.field_20)) as field_21,
l.field_5,
jsonb_agg(distinct jsonb_build_object('id',e.optionid,'data',e.option,'attributes',e.attributes)) as field_23,
n.data as field_13,
jsonb_agg(distinct jsonb_build_object('id',bb.id,'data',bb.fullname)) as field_12

from schema_1.tbl_342 a
left join schema_1.tbl_342_to_tbl_329_field_10 b on a.id=b.tbl_342_id
left join schema_1.tbl_329_customid c on b.tbl_329_id=c.id
left join schema_1.tbl_329 m on m.id=b.tbl_329_id
left join schema_1.tbl_329_field_23_join d on c.id=d.id
left join schema_1.tbl_329_field_23 e on d.optionid = e.optionid
left join schema_1.tbl_342_to_tbl_312_field_4 f on a.id=f.tbl_342_id
left join schema_1.tbl_312_customid g on f.tbl_312_id = g.id
left join schema_1.tbl_342_field_9_join h on h.id=a.id
left join schema_1.tbl_342_field_9 i on i.optionid=h.optionid
left join schema_1.tbl_343_to_tbl_342_field_6 j on j.tbl_342_id=a.id
left join schema_1.tbl_343_customid k on j.tbl_343_id=k.id
left join schema_1.tbl_343 l on l.id=j.tbl_343_id
left join schema_1.tbl_342_field_13_max n on n.id=a.id
group by a.field_1,a.field_2,l.field_5,m.field_23,n.data
) t)x

It will give you the desired output
UPDATE as per comment
with cte as (
select
a.field_1,
a.field_2,
jsonb_agg(distinct jsonb_build_object('id',g.id,'data',g.fullname)) as field_4,
jsonb_agg(distinct jsonb_build_object('id',i.optionid,'data',i.option)) as field_9,
jsonb_agg(distinct jsonb_build_object('id',c.id,'data',c.fullname)) as field_6,
jsonb_agg(distinct jsonb_build_object('id',k.id,'data',k.fullname)) as field_8,
jsonb_agg(distinct jsonb_build_object('id',m.id,'data',m.field_20)) as field_21,
l.field_5,
jsonb_agg(distinct jsonb_build_object('id',e.optionid,'data',e.option,'attributes',e.attributes)) as field_23,
n.data as field_13,
jsonb_agg(distinct jsonb_build_object('id',bb.id,'data',bb.fullname)) as field_12

from schema_1.tbl_342 a
left join schema_1.tbl_342_to_tbl_329_field_10 b on a.id=b.tbl_342_id
left join schema_1.tbl_329_customid c on b.tbl_329_id=c.id
left join schema_1.tbl_329 m on m.id=b.tbl_329_id
left join schema_1.tbl_329_field_23_join d on c.id=d.id
left join schema_1.tbl_329_field_23 e on d.optionid = e.optionid
left join schema_1.tbl_342_to_tbl_312_field_4 f on a.id=f.tbl_342_id
left join schema_1.tbl_312_customid g on f.tbl_312_id = g.id
left join schema_1.tbl_342_field_9_join h on h.id=a.id
left join schema_1.tbl_342_field_9 i on i.optionid=h.optionid
left join schema_1.tbl_343_to_tbl_342_field_6 j on j.tbl_342_id=a.id
left join schema_1.tbl_343_customid k on j.tbl_343_id=k.id
left join schema_1.tbl_343 l on l.id=j.tbl_343_id
left join schema_1.tbl_342_field_13_max n on n.id=a.id
group by a.field_1,a.field_2,l.field_5,m.field_23,n.data
),
cte2 as
(select count(*) as "count_" from cte)

select row_to_json(x) from (
select cte2.count_ "count", array_to_json(array_agg(t)) as data from (
select * from cte limit 3 -- you can add desired limit here
 ) t, cte2
group by 1
)x

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems displaying directions on button click using Aangular JS and the Google Maps JS API Have been trying to get a button to work on in a small app that I have been building using the Ionic Framework.
The button has a pretty simple job right now, on click show directions on the map. When the function is called within the controller it shows on the map but when I try to call it from the click, I am not able to get the directions showing.
Wondering what the issue could be here.
var directionsDisplay = new google.maps.DirectionsRenderer({
  map: $scope.map
});

$scope.show_dirs = function(){

var request = {
  destination: locations[3],
  origin: temp_center,
  travelMode: google.maps.TravelMode.DRIVING
};

var directionsService = new google.maps.DirectionsService();

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    // Display the route on the map.
    directionsDisplay.setDirections(response);
  }
});
};
//show function works
//$scope.show_dirs();

The HTML button:
    <div style= "position: absolute; bottom: -10px; width: 100%" ng-controller="MapCtrl">
      <button class="button button-block button-balanced" ng-click = "show_dirs">Find Parking Near Me</button>
    </div>

A: Your ng-click attribute is incorrect. It should be an Angular expression to evaluate and execute when the button is clicked.
What you have, show_dirs, will evaluate to the function itself. What you want instead is to actually call that function.
So it should be ng-click="show_dirs()".


text:
Q: Insert a thumbnail for PDF attachment using apache PDF-Box I have a code to attach a file to a PDF file.
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);

// read attachment file
File file = new File("/Users/TMac/Projects/Web/dir/index.html");
FileInputStream inputStream = new FileInputStream(file);

PDEmbeddedFile pdEmbeddedFile = new PDEmbeddedFile(doc, inputStream );
pdEmbeddedFile.setSubtype( "application/octet-stream" );

PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setEmbeddedFile( pdEmbeddedFile );
fs.setFile("index.html");

int offsetX = 20;
int offsetY = 600;

PDAnnotationFileAttachment txtLink = new PDAnnotationFileAttachment();
txtLink.setFile(fs);

// Set the rectangle containing the link
PDRectangle position = new PDRectangle();
position.setLowerLeftX(offsetX);
position.setLowerLeftY(offsetY);
position.setUpperRightX(offsetX + 20);
position.setUpperRightY(offsetY + 20);
txtLink.setRectangle(position);

page.getAnnotations().add(txtLink);

doc.save("/Users/TMac/Projects/PDF/outputFiles/testHTML.pdf");
doc.close();

The problem is the attachment icon is looks like this:

I need to replace this icon with custom image.I have found some examples related to text links. when i click on that image it should open the file. Attachment code (above code) working fine. How can i add a custom image as a thumbnail ?

A: You need to create an appearance stream:
PDAnnotationFileAttachment txtLink = new PDAnnotationFileAttachment();
txtLink.setFile(fs);
// Set the rectangle containing the link
int offsetX = 20;
int offsetY = 600;
PDRectangle position = new PDRectangle();
position.setLowerLeftX(offsetX);
position.setLowerLeftY(offsetY);
position.setUpperRightX(offsetX + 20);
position.setUpperRightY(offsetY + 20);
txtLink.setRectangle(position);

PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
PDAppearanceStream appearanceStream = new PDAppearanceStream(doc);
appearanceStream.setResources(new PDResources());
PDRectangle bbox = new PDRectangle(txtLink.getRectangle().getWidth(), txtLink.getRectangle().getHeight());
appearanceStream.setBBox(bbox);
try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
{
    PDImageXObject image = PDImageXObject.createFromFile("image.jpg", doc);
    cs.drawImage(image, 0, 0);
}
appearanceDictionary.setNormalAppearance(appearanceStream);
txtLink.setAppearance(appearanceDictionary);

page.getAnnotations().add(txtLink);


text:
Q: R crashed when using Geom_Point for large data frame Background: I have a large data frame data_2014, containing ~ 1,000,000 rows like this
library(tidyverse)

tibble(
date_time = "4/1/2014 0:11:00",
Lat = 40.7690,
Lon = -73.9549,
Base = "B02512"
)

Problem: I want to create a plot like this
This is what I've attempted to do:
library(tidyverse)
library(ggthemes)
library(scales)

    min_lat <- 40.5774
    max_lat <- 40.9176
    min_long <- -74.15
    max_long <- -73.7004

    ggplot(data_2014, aes(Lon, Lat)) +
      geom_point(size = 1, color = "chocolate") +
      scale_x_continuous(limits = c(min_long, max_long)) +
      scale_y_continuous(limits = c(min_lat, max_lat)) +
      theme_map() +
      ggtitle("NYC Map Based on Uber Rides Data (April-September 2014)")

However, when I ran this code, Rstudio crashed. I'm not particularly sure how to fix or improve this. Is there any suggestion?

A: A million points is a lot for ggplot2, but do-able if your computer is good enough.  Yours may or may not be. Short of getting a bigger computer here's what you should do.

*

*This is spatial data, so use the sf package.

library(sf)
data_2014 <- st_as_sf(data_2014, coords = c('Lon', 'Lat')) %>%
  st_set_crs(4326)

*If you're only plotting the points, get rid of the columns of data you don't need.  I'm guessing they might include trip distance, time, borough, etc. Use dplyr's select, or whatever other method you're familiar with.

*Try plotting some of the data, and then a little more.  See where your computer slows down & stop there.  You can plot the data from row 1:n, or sample x number of rows.

# try starting with 100,000 and go up from there.
n <- 100000
ggplot(data_2014[1:n,]) +
 geom_sf()

# Alternatively sample a fraction of the data.
# Start with ~10% and go up until R crashes again.
data_2015 %>%
  sample_frac(.1) %>%
ggplot() +
 geom_sf()


text:
Q: how to cancel a localNotification taken from an array of strings after being converted to NSDate? Let's say this StringArray has strings of Dates which are already scheduled in localNotification, is there a way to get those strings, convert them to dates and then remove a certain scheduled date
var arr = ["2016-08-27 19:29:50 +0000","2016-09-20 17:19:50 +0000","2016-07-27 10:20:30 +0000"]**

func locaNotification(num:Int)

{

    let notification = UILocalNotification()
    let notifTime = NSDate(notificationTime[num])
   UIApplication.sharedApplication().cancelLocalNotification(notification)

}

A: let arrLocalNotif = UIApplication.sharedApplication().scheduledLocalNotifications
for (let localN in arrLocalNotif) {
     let notificationFireDate = localN.fireDate;
    //convert string array value to date object and Compair this bothdate
    if(compair true) {
      UIApplication.sharedApplication().cancelLocalNotification(notification)
            break
    }
}


text:
Q: How to move text labels vertically in tikztiming In a tikz timing graph I want to reduce the font size of the labels. When I do that they are not vertically centred with the graph anymore. How does one move the label vertically to the center?
The MWE is below:
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\begin{document}
\begin{tikztimingtable}[%
    timing/dslope=0.1,
    timing/.style={x=5ex,y=2.2ex},
    x=1ex,
    timing/rowdist=3ex,
    timing/name/.style={font=\rmfamily}]
\small Data   & {[semitransparent]3u} 2D{0} 2D{1}  2D{1} 2D{0} {[semitransparent]2u}\\
\small Clock  & {[semitransparent]3u} LHLHLHLH {[semitransparent]2u}\\ \\
\end{tikztimingtable}
\end{document}

I found in the documentation that I can probably use anchor=mid east, but i'm not sure where to put it.
Thank you for your help!

A: Here, I place the text in equal sized \makeboxes.  The \small can be inside or outside of the \makebox, though a slightly different gap will result after the text, depending...
Why the original version of the OP behaves thus, it might be a case of right-aligned labels.
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\begin{document}
\begin{tikztimingtable}[%
    timing/dslope=0.1,
    timing/.style={x=5ex,y=2.2ex},
    x=1ex,
    timing/rowdist=3ex,
    timing/name/.style={font=\rmfamily}]
\makebox[5ex]{\small Data}   & {[semitransparent]3u} 2D{0} 2D{1}  2D{1} 2D{0} {[semitransparent]2u}\\
\makebox[5ex]{\small Clock}  & {[semitransparent]3u} LHLHLHLH {[semitransparent]2u}\\ \\
\end{tikztimingtable}
\end{document}

The above MWE fixes the horizontal centering of the two words.  To also fix the vertical alignment, per follow-up comments, one can combine this result with a \raisebox:
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\begin{document}
\begin{tikztimingtable}[%
    timing/dslope=0.1,
    timing/.style={x=5ex,y=2.2ex},
    x=1ex,
    timing/rowdist=3ex,
    timing/name/.style={font=\rmfamily}]
\raisebox{1.5pt}{\makebox[5ex]{\small Data}}   & {[semitransparent]3u} 2D{0} 2D{1}  2D{1} 2D{0} {[semitransparent]2u}\\
\raisebox{1.5pt}{\makebox[5ex]{\small Clock}}  & {[semitransparent]3u} LHLHLHLH {[semitransparent]2u}\\ \\
\end{tikztimingtable}
\end{document}

A: A little yshift added to the timing/name style. Also, I'd move the \small there as well.
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\begin{document}
\begin{tikztimingtable}[%
    timing/dslope=0.1,
    timing/.style={x=5ex,y=2.2ex},
    x=1ex,
    timing/rowdist=3ex,
    timing/name/.style={font=\rmfamily\small,yshift=2pt}]
Data   & {[semitransparent]3u} 2D{0} 2D{1}  2D{1} 2D{0} {[semitransparent]2u}\\
Clock  & {[semitransparent]3u} LHLHLHLH {[semitransparent]2u}\\ \\
\end{tikztimingtable}
\end{document}


text:
Q: Android: ListView onItemClickListener retrieve info from database private class lvIncomeListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          (what to do here?)
        }
    }

I have a ListView that is populated by items from my database. The rows in the ListView are multicolumn. The rows show DATE, TITLE, AMOUNT and CATEGORY from that particular Table that I'm fetching the data from.
My next step is to set a onItemClickListener for the ListView, and when the user clicks on of the items in the list, I want there to be a dialog popping up that shows the DATE, TITLE, AMOUNT and CATEGORY from that particular row that was clicked upon.
How is the best way to do this? Do I need to create a cursor inside the onItemClickListener or can I somehow rely on the "position" in the onItemClick?

A: I assume that your Cursor object is somewhere inside your Adapter class. Since the position is provided by your onItemClick method I would do the following:
Cursor cursor = getCursor();
cursor.moveToPosition(position);
String date = cursor.getString(0);

Note that you need to know how your Cursor is queried, and what values it actually contains.


text:
Q: Deadlock occurs when using findAll() from JpaRepository There was a problem with the implementation of the findAll () methods. When called, Deadlock occurs.
@Data
@Entity
@Table(name = "groups")
public class Group {
   /** other fields omitted **/
   @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   private Faculty faculty;
 }

@Data
@Entity
@Table(name = "faculties")
public class Faculty {
   /** other fields omitted **/
   @OneToMany( cascade = CascadeType.ALL,
               orphanRemoval = true)
   private List<Group> groups = new ArrayList<>();
}

Repository:
@Repository
public interface FacultyRepository extends JpaRepository<Faculty, Long> {
}

@Repository
public interface GroupRepository extends JpaRepository<Group, Long> {
}

When I call the findAll () method from the controller,

I installed all the dependencies between the objects as recommended here
Please tell me how to fix this Deadlock=) Thanks)


text:
Q: Taking certain values from a repeated range and pasting them as a row UPDATE
The solution from VBasic2008 works great but I forgot to mention that "all employees" in the names column has a different size array. Adding in another if loop can hopefully correct this? See the screenshot.

The first name is "grouped" as A2:C7. From that range am looking to copy paste the name, job and 2nd and 5th number in column B. This would then loop for the next people and job functions.
Attached are some screenshots for context:
Data Dumps

Desired Output

Sub ArrangeDailyCumulations()

' Source
Const sName As String = "Data Dump"
Const sfCol As String = "A"
Const sfRow As Long = 1
Const sTextColOffset As Long = 1
Const sNumbersCount As Long = 5
Dim sRowOffsets As Variant: sRowOffsets = VBA.Array(0, 0, 2, 5)
Dim sColOffsets As Variant: sColOffsets = VBA.Array(0, 1, 1, 1)
' Destination
Const dName As String = "Daily Cumulations"
Const dfCol As String = "A"
Const dfRow As Long = 2
Dim dColOffsets As Variant: dColOffsets = VBA.Array(1, 0, 3, 2)
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

' Reference the source worksheet and calculate the last row.
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim slRow As Long: slRow = sws.Cells(sws.Rows.count, sfCol).End(xlUp).row

' Reference the destination worksheet, the destination first cell
' and calculate the number of rows from the first cell to the bottom.
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim dfCell As Range: Set dfCell = dws.Cells(dfRow, dfCol)
Dim dwsrCount As Long: dwsrCount = dws.Rows.count - dfCell.row + 1

' Clear the destination column data.

Dim oUpper As Long: oUpper = UBound(dColOffsets)

Dim o As Long

For o = 0 To oUpper
    dfCell.Offset(, dColOffsets(o)).Resize(dwsrCount).Clear
Next o

' Write the values from the source to the destination worksheet.

Dim sCell As Range
Dim sr As Long
Dim dCell As Range
Dim ddrCount As Long

For sr = sfRow To slRow
    Set sCell = sws.Cells(sr, sfCol)
    If Not IsNumeric(sCell.Offset(, sTextColOffset)) Then ' not numeric
        ddrCount = ddrCount + 1
        For o = 0 To oUpper
            dfCell.Offset(, dColOffsets(o)).Value _
                = sCell.Offset(sRowOffsets(o), sColOffsets(o)).Value
        Next o
        Set dfCell = dfCell.Offset(1)
        sr = sr + sNumbersCount
    'Else ' the cell value is a number or is empty (also numeric in vBA)
    End If
Next sr

' Inform.
MsgBox "Number of cumulations copied: " & ddrCount, vbInformation

End Sub

A: Copy From Groups of Data

*

*The second screenshot of the source data is showing that the data is not consistent row-wise hence some of the complications.

*Most of the remaining complications are due to making the code dynamic.

*Adjust (play with) the values in the constants section.

Option Explicit

Sub CopyDailyCumulations()

    ' Source
    Const sName As String = "Data Dump"
    Const sfCol As String = "A"
    Const sfRow As Long = 1
    Const sTextColOffset As Long = 1
    Const sNumbersCount As Long = 5
    Dim sRowOffsets As Variant: sRowOffsets = VBA.Array(0, 0, 2, 5)
    Dim sColOffsets As Variant: sColOffsets = VBA.Array(0, 1, 1, 1)
    ' Destination
    Const dName As String = "Daily Cumulations"
    Const dfCol As String = "A"
    Const dfRow As Long = 2
    Dim dColOffsets As Variant: dColOffsets = VBA.Array(1, 0, 3, 2)
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Reference the source worksheet and calculate the last row.
    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, sfCol).End(xlUp).Row

    ' Reference the destination worksheet, the destination first cell
    ' and calculate the number of rows from the first cell to the bottom.
    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    Dim dfCell As Range: Set dfCell = dws.Cells(dfRow, dfCol)
    Dim dwsrCount As Long: dwsrCount = dws.Rows.Count - dfCell.Row + 1

    ' Clear the destination column data.

    Dim oUpper As Long: oUpper = UBound(dColOffsets)

    Dim o As Long

    For o = 0 To oUpper
        dfCell.Offset(, dColOffsets(o)).Resize(dwsrCount).Clear
    Next o

    ' Write the values from the source to the destination worksheet.

    Dim sCell As Range
    Dim sr As Long
    Dim dCell As Range
    Dim ddrCount As Long

    For sr = sfRow To slRow
        Set sCell = sws.Cells(sr, sfCol)
        If Not IsNumeric(sCell.Offset(, sTextColOffset)) Then ' not numeric
            ddrCount = ddrCount + 1
            For o = 0 To oUpper
                dfCell.Offset(, dColOffsets(o)).Value _
                    = sCell.Offset(sRowOffsets(o), sColOffsets(o)).Value
            Next o
            Set dfCell = dfCell.Offset(1)
            sr = sr + sNumbersCount
        'Else ' the cell value is a number or is empty (also numeric in vBA)
        End If
    Next sr

    ' Inform.
    MsgBox "Number of cumulations copied: " & ddrCount, vbInformation

End Sub

A: Something like this might work (assuming your blocks are all the same size and start in the same place)
Sub DailyCumulations2()

    Dim rng As Range
    Dim ws1 As Worksheet, ws2 As Worksheet

    Set ws1 = Worksheets("Data Dump")
    Set ws2 = Worksheets("Daily Cumulations")

    Set rng = ws1.Range("A2:B7")
    Do While Len(rng.Cells(1).Value) > 0 'while there's content...
        'next empty row on ws2
        With ws2.Cells(Rows.Count, "A").End(xlUp).Offset(1).EntireRow
            'populate data for this row
            .Cells(1).Resize(1, 4).Value = Array(rng.Cells(1, 1).Value, _
                                                 rng.Cells(1, 2).Value, _
                                                 rng.Cells(3, 2).Value, _
                                                 rng.Cells(6, 2).Value)

        End With
        Set rng = rng.Offset(rng.Rows.Count, 0) 'next block down
    Loop
End Sub

A: Besides all the answers above, another way :
The code assumed that there is a consistency of the data in sheet "Bulk Dump", which is something like this :

*

*The cell to the left of each name (A, B, C, etc) is the Job Function value

*the cell to the right of each name is always blank and the rest is always with value (column C)

*the second row after the row of each name in column B is the Time Stamp value

*the fifth row after the row with each name in column B is the Time Allocated value

Sub test()
Dim rg As Range: Dim cell As Range
Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Worksheets("Data Dump")
Set ws2 = Worksheets("Daily Cumulations")

    With ws1
        Set rg = .Range("B2", .Range("B" & Rows.Count).End(xlUp)).Offset(0, 1)
    End With

    With ws2
        Set oFill = .Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
        .Range("A1").Value = "Name": .Range("B1").Value = "Job Function"
        .Range("C1").Value = "Time Stamp": .Range("D1").Value = "Time Allocated"
    End With

    For Each cell In rg.SpecialCells(xlCellTypeBlanks)
        oFill.Value = cell.Offset(0, -1)
        oFill.Offset(0, 1).Value = cell.Offset(0, -2)
        oFill.Offset(0, 2).Value = cell.Offset(2, -1)
        oFill.Offset(0, 3).Value = cell.Offset(5, -1)
        Set oFill = oFill.Offset(1, 0)
    Next

End Sub

Result in ws2:

The sub set the range of the data in column B then offset the range (0,1) into variable rg.
Then it loops to each cell in rg which is blank and used this blank cell as the indicator that the cell to the left of this blank cell is the name. And so on.


text:
Q: Having trouble getting 2nd Nginx site on the same Ubuntu server to work correctly and complete acme challenge Having some trouble getting a 2nd nginx block live - can't get the domain to point to the correct root folder and the Let's Encrypt Acme challenge is failing (probably related problems).
The server is Ubuntu 18.04 and I'm using it as a sandbox to work on sites.
Here is the sites available conf for the site that is just redirecting to the nginx default page
server {
root /var/www/boothslop.online;
index index.php index.html index.htm index.nginx-debian.html
servername boothslop.online www.boothslop.online;
location = /favicon.ico { lognotfound off; accesslog off; }
location = /robots.txt { lognotfound off; accesslog off; allow all; }
location ~* .(css|gif|ico|jpeg|jpg|js|png)$ {
expires max;
lognotfound off;
}
location / {
#tryfiles $uri $uri/ =404;
tryfiles $uri $uri/ /index.php$isargs$args;
}

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }
}

Here is the sites available conf for the site that is working correctly both for lets encrypt and finding the correct root folder when the domain is accessed.
server {
root /var/www/webtest.tech;
index index.php index.html index.htm index.nginx-debian.html
servername webtest.tech www.webtest.tech;
location = /favicon.ico { lognotfound off; accesslog off; }
location = /robots.txt { lognotfound off; accesslog off; allow all; }
location ~* .(css|gif|ico|jpeg|jpg|js|png)$ {
expires max;
lognotfound off;
}
location / {
#tryfiles $uri $uri/ =404;
tryfiles $uri $uri/ /index.php$isargs$args;
}

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }

listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/webtest.tech/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/webtest.tech/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.webtest.tech) {
return 301 https://$host$request_uri;
} # managed by Certbot

if ($host = webtest.tech) {
    return 301 https://$host$request_uri;
} # managed by Certbot

    listen 80;
    server_name webtest.tech www.webtest.tech;
}

This is the error I get from the Acme challenge
 Domain: www.boothslop.online
   Type:   unauthorized
   Detail: Invalid response from
   http://www.boothslop.online/.well-known/acme-challenge/G13Ou7X8U-KMQVvT_ExNvAfK5cF-jHkobGp7hyqw8ac
   [192.34.60.43]: "\r\n<title>404 Not
   Found</title>\r\n\r\n
404
   Not Found
\r\n
"

Thanks very much in advance!

A: The error 404 Not Found means it couldn't find the following file:

http://www.boothslop.online/.well-known/acme-challenge/G13Ou7X8U-KMQVvT_ExNvAfK5cF-jHkobGp7hyqw8ac

Have you added the said file inside your public directory?
When doing responding to acme challenges, you're asked to add a text file in that address, along with what the content should be, so that it can run verification
Run the command again and it'll ask you to save a file with a definite file name and contents. Create the folders in the following structure:
<public directory>
       - .well-known
             - acme-challenge

Add the text file inside the acme folder, then proceed with the verification.
Hope that helps!


text:
Q: For loop doesnt execute for all instances - OS Module Python The code below reads the first 4 letters of a filename, and if a folder with those 4 letters exists then it shifts that file to that folder. Otherwise, it creates a new folder with the first 4 letters and then moves the file to that new folder.
The problem is that it only reads the name of the first file and creates a folder with its first 4 letters when it is executed and doesn't loop through the rest of the files.
# Loop through files,
# read first 4 letters of file name,
# create a folder using the first 4 letters of the file if it doesnt already exsist,
#  If it exsists change directory of the current file to the folder
#  If it doesnt exsist create a folder with first 4 letters of the file and then set path of that file to that folder.

import os
import sys
import shutil

# dir="D:\ALPastPapers\All Past Papers - Copy"
dir="D:\ForFileName"

for filename in os.listdir(dir):
    path = dir + "\\" + filename[0:4]
    # double backslash represents single backslash
    if os.path.isfile(path):
        # if folder exsists:
        source= dir + "\\" + filename
        #getting the directory of the current file
        destination= dir + "\\" + filename[0:4]
        # the folder where we move the file
        shutil.move(source, destination)
        # move the file to the folder
    else:
        os.mkdir(path)
        # make new file
        source= dir + "\\" + filename
        destination= path
        shutil.move(source, destination)

A: It is important to understand the distinction Python sets between files and folders.
Files can be recognised by the os.path.isfile() command but since folders are actually considered as directories you would have to use the os.path.isdir() command.
This is why in the code I posted above, specifically this line:
if os.path.isfile(path):

Actually says, " No the path defined is actually a folder and not a file," so the loop quits.
Instead changing that part to
if os.path.isdir(path):

Gives the perfect result.


text:
Q: intent-filter + nfc.addMimeTypeListener re-opens the app again and again I'm using the phonegap-nfc to perfomr all read/ write actions on NFC tags. The interaction with nfc tag is enabled only in few pages of the app.
Now I'm trying to add new feature i.e on tap NFC tag launch my app(when the app is not running) and do read action on the tag. Launching the app is working.
I have added intent-filter in AndroidManifest.xml as follows:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <data android:host="ext" android:pathPrefix="/<my-urn>" android:scheme="vnd.android.nfc" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

and Added nfc.addMimeTypeListener as follows:

nfc.addMimeTypeListener('text/any', function () {
  // route to particular page
}, function () {
  console.log('success!');
}, function () {
  console.log('Failed!');
});

I'm facing issue when I add nfc.addMimeTypeListener, if I just add intent-filter(without nfc.addMimeTypeListener), it launches the app and when I tap on NFC tag either it does nothing or it performs necessary nfc action based in which page I'm in - which is correct behavior. But when I add nfc.addMimeTypeListener in additoion to intent-filter, if I tap on NFC when the app is already open, it re-opens the app again and again instead of performing the necessary nfc action. Not getting what I'm doing wrong!
Any help would be appriciated!

A: you can try removing listener and add mimeType in the manifest itself for eg <data android:mimeType="text/plain" />


text:
Q: Adjusting css for one specific tab content I'm using a bootstrap for this development. But I'm having a hard time in adjusting the bootstrap CSS. I want to make all the text sit nicely and align and most importantly the text should not sit under the exclamation mark icon. If the text are too long it will go sit under the exclamation mark which I want to avoid it.

If possible can I do my own css for this particular tab content ? If so how would u suggested it ?
Below is what I have tried but the text still goes under the exclamation icon.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

INFORMATION

          PLEASE READ ALL THE TERMS AND CONDITION BEFORE PROCEEDING IT !

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

          <button type="button" class="btn btn-md btn-primary ml-2 button-icon rounded-small f-r" id="startReg" data-toggle="tooltip" data-placement="top" title="Register>Register Now</button>

A: You can do something like that:

/* target the div's you want to style and set it display to flex */
.col-md-12 > div:not(.sec-title2) { display: flex; }
/* put extra padding for readability */
.col-md-12 > div:not(.sec-title2) > i {padding-right: 10px;}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

INFORMATION

          PLEASE READ ALL THE TERMS AND CONDITION BEFORE PROCEEDING IT !

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

 Change in the volume of expected sales Lorem ipsum dolor sit amet, consectetur adipiscing lit, sed do eiusmod data tempor incididunt ut labore et dolore magna.

          <button type="button" class="btn btn-md btn-primary ml-2 button-icon rounded-small f-r" id="startReg" data-toggle="tooltip" data-placement="top" title="Register>Register Now</button>


text:
Q: How to set animation unset when it is hovered I want to add animated footer to my project. It has animation which goes from right to left and then disapears, and it is in the loop. I want it to stop when it is hovered but since there are 2 animation, I want both of them stop when .Footer class is hovered. So html:

And this is the css:
/* INIT */
$logoSize : 50px;
$wrapperWidth : $logoSize*6;
$animationDuration : 3000ms;

html, body, ul {
  margin : 0;
  padding : 0;
}
html, body{
  position:relative;
  width:100%;
  height:100%;
  background: #fff;
  overflow : hidden;
  font-family: Century Gothic,CenturyGothic,AppleGothic,sans-serif;
}
ul {
  list-style-type: none;
}
a {
  text-decoration : none;
}

.f {
  font-size: 0.8em;
  position: fixed;
  top: 5px;
  right: 10px;
  color : #070707;
}

.f a {
  color : #FFC6C6;
}

/* FOOTER */

.Footer {
  position : absolute;
  top : 50%;
  right : 5%;
  transform:translateY( -50% );
}

.Footer::before {
  content : '';
  position : absolute;
  bottom : 25%;
  right : 0;
  width : $wrapperWidth;
  height : 25%;
  background-color : #FFC6C6;
  animation : translate1 $animationDuration infinite;
}

.Footer-items {
  width : $wrapperWidth;
  float : right;
}
.Footer-item {
  display : inline-block;
  width : $logoSize;
  height : $logoSize;
  text-align: center;
}
.Footer-link {
  position : relative;
  display: block;
  width : 100%;
  height : 100%;
  opacity : 0;
  animation : translate2 $animationDuration infinite;
}
.Footer-item:nth-child(2) .Footer-link {
  animation-delay : ($animationDuration/50);
}
.Footer-item:nth-child(3) .Footer-link {
  animation-delay : ($animationDuration/50)*2;
}
.Footer-item:nth-child(4) .Footer-link {
  animation-delay : ($animationDuration/50)*3;
}
.Footer-item:nth-child(5) .Footer-link {
  animation-delay : ($animationDuration/50)*4;
}

.Footer-icon {
  color : #070707;
  position: absolute;
  left : 50%;
  top : 50%;
  font-size : 1.6em;
  transform : translate( -50%, -50% );
  transition : 0.3s;
}

.fa-codepen, .fa-linkedin, .fa-envelope {
  font-size : 1.4em;
}
.fa-linkedin {
  font-size : 1.5em;
}
.fa-envelope {
  font-size : 1.3em;
}

.Footer-link:hover {
  .Footer-icon {
    top : 30%;
  }
  /*.fa-twitter {
    color : #3498db;
  }
  .fa-google-plus {
    color : #E34429;
  }
  .fa-github {
    color : #9C7A5B;
  }
   .fa-linkedin {
    color : #34495e;
  }
   .fa-codepen {
    color : #161616;
  }*/
}

@keyframes translate1{
  0% { opacity : 0; margin-right : -7%; }
  20% { opacity : 1; margin-right : 0; }
  65% { opacity : 1; margin-right : 0; }
  85% { opacity : 0; margin-right : 10%; }
  100% { opacity : 0; margin-right : 10%; }
}
@keyframes translate2{
  2% { opacity : 0; margin-left : 175%; }
  21% { opacity : 1; margin-left : 0%; }
  64% { opacity : 1; margin-left : 0%; }
  80% { opacity : 0; margin-left : -250%; }
  100% { opacity : 0; margin-left : -250%; }
}

So what I am trying to achieve when it is hovered to .Footer, I want to set animation to unset but I don't know how to do that.
Thanks

A: you can do this with CSS too. add this CSS at the end to style tag
.Footer:hover {
    --animationDuration : null;
}

:root {
  --logoSize : 50px;
  --wrapperWidth : 300px;
  --animationDuration : 3000ms;
}

html, body, ul {
  margin : 0;
  padding : 0;
}
html, body{
  position:relative;
  width:100%;
  height:100%;
  background: #fff;
  overflow : hidden;
  font-family: Century Gothic,CenturyGothic,AppleGothic,sans-serif;
}
ul {
  list-style-type: none;
}
a {
  text-decoration : none;
}

.f {
  font-size: 0.8em;
  position: fixed;
  top: 5px;
  right: 10px;
  color : #070707;
}

.f a {
  color : #FFC6C6;
}

/* FOOTER */

.Footer {
  position : absolute;
  top : 50%;
  right : 5%;
  transform:translateY( -50% );
}

.Footer::before {
  content : '';
  position : absolute;
  bottom : 25%;
  right : 0;
  width : var(--wrapperWidth);
  height : 25%;
  background-color : #FFC6C6;
  animation : translate1 var(--animationDuration) infinite;
}

.Footer-items {
  width : var(--wrapperWidth);
  float : right;
}
.Footer-item {
  display : inline-block;
  width : var(--logoSize);
  height : var(--logoSize);
  text-align: center;
}
.Footer-link {
  position : relative;
  display: block;
  width : 100%;
  height : 100%;
  opacity : 0;
  animation : translate2 var(--animationDuration) infinite;
}
.Footer-item:nth-child(2) .Footer-link {
  animation-delay : (var(--animationDuration)/50);
}
.Footer-item:nth-child(3) .Footer-link {
  animation-delay : (var(--animationDuration)/50)*2;
}
.Footer-item:nth-child(4) .Footer-link {
  animation-delay : (var(--animationDuration)/50)*3;
}
.Footer-item:nth-child(5) .Footer-link {
  animation-delay : (var(--animationDuration)/50)*4;
}

.Footer-icon {
  color : #070707;
  position: absolute;
  left : 50%;
  top : 50%;
  font-size : 1.6em;
  transform : translate( -50%, -50% );
  transition : 0.3s;
}

.fa-codepen, .fa-linkedin, .fa-envelope {
  font-size : 1.4em;
}
.fa-linkedin {
  font-size : 1.5em;
}
.fa-envelope {
  font-size : 1.3em;
}

.Footer-link:hover {
  .Footer-icon {
    top : 30%;
  }
  /*.fa-twitter {
    color : #3498db;
  }
  .fa-google-plus {
    color : #E34429;
  }
  .fa-github {
    color : #9C7A5B;
  }
   .fa-linkedin {
    color : #34495e;
  }
   .fa-codepen {
    color : #161616;
  }*/
}

@keyframes translate1{
  0% { opacity : 0; margin-right : -7%; }
  20% { opacity : 1; margin-right : 0; }
  65% { opacity : 1; margin-right : 0; }
  85% { opacity : 0; margin-right : 10%; }
  100% { opacity : 0; margin-right : 10%; }
}
@keyframes translate2{
  2% { opacity : 0; margin-left : 175%; }
  21% { opacity : 1; margin-left : 0%; }
  64% { opacity : 1; margin-left : 0%; }
  80% { opacity : 0; margin-left : -250%; }
  100% { opacity : 0; margin-left : -250%; }
}
.Footer:hover {
    --animationDuration : null;
}


text:
Q: String incrementation I've just started to learn Python and I'm doing some exercises in codewars. The instructions are simple: If the string already ends with a number, the number should be incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
I wrote this:
    if strng[-1].isdigit():
        return strng.replace(strng[-1],str(int(strng[-1])+1))
    else:
        return strng + "1"
    return(strng)

It works sometimes (for example 'foobar001 - foobar002', 'foobar' - 'foobar1'). But in other cases it adds 1 to each number at the end (for example 'foobar11' - 'foobar22'), I would like to achieve a code where the effect is to add only +1 to the ending number, for example when 'foobar99' then 'foobar100', so the number has to be considered as a whole. I would be grateful for advices for beginner :)!

A: First, you have to make some assumptions
Assuming that the numerical values are always at the end of string and the first character from the right that is not numeric would mark the end of the non-number string, i.e.
>>> input = "foobar123456"
>>> output = 123456 + 1

Second, we need to assume that number exists at the end of the string.
So if we encounter a string without a number, we need to decide if the python code should throw an error and not try to add 1.
>>> input = "foobar"

Or we decide that we automatically generate a 0 digit, which would require us to do something like
input = input if input[-1].isdigit() else input + "0"

Lets assume the latter decision for simplicity of the explanation.
Next we will try to read the numbers from the right until you get to a non-digit
Lets use reversed() to flip the string and then a for-loop to read the characters until we reach a non-number, i.e.
>>> s = "foobar123456"
>>> output = 123456

>>> for character in reversed(s):
...     if not character.isdigit():
...         break
...     else:
...         print(character)
...
6
5
4
3
2
1

Now, lets use a list to keep the digits characters
>>> digits_in_reverse = []
>>> for character in reversed(s):
...     if not character.isdigit():
...         break
...     else:
...         digits_in_reverse.append(character)
...
>>> digits_in_reverse
['6', '5', '4', '3', '2', '1']

Then we reverse it:
>>> ''.join(reversed(digits_in_reverse))
'123456'

And convert it into an integer:
>>> int(''.join(reversed(digits_in_reverse)))
123456

Now the +1 increment would be easy!
How do we find the string preceding the number?
# The input string.
s = "foobar123456"
s = s if s[-1].isdigit() else s + "0"

# Keep a list of the digits in reverse.
digits_in_reverse = []

# Iterate through each character from the right.
for character in reversed(s):
    # If we meet a character that is not a digit, stop.
    if not character.isdigit():
        break
    # Otherwise, keep collecting the digits.
    else:
        digits_in_reverse.append(character)

# Reverse, the reversed digits, then convert it into an integer.
number_str = "".join(reversed(digits_in_reverse))
number = int(number_str)

print(number)

# end of string preceeding number.
end = s.rindex(number_str)
print(s[:end])

# Increment +1
print(s[:end] + str(number + 1))

[output]:
123456
foobar
foobar123457

Bonus: Can you do it with a one-liner?
Not exactly one line, but close:
import itertools

s = "foobar123456"
s = s if s[-1].isdigit() else s + "0"

number_str = "".join(itertools.takewhile(lambda ch: ch.isdigit(), reversed(s)))[::-1]

end = s.rindex(number_str)

print(s[:end] + str(int(number_str) + 1))

Bonus: But how about regex?
Yeah, with regex it's pretty magical, you would still make the same assumption as how we started, and to make your regex as simple as possible you have to add another assumption that the alphabetic characters preceding the number can only be made up of a-z or A-Z.
Then you can do this:
import re

s = "foobar123456"
s = s if s[-1].isdigit() else s + "0"

alpha, numeric = re.match("([a-zA-z]+)(\d.+)", s).groups()
print(alpha + str(int(numeric) + 1))

But you have to understand the regex which might be a steep learning, see https://regex101.com/r/9iiaCW/1

A: One simple solution would be:
Have two empty variables head (=non-numeric prefix) and tail (numeric suffix). Iterate the string normally, from left to right. If the current character is a digit, add it to tail. Otherwise, join head and tail, add the current char to head and empty tail. Once complete, increment tail and return head + tail:
def foo(s):
    head = tail = ''

    for char in s:
        if char.isdigit():
            tail += char
        else:
            head += tail + char
            tail = ''

    tail = int(tail or '0')
    return head + str(tail + 1)

Leading zeroes (x001 -> x002), if needed, left as an exercise ;)

A: In your string, you need to check if it is alpha numeric or not. if it is alpha numeric, then you need to check the last character, whether it is digit or not.
now if above condition satisfy then you need to get the index of first digit in the string which make a integer number in last of string.
once you got the index then, seperate the character and numeric part.
once done, convert numerical string part to interger and add 1. after this join both character and numeric part. that is your answer.
# your code goes here

string = 'randomstring2345'
index = len(string) - 1
if string.isalnum() and string[-1].isdigit():

    while True:
        if string[index].isdigit():
            index-=1
        else:
            index+=1
            break
        if index<0:
            break

char_part = string[:index]
int_part = string[index:]
integer = 0
if int_part:
    integer = int(''.join(int_part))

modified_int = integer + 1

new_string = ''.join([char_part, str(modified_int)])
print(new_string)

output
 randomstring2346

A: Regex can be a useful tool in python~ Here I make two groups, the first (.*?) is as few of anything as possible, while the second (\d*$) is as many digits at the end of the string as possible. For more in depth explanation see regexr.
import re

def increment(s):
    word, digits = re.match('(.*?)(\d*$)', s).groups()
    digits = str(int(digits) + 1).zfill(len(digits)) if digits else '1'
    return word + digits

print(increment('foobar001'))
print(increment('foobar009'))
print(increment('foobar19'))
print(increment('foobar20'))
print(increment('foobar99'))
print(increment('foobar'))
print(increment('1a2c1'))
print(increment(''))
print(increment('01'))

Output:
foobar002
foobar010
foobar20
foobar21
foobar100
foobar1
1a2c2
1
02

A: Source
def solve(data):
    result = None
    if len(data) == 0 or not data[-1].isdigit():
        result = data + str(1) #appending 1
    else:
        lin = 0
        for index, ch in enumerate(data[::-1]):
            if ch.isdigit():
                lin = len(data) - index -1
            else:
                break
        result = data[0 : lin] + str(int(data[lin:]) + 1) # incrementing result
    return result
    pass

print(solve("Hey123"))
print(solve("aaabbbzzz"))

output :
Hey124
aaabbbzzz1


text:
Q: Insert dynamically created div before content in a tag If I have the body of some HTML document as follows:

Here's some text

Then the following appends the text to the :
var jselem = document.createElement("div");
jselem.innerHTML = '
Some other text here
';
document.body.appendChild(jselem);

...resulting in:
Here's some text
Some other text here

Is there a way to generate the following after creating the div dynamically such that the following results?
Some other text here
Here's some text

A: I think you're asking about DOM method insertBefore.
document.body.insertBefore(jselem, document.body.firstChild);

DEMO: http://jsfiddle.net/MCnxM/


text:
Q: Vue-compiler unable to parse "$cookies" While working with cookies in vue,after installing & importing,
import VueCookies from 'vue-cookies'
Vue.use (VueCookies)

The compiler throws the following error-
Property '$cookies' does not exist on type 'CombinedVueInstance..

I have mentioned the cookie statements as mentioned in the official documents, as-
this.$cookies.set('user',this.userContents);

These cookies work well with the designed flow and does gets stored in the browser.
The only issue is that the compiler is throwing error despite the fact that these cookies are interacting as required with the Application.
Thank you


text:
Q: Alphabetically Sorting List with multiple different objects using different attributes in Java For a school project, i have to make a card game. The cards can have different types (Joker, PuntenKaart, KleurKaart). Each player has a hand with multiple different combinations of cards (obviously).
i have an abstract class Kaart (card), with 3 subclasses: Joker, KleurKaart (ColourCard), PuntenKaart (PointsCard). All subclasses have an attribute "type" (Joker, KleurKaart, PuntenKaart), but KleurKaart has a second attribute called kleur (colour).
Here's the question: how can I sort a player's hand alphabetically in this situation? Joker and PuntenKaart are easy, just compare type, but with KleurKaart, i'd first have to check if the given Kaart is an instance of KleurKaart and then compare other cards' type to kleur? i don't understand.
class Kaart
package domein;

public abstract class Kaart implements Comparable<Kaart>{

     private String type;

     public Kaart(String type){
         this.type = type;
     }

     public String getType(){
         return type;
     }

     @Override
     public int compareTo(Kaart vergelijkingsKaart) {
         return type.compareTo(vergelijkingsKaart.type);
     }

     @Override
     public String toString(){
         return this.type;
     }
}

class Joker
package domein.kaarten;
import domein.Kaart;

public class Joker extends Kaart {
     public Joker() {
         super("JokerKaart");
     }
}

class PuntenKaart
package domein.kaarten;
import domein.Kaart;

public class PuntenKaart extends Kaart {
    public PuntenKaart() {
        super("PuntenKaart");
    }
}

class KleurKaart
package domein.kaarten;
import domein.Kaart;

public class KleurKaart extends Kaart {
     private String kleur;

     public KleurKaart(String kleur) {
         super("KleurKaart");
         this.kleur = kleur;
     }

     public String getKleur(){
         return this.kleur;
     }

     @Override
     public String toString(){
         return this.kleur;
     }
}

A: Add this code to your KleurKaart class:
 @Override
 public int compareTo(Kaart vergelijkingsKaart) {
     int superReturn = super.compareTo(vergelijkingsKaart);//check how the types of the two cards compare.
     if(superReturn == 0){//if they are the same then do some more checking otherwise return the output of the first check.
        if(vergelijkingsKaart isinstanceof KleurKaart){//if the other card is also a colored card then compare the colours otherwise return the result of the first check.
            KleurKaart otherKaart = ((KleurKaart) vergelijkingsKaart);//cast the other card
            return kleur.compareTo(otherKaart.getgetKleur());//compare the colours.
        }
     }
     return superReturn
 }

This is will override your compareTo() method in the superclass.
So when you call compareTo() on an instance of KleurKaart even if you don't know that it is a KleurKaart when executing the code then the new compareTo() method will be used.
So essentially check the types of the two cards.
If the types are the same AND the other card is a coloured card * , then compare the two colours of the two cards and return that result, otherwise return the result of super.compareTo() method.
Tip: There is actually a class called Color that is usually used for graphics, so if there is extra functionality, such as printing the cards, then i suggest you change type of color to Color.
*(no need to check for this card since it is already an instance of KleurKaart since this compareTo() method only exists in the KleurKaart)
Another way to solve this is to change the toString() method of KleurKaart to
 @Override
 public String toString(){
     return super.toString() + "  " +  this.type;
 }

And the compareTo() method of the Kaart superclass
 @Override
 public int compareTo(Kaart vergelijkingsKaart) {
     return this.toString().compareTo(vergelijkingsKaart.toString());
 }

So you fully write everything you need in the toString() class and the compareTo() method can check which string goes first.

A: You should ovverride the compareTo in the KleurKaart class as below:
 @Override
 public int compareTo(Kaart vergelijkingsKaart) {
     int result = super.compareTo(vergelijkingsKaart.type);
     if(result==0) { //they are both KleurKaart objects
         return ((KleurKaart)this).kleur.compareTo(((KleurKaart)vergelijkingsKaart).kleur);
     }
     return result;
 }

A: I think you should be able to add anothor compareTo in KleurKaart which accepts KleurKaart as a type. It can do the special two-level (color and type) comparison.

A: Depends what you want to compare. Color name for KleurKaart (RED) vs. type JOKER for instance?
Say I have hand JOKER, BLUE, RED, PuntenKaart. How to you expect to be sorted?
BLUE, JokerKaart, PuntenKaart, RED ?
If so, just compare the toString() you already have in place (although it's probably better to define a clearly named method for this).
this.toString().compareTo(vergelijkingsKaart.toString())


text:
Q: How does this jquery loop works? I would like to ask how exactly this loop works ?
I've read a docs about .data() method but I can't figure out what is happening in this example. At the begging we set those 'size' and big parameters just like this?
if ($(window).width() >= 1025) {
  $(function(){
    $('.navbar').data('size', 'big');

    $(window).scroll(function(){
      if ($(document).scrollTop() > 0) {
        if ($('.navbar').data('size') == 'big') {
          $('.navbar').data('size', 'small');
          $('.navbar').stop().animate({
            height: '5vh'
          }, 600);
        }
      } else {
        if ($('.navbar').data('size') == 'small') {
          $('.navbar').data('size', 'big');
          $('.navbar').stop().animate({
            height: '15vh'
          }, 600);
        }
      }
    });

A: There is no loop, data is just for storing parameter "size". (can be 'big' or 'small').
The value is changing when scrolling.
Then the height of the navbar is updated.


text:
Q: Python Tkinter --AttributeError Cannot seem to figure out the below Tkinter message. Usually doing a quick
search will provide answers but this time I seem to miffed the search engines as to
what might be causing the below error.  Curious to know if I am missing a Python package or line 25 below is used in an older version of Python and it has been updated to
a newer command.
I am importing the following packages into the script:
from tkinter import *
from tkinter import filedialog
The function is suppose to save any typed text put into a text area.  It does save the file but the file is empty.
Thanks,
Kurt
C:\Users\kurt>python --version
Python 3.10.4

def saveFiles():
    filename = filedialog.asksaveasfile(
        mode='w',
        title="Save a File",
        defaultextension=".txt"
        )
    filename.config(mode='w')  ------------> **This is line 25**

    pathh.insert(END, filename)
    data = str(txtarea.get(1.0, END))
    filename.write(data)
    filename.close()

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\kurt\Documents\Scripts\TKinter\fileExplorerReadFile.py", line 25, in saveFiles
    filename.config(mode='w')
AttributeError: '_io.TextIOWrapper' object has no attribute 'config'

A: The error is saying that the object returned by the asksaveasfile method doesn't have a config method.

tkinter.filedialog.asksaveasfile(mode='w', **options)¶
Create a SaveAs dialog and return a file object opened in write-only mode.

When you call the asksaveasfile method, it automatically returns a file object in write mode already so there is no need for any further configuration to write to the file.  If you were to omit the line throwing the error, your code should work the way you intended.


text:
Q: Does PHP performance increase by disabling modules? I'm running PHP 7.1.10 with Apache 2.4.6. There's a bunch of PHP modules that are probably not used in my application. Is there any performance boost disabling them?
# ls /etc/php.d
10-opcache.ini   20-dom.ini       20-gettext.ini  20-mbstring.ini  20-shmop.ini      20-sysvsem.ini    20-xsl.ini         30-wddx.ini
20-bz2.ini       20-exif.ini      20-gmp.ini      20-mysqlnd.ini   20-simplexml.ini  20-sysvshm.ini    20-zip.ini         30-xmlreader.ini
20-calendar.ini  20-fileinfo.ini  20-iconv.ini    20-pdo.ini       20-sockets.ini    20-tokenizer.ini  30-mysqli.ini      opcache-default.blacklist
20-ctype.ini     20-ftp.ini       20-imap.ini     20-phar.ini      20-sqlite3.ini    20-xml.ini        30-pdo_mysql.ini
20-curl.ini      20-gd.ini        20-json.ini     20-posix.ini     20-sysvmsg.ini    20-xmlwriter.ini  30-pdo_sqlite.ini

Example, 20-posix.ini:
# cat /etc/php.d/20-posix.ini
; Enable posix extension module
extension=posix.so

Can I safely disable most modules, or is there no significant performance boost?

A: Usually core extensions does not have real impact on performances. But some knowns extensions are really performances-killing like Xdebug (which should be strictly reserved to dev environment).
However if you plan to not make use of some specific extensions you can still make a quick benchmark to test if there's a notable performances changes.
But to be honest as of php7, they highly improved performances by removing old and greedy code, unsupported SAPI, etc. So you should not be worried at all about that.


text:
Q: Explicitly assign or access values to or from specific address/location in memory? My exact question is that there is any provision in c and c++ to assign a value explicitly to particular address for example suppose I want to store 20 at 0x1846010 address in memory and I also want to access a value using this same address (0x1846010).
Might be its easy but I am really confused how to do this if we can.
Anyone can explain is that possible, if yes then how (with suitable example) and if not then why?
Thanks in advance.

A: You can do it like this:
*(int *)0x1846010 = 20;  // store int value 20 at address 0x1846010

Retrieving works similar:
int x = *(int *)0x1846010;

Note that this assumes that address 0x1846010 is writable - in most cases this will generate an exception like Access violation writing location 0x01846010.
P.S. For your interest, you can check given address writable or not at run-time by using the following (borrowed from here):
#include <fcntl.h>
#include <unistd.h>

int is_writeable(void *p)
{
    int fd = open("/dev/zero", O_RDONLY);
    int writeable;

    if (fd < 0)
        return -1; /* Should not happen */

    writeable = read(fd, p, 1) == 1;
    close(fd);

    return writeable;
}

As discussed here, typically you will only ever do this kind of thing for embedded code etc where there is no OS and you need to write to specific memory locations such as registers, I/O ports or special types of memory (e.g. NVRAM).

A: Yes.
Assuming that 0x1846010 is a valid address to which you have write access, you can write:
*(int*)0x1846010 = 20;

And to access the stored value:
printf("%d\n", *(int*)0x1846010);

And if you actually do that in a program, it will probably crash, because 0x1846010 very probably isn't a valid address to which you have write access.
Why exactly do you want to do this? How do you know (if you know) that 0x1846010 is a valid address?
This assumes that the conversion of the integer value 0x1846010 to a pointer is even meaningful. The result of the conversion is implementation-defined, but is "intended to
be consistent with the addressing structure of the execution environment".

A: It depends on the platform and OS (if any) you are using. The herohuyongtao's solution is usually valid BY THE LANGUAGE'S POINT OF VIEW. The real problem is the meaning of addresses in your environment (in other words: what is your goal exactly?). If you are using a modern OS, addresses are almost surely virtual (i.e. translated in a transparent way by the CPU's memory management unit). If your goal is to write on some specific PHYSICAL cell (i.e. because it hosts a device and you want to drive it), you must first be sure that the OS has created a view on the physical address for you. The way to do it depends completely on the OS's API. Even if you don't ave any OS, it's nevertheless possible that the addresses you are handling are not "physical". It depends on the CPU and the way it's initialized.
A completely different case is when your goal is to change a particular address because "you know" that in your environment it has a specific meaning. I.e. an OS may store at a known virtual address some useful information. Many OSs are used to store at a fixed address a copy of the environment variables and command line arguments, so the C runtime library can easily find them. If this is your case, the herohuyongtao's suggestion is usually good.


text:
Q: strings in java behave differently In case of string literal :-
String s = "happ"

s = s.concat("y")  //line1

A: In your first example:
  String s = "happ";
  s = s.concat("y");

By the time these statement have been executed1, String objects have been created in the string pool to represent (respectively) the "happ" literal, and the "y" literal.
The execution of the second statement creates a new String object that represents the string "happy".  This object is NOT in the string pool.

I wanted to specifically clear this doubt on where string stores the result of concat method when operated on strings from pool vs heap.

It is created in the heap2, not the string pool.  Specifically.
The ONLY method in the String API that creates objects in the string pool is String.intern().  (That includes constructors.)

1 - Note my careful choice of words here.  If you are executing the statements for the first time, the creation of the objects in the string pool may have happened during the execution of the statements.  Or it may have happened before.  The exact timing is implementation specific.  However, the JLS guarantees that it won't happen more than once for the same literal.
2 - Note that for a modern HotSpot JVM, the string pool is in the regular heap.  It is not a separate space.  The string pool is effectively just a (JVM private) data structure.

A: Let's just try it out.
String s = "happ";
s = s.concat("y");

System.out.println(s == "happy"); // false
s = s.intern();
System.out.println(s == "happy"); // true

String s1 = new String("Birth");
s1 = s1.concat("day");

System.out.println(s1 == "Birthday"); // false
s1 = s1.intern();
System.out.println(s1 == "Birthday"); // true

So yeah, it just doesn't matter. Only literals are being interned here, not dynamically constructed values (unless explicitly interned).


text:
Q: Pivot data-frame with list as value in column? I have a data-frame like this:

name
A
B
i

x
3
[1,1,1]
1

y
3
4
1

z
5
[1,1,1]
1

x
5
3
2

y
5
7
2

z
7
3
2

What I want is this:

x_A
x_B
y_A
y_B
z_A
z_B
i

3
[1,1,1]
3
4
5
[1,1,1]
1

5
3
5
7
3
3
2

My code so far looks like this:
df = df.pivot_table(column= 'name', values =['A','B'])
df2 = df.unstack().to_frame().T
df2.columns = df2.columns.map('_'.join)

However, when I run this, it seems to skip the columns that have lists (ie. column B) and gives me:

x_A
y_A
z_A

3
3
5

Is there another way to solve this? Am I missing something? TIA.

A: Try:
df = df.set_index("name").stack().to_frame().T
df.columns = df.columns.map("_".join)
print(df)

Prints:
  x_A        x_B y_A y_B z_A        z_B
0   3  [1, 1, 1]   3   4   5  [1, 1, 1]

EDIT: With updated question:
df = df.set_index(["name", "i"]).unstack(level=0).swaplevel(axis=1)
df.columns = df.columns.map("_".join)
print(df.reset_index())

Prints:
   i  x_A  y_A  z_A        x_B y_B        z_B
0  1    3    3    5  [1, 1, 1]   4  [1, 1, 1]
1  2    5    5    7          3   7          3

A: We can use pivot_table with aggfunc of first (to handle object types like list) and sort_index to group level 1 keys together. Then collapse the MultiIndex with Index.swaplevel and Index.map. Lastly, return i to the columns with DataFrame.reset_index:
out_df = (
    df.pivot_table(
        index='i',
        columns='name',
        aggfunc='first'
    ).sort_index(axis=1, level=1)
)
out_df.columns = out_df.columns.swaplevel().map('_'.join)
out_df = out_df.reset_index()

out_df:

i
x_A
x_B
y_A
y_B
z_A
z_B

0
1
3
[1, 1, 1]
3
4
5
[1, 1, 1]

1
2
5
3
5
7
7
3

Setup:
import pandas as pd

df = pd.DataFrame({
    'name': ['x', 'y', 'z', 'x', 'y', 'z'],
    'A': [3, 3, 5, 5, 5, 7],
    'B': [[1, 1, 1], '4', [1, 1, 1], '3', '7', '3'],
    'i': [1, 1, 1, 2, 2, 2]
})

The pyjanitor module has an abstraction for this operation called pivot_wider which simplifies this transformation to:
out_df = df.pivot_wider(index='i', names_from='name')

i
x_A
y_A
z_A
x_B
y_B
z_B

0
1
3
3
5
[1, 1, 1]
4
[1, 1, 1]

1
2
5
5
7
3
7
3

Complete Working Example:
# pip install pyjanitor
# conda install pyjanitor -c conda-forge
import janitor
import pandas as pd

df = pd.DataFrame({
    'name': ['x', 'y', 'z', 'x', 'y', 'z'],
    'A': [3, 3, 5, 5, 5, 7],
    'B': [[1, 1, 1], '4', [1, 1, 1], '3', '7', '3'],
    'i': [1, 1, 1, 2, 2, 2]
})

out_df = df.pivot_wider(index='i', names_from='name')
print(out_df)

A: see https://numpy.org/doc/stable/reference/generated/numpy.ravel.html
from io import StringIO
df = """name    A   B
x   3   [1,1,1]
y   3   4
z   5   [1,1,1]"""
df = pd.read_table(StringIO(df)).set_index('name')
s = pd.Series(df.values.ravel(),
              index=[i+'_'+c for i in df.index for c in df.columns])
s.to_frame().T

x_A
x_B
y_A
y_B
z_A
z_B

0
3
[1,1,1]
3
4
5
[1,1,1]


text:
Q: Words ending in -cial/tial Can anyone please highlight the process behind the formation of words ending in -cial/-tial?
For instance,

finance is the root for financial

but,

different is the root for differential
substance is the root for substantial

Is there some general rule to apply?


text:
Q: flutter and firebase error: type 'String?' can't be assigned to the parameter type 'Object' I am creating a workout app using flutter & firebase. I have an ExerciseStream class which contains a StreamBuilder widget. in the StreamBuilder contains a ListView. in the ListView I pass the ExerciseCard class. In the ExerciseCard class I have if statements which determines which type of card I wanna return. A CardiovascularCard and a StrengthCard. but I get an error inside the if statements.
solution
instead of data!.docs[widget.index][exerciseType] == strength I did this data!.docs[widget.index]['exerciseType'] == strength and it worked. I was missing the quotes around exercisetype
error
when I hover over data!.docs[widget.index][exerciseType] as String == 'strength' in ExerciseCard Class
I get this error:
The argument type 'String?' can't be assigned to the parameter type 'Object'

where is the 'object' in this situation?
code
ExerciseStream
class _ExerciseStreamState extends State<ExerciseStream> {
  @override
  Widget build(BuildContext context) {
    bool? firstLoad = false;
    CollectionReference users = FirebaseFirestore.instance.collection('users');
    return StreamBuilder<QuerySnapshot>(
        stream: users
            .doc(FirebaseAuth.instance.currentUser?.uid.toString())
            .collection('workout')
            .orderBy('exerciseName', descending: true)
            .snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          List<Map<String, dynamic>?>? documentData = snapshot.data?.docs
              .map((e) => e.data() as Map<String, dynamic>?)
              .toList();

          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else {
            if (snapshot.hasError) {
              return const Center(child: Text('Something went wrong'));
            } else {
              if (snapshot.data!.size == 0) {
                firstLoad = false;
                Future.delayed(Duration.zero, () => ExerciseTypeDialog(context))
                    .then((_) => firstLoad = true);
                return const SizedBox(height: 0.0);
              } else {
                firstLoad = true;
                print('documentData = $documentData');
                return Expanded(
                  child: ListView.builder(
                      itemCount: snapshot.data!.size,
                      itemBuilder: (context, index) {
                        return CardiovascularCard(snapshot, index);
                      }),
                );
              }
            }
          }
        });
  }
}

ExerciseTypeDialog
TextEditingController exerciseNameController = TextEditingController();
final uid = FirebaseAuth.instance.currentUser?.uid;
String? exerciseType;
String? strength = 'Strength';
String? cardiovascualar = 'Cardiovascular';
Future<void> ExerciseTypeDialog(BuildContext context) {
  return showDialog(
      barrierDismissible: firstLoad ?? true,
      context: context,
      builder: (context) {
        return AlertDialog(
          backgroundColor: Colors.blueGrey,
          title: const Text('Exercise type'),
          content: Column(mainAxisSize: MainAxisSize.min, children: [
            ListTile(
              onTap: () {
                exerciseType = strength;
                Navigator.pop(context);
                Future.delayed(
                    Duration.zero,
                    () => ExerciseNameDialog(
                        context, exerciseType!, strength, cardiovascualar));
              },
              title: Text(strength!),
            ),
            ListTile(
              onTap: () {
                exerciseType = cardiovascualar;
                Navigator.pop(context);
                Future.delayed(
                    Duration.zero,
                    () => ExerciseNameDialog(
                        context, exerciseType!, strength, cardiovascualar));
              },
              title: Text(cardiovascualar!),
            ),
          ]),
        );
      });
}

ExerciseNameDialog
TextEditingController exerciseNameController = TextEditingController();
final uid = FirebaseAuth.instance.currentUser?.uid;
Future<void> ExerciseNameDialog(
    BuildContext context, String exerciseType, strength, cardiovascualar) {
  return showDialog(
      barrierDismissible: firstLoad ?? true,
      context: context,
      builder: (context) {
        return AlertDialog(
          backgroundColor: Colors.blueGrey,
          title: Text(exerciseType),
          content: TextField(
            controller: exerciseNameController,
          ),
          actions: [
            GradientElevatedButton(
                onPressed: () async {
                  if (exerciseType == strength &&
                      exerciseNameController.text.isNotEmpty) {
                    print(exerciseType);
                    await FirebaseFirestore.instance
                        .collection('users')
                        .doc(uid)
                        .collection('workout')
                        .add({
                      'exerciseName': exerciseNameController.text,
                      'reps': 0.toString(),
                      'sets': 0.toString(),
                      'weight': 0.0.toString(),
                      'rest': 0.0.toString(),
                      'exerciseType': exerciseType
                    });
                    exerciseNameController.clear();
                    Navigator.pop(context);
                  } else {
                    if (exerciseType == cardiovascualar &&
                        exerciseNameController.text.isNotEmpty) {
                      await FirebaseFirestore.instance
                          .collection('users')
                          .doc(uid)
                          .collection('workout')
                          .add({
                        'exerciseName': exerciseNameController.text,
                        'caloriesBurnt': 0,
                        'time': 0.0,
                        'exerciseType': exerciseType
                      });
                      exerciseNameController.clear();
                      Navigator.pop(context);
                    } else {
                      SnackBar _snackBar = const SnackBar(
                        content: Text("Text field can't be empty"),
                      );
                      ScaffoldMessenger.of(context).showSnackBar(_snackBar);
                    }
                  }
                },
                child: const Text(
                  'ADD',
                  style: TextStyle(color: Colors.white),
                ))
          ],
        );
      });
}

ExerciseCard
class ExerciseCard extends StatefulWidget {
  AsyncSnapshot<QuerySnapshot> snapshot;
  int index;
  ExerciseCard(this.snapshot, this.index, {Key? key}) : super(key: key);

  @override
  State<ExerciseCard> createState() => _ExerciseCardState();
}

class _ExerciseCardState extends State<ExerciseCard> {
  @override
  Widget build(BuildContext context) {
    final data = widget.snapshot.data;

    if (data!.docs[widget.index][exerciseType] as String == 'strength') {
      return StrengthCard(widget.snapshot, widget.index);
    } else if (data.docs[widget.index][exerciseType].toString() ==
        'cardiovascualar') {
      return CardiovascularCard(widget.snapshot, widget.index);
    } else {
      Future.delayed(Duration.zero, () => ExerciseTypeDialog(context));
      return const SizedBox(height: 0.0);
    }
  }
}

CardiovascularCard
class CardiovascularCard extends StatefulWidget {
  AsyncSnapshot<QuerySnapshot> snapshot;
  int index;
  CardiovascularCard(this.snapshot, this.index, {Key? key})
      : super(key: key);

  @override
  State<CardiovascularCard> createState() => _CardiovascularCardState();
}

String deleteExerciseText = 'Delete exercise';
final uid = FirebaseAuth.instance.currentUser?.uid;
TextEditingController _calorieController = TextEditingController();
TextEditingController _timeController = TextEditingController();

class _CardiovascularCardState extends State<CardiovascularCard> {

  @override
  Widget build(BuildContext context) {
    String deleteExerciseText = 'Delete exercise';
    final uid = FirebaseAuth.instance.currentUser?.uid;
    final data = widget.snapshot.data;
    final exerciseId = data!.docs[widget.index].reference.id;
    void deleteExerciseFunction() {
      FirebaseFirestore.instance
          .runTransaction((Transaction myTransaction) async {
        myTransaction.delete(data.docs[widget.index].reference);
      });
    }

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(children: [
        Card(
          elevation: 8,
          color: const Color.fromARGB(255, 81, 108, 122),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      data.docs[widget.index]['exerciseName'],
                      style: const TextStyle(
                          fontSize: 20.0, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const Divider(thickness: 1.0),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: const [
                  Text(
                    'Calories',
                    style: TextStyle(color: Colors.white),
                  ),
                  Text(
                    'Time',
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              ),
              Slidable(
                endActionPane: ActionPane(
                  motion: const ScrollMotion(),
                  children: [
                    SlidableAction(
                      onPressed: (context) {
                        DialogInstance(context, deleteExerciseFunction,
                            deleteExerciseText);
                      },
                      label: 'Delete',
                      backgroundColor: Colors.red,
                      icon: Icons.delete,
                    )
                  ],
                ),
                child: ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'caloriesBurnt': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _calorieController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText: data.docs[widget.index]['caloriesBurnt']
                                  .toString()),
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'time': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _timeController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['time'].toString()),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ]),
    );
  }
}

StrengthCard
class StrengthCard extends StatefulWidget {
  final AsyncSnapshot<QuerySnapshot> snapshot;
  int index;

  StrengthCard(this.snapshot, this.index, {Key? key}) : super(key: key);

  @override
  State<StrengthCard> createState() => _StrengthCardState();
}

String deleteExerciseText = 'Delete exercise';
final uid = FirebaseAuth.instance.currentUser?.uid;
late TextEditingController _setsController;
late TextEditingController _repsController;
late TextEditingController _weightController;
late TextEditingController _restController;

class _StrengthCardState extends State<StrengthCard> {
  @override
  void initState() {
    _repsController = TextEditingController();
    _setsController = TextEditingController();
    _weightController = TextEditingController();
    _restController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final data = widget.snapshot.data;
    final exerciseId = data!.docs[widget.index].reference.id;
    void deleteExerciseFunction() {
      FirebaseFirestore.instance
          .runTransaction((Transaction myTransaction) async {
        myTransaction.delete(data.docs[widget.index].reference);
      });
    }

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(children: [
        Card(
          elevation: 8,
          color: const Color.fromARGB(255, 81, 108, 122),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      data.docs[widget.index]['exerciseName'],
                      style: const TextStyle(
                          fontSize: 20.0, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const Divider(thickness: 1.0),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: const [
                  Text(
                    'Reps',
                    style: TextStyle(color: Colors.white),
                  ),
                  Text(
                    'Sets',
                    style: TextStyle(color: Colors.white),
                  ),
                  Text(
                    'Weight',
                    style: TextStyle(color: Colors.white),
                  ),
                  Text(
                    'rest',
                    style: TextStyle(color: Colors.white),
                  )
                ],
              ),
              Slidable(
                endActionPane: ActionPane(
                  motion: const ScrollMotion(),
                  children: [
                    SlidableAction(
                      onPressed: (context) {
                        DialogInstance(context, deleteExerciseFunction,
                            deleteExerciseText);
                      },
                      label: 'Delete',
                      backgroundColor: Colors.red,
                      icon: Icons.delete,
                    )
                  ],
                ),
                child: ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workouts')
                                  .doc(exerciseId)
                                  .update({'reps': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _repsController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['reps'].toString()),
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'sets': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _setsController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['sets'].toString()),
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'weight': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _weightController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['weight'].toString()),
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'rest': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _restController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['rest'].toString()),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ]),
    );
  }
}

Thanks!

A: If you are sure that it's type is string, try cast it with as keyword

A: Try this
data!.docs[widget.index][exerciseType]?.toString() == 'strength'

Remove '?' if the variable is non-nullable

A: instead of data!.docs[widget.index][exerciseType] == strength
I did this data!.docs[widget.index]['exerciseType'] == strength
and it worked