text:
Q: MongoDB ETL (php/java...) Is there an ETL for MongoDB ?...

A: Pentaho Data Integration supports MongoDB (See the documentation http://wiki.pentaho.com/display/EAI/Pentaho+Data+Integration+Steps).
Similarly Talend supports MongoDB: https://github.com/adrien-mogenet/tMongoDBConnection

A: For simple inserts of CSV documents I would suggest looking at the Mongo wiki page Import Export Tools.
For anything more complicated I'd suggest writing an ad-hoc script in the language you are most comfortable with.

A: It seems that Pentaho Data Integration and Talend only supports reading from MongoDB, but not writing.
Another tool that just announced support for MongoDB is DataCleaner, and it supports both read and write operations. It does not position itself quite as an ETL tool, but more like a data quality analysis tool, but it does have ETL-like capabilities also.
http://datacleaner.eobjects.org

A: I created my own ETL solution with python scripts to transfer data from MySQL to MongoDB. It's awesome in my mind.
Basically, I used following two python modules for accessing mysql and mongodb:

*

*pymongo

*python-mysql.connect

Both of them are installable from official Ubuntu repository.

A: I've created MongoDB driver for Scriptella ETL tool. It is available at https://github.com/scriptella/scriptella-mongodb.
Example of migrating data from the relational table:
<connection id="out" url="mongodb://localhost/test"  classpath="../lib/scriptella-mongodb-driver.jar:../lib/mongo-java-driver-2.10.1.jar" />

<query connection-id="in">
    SELECT * FROM USERS
    <script connection-id="out">
        {
            operation: 'db.collection.save',
            collection: 'users',
            data: {
                user_id: '?user_id',
                name: '?name'
            }
        }
    </script>
</query>

A: This PHP program automatically transfers MongoDB database to MySQL,
It introspects the Mogno collections, creates MySQL schema and transfers the data.
It does it only 1 level deep (level 0 and 1), deeper nesting is not migrated:
http://my.sociopal.com/sociopaltech/post?id=simple_utility_for_copying_data_from_mongodb_to_mysql_this_is_a_simple_php_program_im_using_in_o_61755

A: Pentaho DI supports MongoDB reads. I am not sure about the writes. I would think considering the underlying structure of MongoDB as opposed to conventional RDBMS you might be better off looking for a custom ETL process/scripting using python/java maybe rather than off the shelf tools that might not do what they claim to. Eventually one of these players in the BI-ETL market would have this in their tool once the process is mature and tested multiple times for mongoDb

A: MongoSyphon is a lightweight open source ETL tool that transforms data into documents in JSON or XML format.
It can also do the reverse, sending documents directly into MongoDB, differing from other ETL tools that try to create relational structure. Other than MongoSyphon, we can also work with these all tools which deal with the same for eg:

*

*Transporter

*Hevo

*Data

*Krawler

*Panoply

*SYNC

*Pentaho


text:
Q: Python: Matplotlib Surface_plot I'm trying to Plot a high resolution surface_plot, but I would also really like some nice grid lines on top of it. If i use the gridlines in the same argument
ax.plot_surface(x_itp, y_itp, z_itp, rstride=1, cstride=1, facecolors=facecolors, linewidth=0.1)

I get a LOT of grid lines. If I, on the other hand, set "rstride" and "cstride" to higher values, my sphere will become ugly.
I then tried to smash a
ax.plot_wireframe(x_itp, y_itp, z_itp, rstride=3, cstride=3)

in afterwards, but it just lies on top of the colored sphere.. meaning that I can see the backside of the wireframe and then the surface_plot behind it all.
Have anyone tried this?
Another option was to use "Basemap" which can create a nice grid, but then I will have to adapt my colored surface to that.?!
My plot looks like this:

If I add edges to the map with a higher "rstride" and "cstride" then it looks like this:

code :
norm = plt.Normalize()
facecolors = plt.cm.jet(norm(d_itp))

# surface plot
fig, ax = plt.subplots(1, 1, subplot_kw={'projection':'3d', 'aspect':'equal'})
ax.hold(True)
surf = ax.plot_surface(x_itp, y_itp, z_itp, rstride=4, cstride=4, facecolors=facecolors)
surf.set_edgecolors("black")

I want to show the \theta and \phi angles around the sphere.. maybe with 30 degrees apart.
Cheers!
Morten

A: It looks like you may need to use basemap. With plot_surface() you can either have high resolution plot or low resolution with good grid on top. But not both. I just made a simple basemap with contour plot. I think you can do easily apply pcolor on it. Just do not draw continent and country boundary. Then, you have a nice sphere which gives more control. After making your plot, you can easily add grid on it.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

map = Basemap(projection='ortho',lat_0=45,lon_0=-150)
map.drawmapboundary(fill_color='aquamarine')
map.drawmeridians(np.arange(0,360,30)) # grid every 30 deg
map.drawparallels(np.arange(-90,90,30))

nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])
wave = 0.6*(np.sin(2.*lats)**6*np.cos(4.*lons))
mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)

x, y = map(lons*180./np.pi, lats*180./np.pi) # projection from lat, lon to sphere
cs = map.contour(x,y,wave+mean,15,linewidths=1.5) # contour data. You can use pcolor() for your project
plt.title('test1')
plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Embedded .swf file in .pfd-Ubuntu 10.04 I have just finished a presentation in LaTeX. In this very .pdf file I have included a .swf animation(done with adobe flash CS5 in windows) which starts when you click on it.
While I have already installed a relevant player(swfdec flash player) neither document viewer nor okular are able to reproduce it. I tried with my player to make sure that the file is not corrupted and the result was that it can be produced.
I tried the same .pdf file in windows using adobe reader and there is no problem there. The embedded file can be reproduced with no problem.
So I thought of installing adobe in ubuntu. I tried there to see if the problem was solved. Things got a bit better. Adobe could understand that there is something there, so when clicked I got a message that I had to get the proper player. When I clicked on a relevant button I expected to open my browser in a player's page. Instead nothing happened.
If I place my mouse's cursor next to the space that defines my animation the is a "message" stating "Media File(application/x-shockwave flash)". The next step was to install Adobe Flash player, but I couldn't find the standallone player;only the browser's plugs...
How can I get this .swf file play in pdf?

A: First of all install gnash , which can be used as a standalone swf player. As you said, you were using LaTeX, you can write something like \href{run:/tmp/test.swf} in your file.
These steps are explained in more details on tex.stackexchange.com.

A: As alternative, you can embed a flash movie (SWF) into PDf file and play SWF file in Ubuntu using Adobe Reader version < 9.4-2 (version 9.4.1 is recommended as it is the last version for Linux with a built-in Flash player, you can find it here). The embedding is possible using flashmovie LaTeX package, for example:
\flashmovie[width=10cm,height=5cm,auto=1]{yournameforvideofile.swf}

I have recently tested it again in current Ubuntu 16.04 and TeXlive 2015 LaTeX distribution and it works well.


text:
Q: Augmented reality using phonegap I'm working in a project that consist in make a Phonegap app to use Augmented reality.
I was looking for some plugins, but most of them are not free.
someone know how could I do it? my app needs to scan a marker and when it was detected, puts with AR an image. Maybe there are an option in which I could integrate a Unity project with phonegap?
The plugins I researched were:
With pay license:
CraftAr http://catchoom.com/product/
Wikitude http://www.wikitude.com
Layar https://www.layar.com/solutions/#sdk
without license:
ARviewer (without documentation and old version) https://github.com/dixon1e/ARviewer-phoneGap


text:
Q: How to re display tooltip after mouse move I am using a canvas to present several UI components. I am setting canvas.title to present the help for each component.
...
if(mouse.y >= y && mouse.y <= y + w && mouse.over){
    if(currentId !== tool.id){
        canvas.title = tool.help;
    }
    currentId = tool.id;
...

The problem is that when the mouse moves the tool tip is hidden and will not re display until I move the mouse out and then move back onto the canvas.
I would like to change the behaviour so that the tool tip displays again when I hover over another UI component without leaving the canvas element?

A: Implementing your custom tooltip gives more freedom and control.
This is a simple example http://jsfiddle.net/mynetx/5qbP3/
You can take ideas and build from here. Another advantage is control over the CSS which in cases like yours, where you want to provide help.
window.addEventListener("load", function () {
var couponcodes = document.getElementsByClassName("couponcode");
for (var i = 0; i < couponcodes.length; i++) {
    couponcodes[i].addEventListener("mouseover", function () {
        var coupontooltip = this.getElementsByClassName("coupontooltip")[0];
        coupontooltip.removeAttribute("style");
    });
    couponcodes[i].addEventListener("mouseout", function () {
        var coupontooltip = this.getElementsByClassName("coupontooltip")[0];
        coupontooltip.style.display = "none";
    });
} });

A: Tooltips are part of the system the browser runs in and sadly aren't accessible in any way from JavaScript.
I would recommend implementing your own tooltip, which is not very hard (both on canvas and using an extra element).
If you are worried about accessibility—it's possible to give an element "tooltip" role: http://accessibility.athena-ict.com/aria/examples/tooltip.shtml

A: You can use fabric.js. see this.


text:
Q: Is there any way to execute a function after execution of all scenarios in Ruby, Cucumber? Very similar to @aftersuite in testNG. I have an Gsheet API which needs to perform only once all execution is over. I am not using any testNG or JUnit lab.
Thanks in advance :)

A: I have found a similar question here at stackoverflow
It seems you can use the at_exit hook, but there are some issues with that: if you use it the cucumber at_exit code is not run, so you have to call that explicitly yourself.


text:
Q: Display values of multiple input type range in one page I'm trying to display values of every slider I have on my page, this is my code so far:

var i = 0;
var st = 'slider';
var ot = 'output';
var s = '';
var o = '';

for (var x = 0; x < 3; x++) {
i++;
s = st+i;
o = ot+i;

 var s = document.getElementById("range"+i);
    var o = document.getElementById("limit"+i);
 o.innerHTML = s.value;

s.oninput = function() {
 o.innerHTML = this.value;
}

}

     <input type="range" min="2" max="50" value="20" class="slider" id="range1" >
 You chose

     <input type="range" min="2" max="50" value="20" class="slider" id="range2" >
 You chose

     <input type="range" min="2" max="50" value="20" class="slider" id="range3" >
 You chose

It's only changing the last value when I move any slider, I want to display the value of each slider respectively. I'm using a loop in my JavaScript code because I have more than 20 sliders and I don't want to write a function for each of them unless that is the only way of doing it. Any suggestions?

A: The problem you are having is related to variable scope. There is only one variable named o, each iteration of the loop changes this variable. So when the
oninput function is evaluated o equals the last value you set it to equal. The current value of o is not "saved" in the function definition.
See https://www.w3schools.com/js/js_scope.asp for more information.
See solution below, here I find the limit in each call to the function.

function updateLabel() {
  var limit = this.parentElement.getElementsByClassName("limit")[0];
  limit.innerHTML = this.value;
}

var slideContainers = document.getElementsByClassName("slidecontainer");

for (var i = 0; i < slideContainers.length; i++) {
  var slider = slideContainers[i].getElementsByClassName("slider")[0];
  updateLabel.call(slider);
  slider.oninput = updateLabel;
}

  <input type="range" min="2" max="50" value="20" class="slider">
  You chose

  <input type="range" min="2" max="50" value="20" class="slider">
  You chose

  <input type="range" min="2" max="50" value="20" class="slider">
  You chose


text:
Q: How to Ajaxify a Partial View which uses Razor Validation I'm very new to MVC Razor (as is our entire team)
My question is How to Ajaxify a Partial view, but only if the Razor HtmlValidationMessagefor has checked what it should, then the ajax call.
The beneath code allows the ajax call even if nothing was selected from the DDL (which has a validation attribute.),
and do it again and there is a failure..it loses it's model.
Totally lost we are.
Parent
Host.cshtml

@model ReloadPartials.Models.MyContainer
@{
 ViewBag.Title = "Host";
}

Host

 @using (Html.BeginForm("Host", "Example"))
 {
  @Html.AntiForgeryToken()
  @Html.Partial("Header", Model)
  @Html.Partial("Details", Model)

   <input type="submit" name="actionPerformed" value="Save All" class="btn btn-default col-md-offset-2 col-md-2" />

 }

@section Scripts {
 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/jqueryval")
}

Details cshtml

@model ReloadPartials.Models.MyContainer

@{
 ViewBag.DetailIndex = 0;
 int detailItemsSideBySide = 2;
 int currentDetailItem = 1;
 int i = 0;
}

Details Section

  @*@for (int i = 0; i < Model.Details.Count(); i++)
  {*@
   Model.Details[i].Index = i;
   ViewBag.DetailIndex = i;

    @Html.Partial("Detail", Model)

   if (currentDetailItem == detailItemsSideBySide)
   {
    currentDetailItem = 0;

   }
   currentDetailItem++;
  @*}*@

Detail.cshtml
(The inner single (or multiple instances of this partial view, depending on Details.cshtml)

@model ReloadPartials.Models.MyContainer

@{
 int index = ViewBag.DetailIndex;
}

Detail Section @index.ToString()

 @Html.HiddenFor(model => model.Details[index].HeaderId)
 @Html.HiddenFor(model => model.Details[index].Id)

  @Html.LabelFor(model => model.Details[index].Name, htmlAttributes: new { @class = "control-label col-md-2" })

   @*This on change will call submit*@
   @*@Html.DropDownListFor(model => model.Details[index].Name, (SelectList)ViewBag.Names, "Select a Name", htmlAttributes: new { @class = "form-control", onchange = "$(this.form).submit();" })*@

   @Html.DropDownListFor(model => model.Details[index].Name,
    (SelectList)ViewBag.Names, "Select a Name",
    htmlAttributes: new { @class = "form-control" , id = "ddlNames" + index.ToString() })

   @Html.ValidationMessageFor(model => model.Details[index].Name, "", new { @class = "text-danger" })

  @Html.LabelFor(model => model.Details[index].SomeNumber, htmlAttributes: new { @class = "control-label col-md-2" })

   @Html.EditorFor(model => model.Details[index].SomeNumber,
     new { htmlAttributes = new { @class = "form-control", id = "txtInput" + index.ToString() } })

   @Html.ValidationMessageFor(model => model.Details[index].SomeNumber, "", new { @class = "text-danger" })

@Model.Details[index].SomeNumber.ToString()

 @*This button (and/or combo onchange) should actually go get data from the server and then just reload this detail section using AJAX*@
 @*Use razor and the viewbag to uniquely identify each instance of this partial, such that we can identify which instance of this partial invoked the Ajax call*@

  <button id ="@("btnReload" +  @ViewBag.DetailIndex)" name="actionPerformed" value="Reload Detail"
    class="btn btn-default col-md-offset-2 col-md-3">Reload</button>

The controller
public class ExampleController : Controller
{
    [ChildActionOnly]
    private MyContainer InitialiseContainer()
    {
        MyContainer containter = new MyContainer();

        containter.Header = new MyHeader(1, "Header Name");
        containter.Details.Add(new MyDetail(1, 1, "Detail 1 Name", 100));
        containter.Details.Add(new MyDetail(1, 2, "Detail 2 Name", 200));

        return containter;
    }

[HttpGet]
public ActionResult Host()
{
    //ViewBag.xxSelectedItem = "Detail Name 4";
    Session["isAjaxCall"] = false;
    MyContainer container = InitialiseContainer();
    ViewBag.Names = NamesLookup(null);
    return View(container);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Host(MyContainer container, string actionPerformed)
{
    if (actionPerformed == "Save All")
    {
        //return RedirectToAction("xxx");
    }
    if (actionPerformed == "Reload Detail")
    {
        if ((bool)Session["isAjaxCall"] == true)
        {
            ViewBag.DetailIndex = 0;
            ViewBag.Names = NamesLookup(null);
            NewModelContainer = (MyContainer)Session["MyContainer"];
            return PartialView("Detail", NewModelContainer);
        }
        else
        {
            //this action runs if , from the ajax code we reference the Div(s) set by the parent view "Details"
            container = setsomeValues(container);
            ViewBag.DetailIndex = 0;
            ViewBag.Names = NamesLookup(null);
            return View(container);
        }
    }

    ViewBag.Names = NamesLookup(null);
    return View(container);
}

`public PartialViewResult GetAjaxPostBackData_OnlyTextBox(string ajaxDetailModelData, string index)
{

    Session["isAjaxCall"] = true;

    int i = 0;
    int.TryParse(index, out i);
    ViewBag.DetailIndex = i;

    //get the items to populate the dropdown List with
    ViewBag.Names = NamesLookup(null);

    //get an instance of the Model (Container), either from session (with changed and persisted values in it, or Cleanly re-initialized)
    MyContainer NewModelContainer = InitialiseContainer();
    NewModelContainer = UnpackAjaxdetailModelData(ajaxDetailModelData,index);

    //arb Test ..change the HTML Input
    NewModelContainer.Details[i].SomeNumber = 777;

    Session["NewModelContainer"] = NewModelContainer;

    //return just the partial view as indexed, which's btnXXX_index was clicked
    return PartialView("Detail", NewModelContainer);
}

[ChildActionOnly]
private SelectList NamesLookup(object selectedObject)
{
    List<MyName> names = new List<MyName>();

    names.Add(new MyName(1, "Detail Name 1"));
    names.Add(new MyName(2, "Detail Name 2"));
    names.Add(new MyName(3, "Detail Name 3"));
    names.Add(new MyName(4, "Detail Name 4"));
    names.Add(new MyName(5, "Detail Name 5"));

    return new SelectList(names, "Name", "Name", selectedObject);
}

}

thanks
Layout


text:
Q: Only select rows from current page using checkbox on header in Ag-grid I am facing an issue related to Ag-grid is that when we check the checkbox from header then they select all total records (all pages in pagination) I just want to select the current page data for ex: I have 10 records in page number 1 then they should select only 10 records in a grid.

A: Creating solution for your problem I chose Custom Components, that will help to define custom header renderer to use at the column definition level.
CustomHeader will be in charge of the checkbox display in the grid - full definition is available in example at the end of the post:
  CustomHeader.prototype.init = function(params) { ... }

Checkboxes are shown in first column (using isFirstColumn function) and will be refreshed on each pagination change
or checkbox selection (onPaginationChanged onSelectionChanged).
This is compulsory, as element needs to be checked only if all rows are selected.

refreshHeader() Redraws the header. Useful if a column name changes, or something else that changes how the column header is displayed.

  // grid definition
  $scope.gridOptions = {
    ...
    defaultColDef: {
      sortable: true,
      filter: true,
      resize: true,
      checkboxSelection: isFirstColumn
    },
    onPaginationChanged: onPaginationChanged,
    onSelectionChanged: onSelectionChanged
  };

  // events handlers
  function onSelectionChanged(event) {
    this.api.refreshHeader();
  }

  function onPaginationChanged(event) {
    this.api.refreshHeader();
  }

  function isFirstColumn(params) {

    return params.column.colId === "make";

    //Previous implementation with detecting
    //first column but slows down the grid
    //var displayedColumns = params.columnApi.getAllDisplayedColumns();
    //var thisIsFirstColumn = displayedColumns[0] === params.column;
    //return thisIsFirstColumn;
  }

Working example AngularJs
Working example Angular5

A: Simple code-based solution without need for any custom component:
Attach paginationChanged event listener to onGridReady Grid event:
onGridReady = (params) =>
{
    this.gridApi.addEventListener('paginationChanged', (e) =>
        {
            //Reset rows selection based on current page
            this.resetPaginationSelection(this);
        });
};

Event Handler method for handling selectable rows in current page:
resetPaginationSelection = (self) =>
{
    //Deselect previously selected rows to reset selection
    self.gridApi.deselectAll();

    //Initialize pagination data
    let paginationSize = self.gridApi.paginationGetPageSize();
    let currentPageNum = self.gridApi.paginationGetCurrentPage();
    let totalRowsCount = self.gridApi.getDisplayedRowCount();

    //Calculate current page row indexes
    let currentPageRowStartIndex = (currentPageNum * paginationSize);
    let currentPageRowLastIndex = (currentPageRowStartIndex + paginationSize);
    if(currentPageRowLastIndex > totalRowsCount) currentPageRowLastIndex = (totalRowsCount);

    for(let i = 0; i < totalRowsCount; i++)
    {
        //Set isRowSelectable=true attribute for current page rows, and false for other page rows
        let isWithinCurrentPage = (i >= currentPageRowStartIndex && i < currentPageRowLastIndex);
        self.gridApi.getDisplayedRowAtIndex(i).setRowSelectable(isWithinCurrentPage);
    }
};


text:
Q: Proving that the quadratic equation $(q-5)x^2 +5x -q=0$ has real roots for any value of $q$ Prove that the quadratic equation $(q-5)x^2 +5x -q=0$ has real roots for any value of $q$.
So I have already tried using the discriminant but just wanted to see if my answer is right or not. Appreciate every feedback.

A: $$Discriminant = {\sqrt {b^2-4ac}}$$
$$ = {\sqrt {5^2-4(-q)(q-5)}}$$
$$ = {\sqrt {25+4(q)(q-5)}}$$
$$ = {\sqrt {4q^2-20q+25}}$$
$$ = {\sqrt {(2q-5)^2}}$$
As ${(2q-5)^2}$ ${\ge}\,0$, real roots always exist.

A: As a hint, and supplementing the discriminant solution offered previously:
$$(q-5)x^2 +5x -q \:=\: (x-1)\big((q-5)x+q\big)$$


text:
Q: is it ubuntu supports wpa3 enterprise security? intel certified wireless adopter (AX201NGW) supported for both wpa3 enterprise and personal, in windows both wpa3 enterprise and personal are working but in the Ubuntu v22 i can see only wpa3 personal, and network manager is 1.36 also,no wpa3 enterprise is not visible ,
required confirmation is wpa3-enterprise supports or not ?
if available please share the details,


text:
Q: Upload progress bar Java Servlet? I want to show upload progress bar for my uploads using servlet. I tried Ajax, iFrame technique. The page is not reloading and the file also getting uplaoded. But, progress bar is not coming. Is there any jQuery progress plugin available for java servelts?
Thanks!!

A: I strongly recommend jQuery Uploadify plugin for ajax file uploads. It comes with a progress bar as well. You can find an example on their demo page.
Integration with JSP/Servlet isn't that hard. You can basically keep the servlet code for "regular" file uploads unchanged. I've however ever written a mini tutorial in an answer here (check the "update" part of the answer), you may find it useful as well.


text:
Q: Chakra UI + React Hook Form error wrong Types I am trying to use ChakraUI and React-Hook-Form to create my form in TypeScript. However, my errors are giving me problems related to typescript it seems. I copy pasted this code from chakra ui/react-hook-form template provided on chakra's website. Here is the code:
import {
  Box,
  Heading,
  FormErrorMessage,
  FormLabel,
  FormControl,
  Input,
  Button,
  Text,
  FormHelperText,
} from '@chakra-ui/react'
import React from 'react'
import styles from '../../theme/styles'
import textStyles from '../../theme/text-styles'
import { useForm } from 'react-hook-form'

const DescribeCargo = () => {
  const {
    handleSubmit,
    register,
    formState: { errors, isSubmitting },
  } = useForm()

  function onSubmit(values: any) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(JSON.stringify(values, null, 2))
        resolve(values)
      }, 3000)
    })
  }

  return (
    <>
      <Box {...styles.bodyContainer}>
        <Heading {...textStyles.componentHeader} my={7} as='h3'>
          Describe the cargo
        </Heading>
        <form onSubmit={handleSubmit(onSubmit)}>
          <FormControl isInvalid={errors.name}>
            <FormLabel htmlFor='name'>First name</FormLabel>
            <Input
              id='name'
              placeholder='name'
              {...register('name', {
                required: 'This is required',
                minLength: { value: 4, message: 'Minimum length should be 4' },
              })}
            />
            <FormErrorMessage>{errors.name && errors.name.message}</FormErrorMessage>
          </FormControl>
          <FormControl isInvalid={errors.lastname}>
            <FormLabel htmlFor='lastname'>Last name</FormLabel>
            <Input
              id='lastname'
              placeholder='lastname'
              {...register('lastname', {
                required: 'This is required',
                minLength: { value: 8, message: 'Minimum length should be 8' },
              })}
            />
            <FormErrorMessage>{errors.lastname && errors.lastname.message}</FormErrorMessage>
          </FormControl>
          <Button mt={4} colorScheme='teal' isLoading={isSubmitting} type='submit'>
            Submit
          </Button>
        </form>
      </Box>
    </>
  )
}

export default DescribeCargo

Here are the errors I'm getting:
TS2322: Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>> | undefined' is not assignable to type 'ReactNode'.
  Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>' is not assignable to type 'ReactNode'.
    Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>' is missing the following properties from type 'ReactPortal': key, children, type, props
    48 |               })}
    49 |             />
  > 50 |             <FormErrorMessage>{errors.name && errors.name.message}</FormErrorMessage>
       |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    51 |           </FormControl>
    52 |           <FormControl isInvalid={errors.lastname}>
    53 |             <FormLabel htmlFor='lastname'>Last name</FormLabel>

TS2322: Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>> | undefined' is not assignable to type 'boolean | undefined'.
  Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>' is not assignable to type 'boolean | undefined'.
    38 |         </Heading>
    39 |         <form onSubmit={handleSubmit(onSubmit)}>
  > 40 |           <FormControl isInvalid={errors.name}>
       |                        ^^^^^^^^^
    41 |             <FormLabel htmlFor='name'>First name</FormLabel>
    42 |             <Input
    43 |               id='name'

Perhaps I could write it without Chakra - however I would like to stick with the theme of this app. I changed the type of errors to any, however it's not helping much.

A: I had the exact same type issue. I solved this with :
<FormErrorMessage>
    {errors.title && errors.title.message?.toString()}
</FormErrorMessage>

A: I don't know about chakra UI, but issue is because type of errors from useForm hook and children type of FormErrorMessage are different. For first error, try updating like this
<FormErrorMessage>
    <Text>{errors.name && errors.name.message}</Text>
</FormErrorMessage>

For 2nd error isInvalid prop expects either boolean or undefined. So, you have to convert errors.name to boolean
<FormControl isInvalid={Boolean(errors.name)}>

If there is some error in name field, then errors.name will not be empty and Boolean(errors.name) is true

A: Create an interface outisde the component
interface IFormInputs {
  name: string;
  lastname: string;
}

then assign the interface to useForm hook
const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm<IFormInputs>();

This should solve the problem.


text:
Q: Global aggregation on non-default measure To aggregate along the default measure we use:
SELECT FROM [Sales]

It returns a "scalar", a value without any header:
+------+
| 1000 |
+------+

How to do the same with non default measure?
This raises an error:
SELECT [Measures].[Quantity] FROM [Sales]

This works:
SELECT [Measures].[Quantity] ON 0 FROM [Sales]

But instead of having a "scalar" we get an additional header with the name of the measure:
+----------+
| Quantity |
+----------+
|   1000   |
+----------+

A: This kind of query
SELECT FROM [Sales]

is so called query with zero axes. Because no members were assigned to any (non-slicer) axis, the result is considered to have zero axes and by convention would be single
unlabeled cell, or at least cell with no distinct row or column headers, and that is what you see.
With this query
SELECT [Measures].[Quantity] ON 0 FROM [Sales]

you have specified that you want to see Quantity measure on axes 0 (to see Quantity measure on Columns).
To achieve "zero axes" query result you should put your measure on slicer (specified with Where):
SELECT  FROM [Sales]
WHERE [Measures].[Quantity]


text:
Q: Ubuntu clock is wrong and I can't change it (running as VirtualBox Guest under OSX) I have a strange problem with my Ubuntu Natty virtual machine running under VirtualBox on OSX.
One day last week, my clock on the top bar in Gnome stopped displaying the correct time (I'm not running Unity).  I'm on GMT, so right now it should be 9:31, but it's showing 3:31, so I think it's something to do with TimeZones.
If I go into the date and time applet, the time is initially wrong but after a second sets itself to the correct GMT Time.  The timezone is correclty set as London and it makes no difference if I unlock and set it again or select manual or automatic from internet time.
From a bash prompt, the "date" command shows: "Tue Sep 20 03:33:35 CDT 2011".
If I run "sudo dpkg-reconfigure tzdata" I am correctly set as London.  Upon exiting the commnand I'm shown the correct London time, but then typing "date" again shows the CDT time again.
:~/$ date
Tue Sep 20 03:33:35 CDT 2011

:~/$ sudo dpkg-reconfigure tzdata
Current default time zone: 'Europe/London'
Local time is now:      Tue Sep 20 09:34:22 BST 2011.
Universal Time is now:  Tue Sep 20 08:34:22 UTC 2011.

:~/$ date
Tue Sep 20 03:34:26 CDT 2011

The clock is correct in OSX.  This has been working fine for a month or two - I think it stopped working after an update last week.  Any ideas?

A: I had a similar issue with ArchLinux guest in VirtualBox host. When I use TIMEZONE="Africa/Johannesburg" or TIMEZONE="Asia/Bahrain" in my rc.conf file, the output of date is correct but when I use TIMEZONE="/Etc/GMT+2" or "/Etc/GMT+3" (corresponding to aforementioned timezones) then the VBoxService sets time 6 hours to early.
My hardware clock time always remains correct (sudo hwclock --show) and setting system time from hardware clock (sudo hwclock --hctosys) sets system time correctly until VBoxService runs timesync again and output of date is 6 hours too early.
To summarize; using timezones from /usr/share/zoneinfo// seems to work but other zoneinfos might not work, I don't know why this is.

A: I had the exact same issue on my regular Ubuntu install. The reason turned out to be that I had installed sontek's dotfiles. In a .profile, the TZ variable was explicitly set to America/Chicago. Removing this entry fixed the problem.
What lead me to the answer was this question, and new123456's comment.

A: In order to change your timezone, run the following command in the shell:
$ sudo "ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime"

That command assumes that your hardware (BIOS) clock is GMT. You can scour /usr/share/zoneinfo for a better option.


text:
Q: Flickering when dragging over child elements I am using ngx-dropzone and it is all working fine except on hover on <ngx-dropzone-label> it start to flicker.
example video is availble in this Link. it seems dragleave event fired when hovering a child element.
      <ngx-dropzone class="dropzone" #dropzonde (change)="onSelect($event)" [accept]="allExtentions" [multiple]="true">
        <ngx-dropzone-label>

          test
          <button igxButton="outlined" class="secondary-button" igxRipple="white">browse</button>

test 1

test 2

        </ngx-dropzone-label>
      </ngx-dropzone>

.dropzone {
  display: flex;
  align-items: center;
  height: 250px;
  background: var(--white);
  cursor: pointer;
  color: var(--g-600-comet);
  border: 2px dashed var(--g-500-granite);
  border-radius: 5px;
  font-size: var(--font-size-16);
  justify-content: center;
  ngx-dropzone-label {
    margin: 0px !important;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.ngx-dz-hovered {
  background-color: rgba(0, 65, 91, 0.7);

  .input-label {
    color: var(--w-100-snow)
  }

  .empty-mountain {
    filter: var(--white-filter-icon);
  }

  .dropping-box {
    display: block !important;
    z-index: 0;
  }

  .drag-drop-upload-icon {
    width: 95px;
    height: 95px;
    filter: var(--white-filter-icon);
  }

  .drag-drop-upload-text,
  .drag-drop-upload-header-text {
    line-height: 24px;
    letter-spacing: 0.15px;
    color: var(--white);
    padding-top: 1px;
  }

  .drag-drop-upload-header-text {
    font-size: var(--font-size-16);
    font-family: var(--font-family-semi-bold);
  }

  .drag-drop-upload-text {
    font-size: var(--font-size-14);
    font-family: var(--font-family-regular);
  }

  .igx-button,
  .input-label,
  .empty-mountain {
    display: none;
  }
}

Any idea why it  is flickring on child element of that element?


text:
Q: Calendar Carousel gives range error in flutter Calendar Carousel given me following error.It worked correctly before.Now It's not working I've tried flutter clean and switching the channel but error remaining same.

 I/flutter (30661): RangeError (index): Invalid value: Valid value range is empty: 0
    I/flutter (30661): The relevant error-causing widget was:
    I/flutter (30661):   Container
    lib\date.dart:53
    I/flutter (30661): When the exception was thrown, this was the stack:
    I/flutter (30661): #0      List.[]  (dart:core-patch/growable_array.dart:146:60)
    I/flutter (30661): #1      _CalendarState._setDatesAndWeeks
    package:flutter_calendar_carousel/flutter_calendar_carousel.dart:836
    I/flutter (30661): #2      _CalendarState._setDate.<anonymous closure>
    package:flutter_calendar_carousel/flutter_calendar_carousel.dart:854
    I/flutter (30661): #3      State.setState
    package:flutter/…/widgets/framework.dart:1233
    I/flutter (30661): #4      _CalendarState._setDate
    package:flutter_calendar_carousel/flutter_calendar_carousel.dart:853
    I/flutter (30661): #5      _CalendarState.initState

Here is the code,I've tried Calendar Carousel example It also gives me the same error.I don't know what causing this.
class BoxContainer extends StatefulWidget {
  @override
  _BoxContainerState createState() => _BoxContainerState();
}

DateTime _currentDate;

class _BoxContainerState extends State<BoxContainer> {
  @override
  Widget build(BuildContext context) {
    return Container(
    margin: EdgeInsets.symmetric(horizontal: 16.0),
    child: CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate = date);
      },
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
      customDayBuilder: (
        bool isSelectable,
        int index,
        bool isSelectedDay,
        bool isToday,
        bool isPrevMonthDay,
        TextStyle textStyle,
        bool isNextMonthDay,
        bool isThisMonthDay,
        DateTime day,
      ) {

          if (day.day == 15) {
            return Center(
              child: Icon(Icons.local_airport),
            );
          } else {
            return null;
          }
      },
      weekFormat: false,
      markedDatesMap: _markedDateMap,
      height: 420.0,
      selectedDateTime: _currentDate,
      daysHaveCircularBorder: false,
    ),
  );
}

}


text:
Q: List all leaf subdirectories in linux Is there an easy way to list only directories under a given directory in Linux?
To explain better, I can do:
find mydir -type d

which gives:
mydir/src
mydir/src/main
mydir/bin
mydir/bin/classes

What I want instead is:
mydir/src/main
mydir/bin/classes

I can do this in a bash script that loops over the lines and removes previous line if next line contains the path, but I'm wondering if there is a simpler method that does not use bash loops.

A: If you're looking for something visual, tree -d is nice.

drinks
|-- coke
|   |-- cherry
|   `-- diet
|       |-- caffeine-free
|       `-- cherry
|-- juice
|   `-- orange
|       `-- homestyle
|           `-- quart
`-- pepsi
    |-- clear
    `-- diet

A: I can't think of anything that will do this without a loop. So, here are some loops:
This displays the leaf directories under the current directory, regardless of their depth:
for dir in $(find -depth -type d); do [[ ! $prev =~ $dir ]] && echo "$dir" ; prev="$dir"; done

This version properly handles directory names containing spaces:
saveIFS=$IFS; IFS=$'\n'; for dir in $(find -depth -type d ); do [[ ! $prev =~ $dir ]] && echo "${dir}" ; prev="$dir"; done; IFS=$saveIFS

Here is a version using Jefromi's suggestion:
find -depth -type d | while read dir;  do [[ ! $prev =~ $dir ]] && echo "${dir}" ; prev="$dir"; done

A: If you want only the leaf directories (directories which don't contain any sub-directory), look at this other question. The answer also explains it, but in short it is:
find . -type d -links 2

A: find . -type d | sort | awk '$0 !~ last "/" {print last} {last=$0} END {print last}'

A: The solution using awk is nice, simple… and fails if the directory name contains any character that is considered special in forming regex patterns. This also presents an issue with the ~ or != tests in Bash.
The following seems to work for both BSD and GNU find:
find . -type d | sed 's:$:/:' | sort -r | while read -r dir;do [[ "${dir}" != "${prev:0:${#dir}}" ]] && echo "${dir}" && prev="${dir}";done

*

*Change find . to any directory you want to start the search in.

*The sed command adds a forward slash to each directory returned by
find.

*sort -r sorts the directory list in reverse alphabetical order,
which has the benefit of listing the directories furthest away from a
root first, which is what we want.

*This list is then read in line-by-line by the while read loop,
where the -r option further protects against treating certain
characters differently from others.

*We then need to compare the current line against the previous one. As
we cannot use the != test and that intermediate directories will
have a path shorter than that of the corresponding leaf directory,
our test will compare the current line to the previous line truncated
to the length of the current line. If that's a match, then we can
discard this line as a non-leaf directory, otherwise we print this
line and set it as the previous line ready for the next iteration.
Note that the strings need to be quoted in the test statement,
otherwise some false positives may be produced.

Oh, if you don't want to use find…
shopt -s nullglob globstar;printf "%s\n" **/ | sort -r | while read -r dir;do [[ "${dir}" != "${prev:0:${#dir}}" ]] && echo "${dir}" && prev="${dir}";done;shopt -u nullglob globstar

UPDATE (2020-06-03): Here's a script I've thrown together that's hopefully useful. Obviously feel free to improve/adapt/point out glaring problems…
#!/usr/bin/env bash

# leaf: from a given source, output only the directories
#       required ('leaf folders' ) to recreate a full
#       directory structure when passed to mkdir -p

usage() {
    echo "Usage: ${0##*/} [-f|-g|-h|-m <target>|-s|-S|-v] <source>" 1>&2
}

# Initial variables...
dirMethod=0 # Set default method of directory listing (find -d)
addSource=0 # Set default ouput path behaviour

# Command options handling with Bash getopts builtin
while getopts ":fghm:sSv" options; do
    case "${options}" in
        f) # use depth-first find method of directory listing
            dirMethod=0 # set again here if user sets both f and g
            ;;
        g) # Use extended globbing and sort method of directory listing
            dirMethod=1
            ;;
        h) # Help text
            echo "Leaf - generate shortest list of directories to (optionally)"
            echo "       fully recreate a directory structure from a given source"
            echo
            echo "Options"
            echo "======="
            usage
            echo
            echo "Directory listing method"
            echo "------------------------"
            echo "-f           Use find command with depth-first search [DEFAULT]"
            echo "-g           Use shell globbing method"
            echo
            echo "Output options"
            echo "--------------"
            echo "-m <target>  Create directory structure in <target> directory"
            echo "-v           Verbose output [use with -m option]"
            echo "-s           Output includes source directory"
            echo "-S           Output includes full given path of <source> directory"
            echo
            echo "Other options"
            echo "-------------"
            echo "-h           This help text"
            exit 0 # Exit script cleanly
            ;;
        m) # make directories in given location
            destinationRootDir="${OPTARG}"
            ;;
        s) # Include source directory as root of output paths/tree recreation
            addSource=1
            ;;
        S) # Include full source path as root of output paths/tree recreation
            addSource=2
            ;;
        v) # Verbose output if -m option given
            mdOpt="v"
            ;;
        *) # If no options...
            usage
            exit 1 # Exit script with an error
            ;;
    esac
done
shift $((OPTIND-1))

# Positional parameters handling - only one (<source>) expected
if (( $# == 1 )); then
    if [[ $1 == "/" ]]; then # Test to see if <source> is the root directory /
        (( dirMethod == 0 )) && sourceDir="${1}" || sourceDir=
            # Set sourceDir to '/' if using find command dir generation or null if bash globbing method
    else
        sourceDir="${1%/}" # Strip trailing /
    fi
else
    usage  # Show usage message and...
    exit 1 # Quit with an error
fi

# Generate full pre-filtered directory list depending on requested method
if (( dirMethod == 0 )); then # find command method
    dirList=$(find "${sourceDir}" -depth -type d 2>/dev/null | sed -e 's:^/::' -e '/^$/ ! s:$:/:')
        # find command with depth-first search should eliminate need to sort directories
        # sed -e 's:^/::' -e '/^$/ ! s:$:/:' - strip leading '/' if present and add '/'
        #                                      to all directories except root
else
    shopt -s nullglob globstar dotglob
    # nullglob - don't return search string if no match
    # globstar - allow ** globbing to descend into subdirectories. '**/' returns directories only
    # dotglob  - return hidden folders (ie. those beginning with '.')
    dirList=$(printf "%s\n" "${sourceDir}"/**/ | sed -e 's:^/::' | sort -r)
    # sort command required so filtering works correctly
fi

# Determine directory stripping string. ie. if given path/to/source[/] as the
# source directory (src), should the output be just that of the contents of src,
# src and its contents or the path/to/src and contents?
sourceDir="${sourceDir#/}"
case "${addSource}" in
    0) strip="${sourceDir}/";; # Set 'strip' to <source>
    1) [[ "${sourceDir}" =~ (\/?.+)\/.+$ ]] && strip="${BASH_REMATCH[1]}/" || strip="/"
       # To strip down to <source> only, check to see if matched by regex and only return matched part
       # If not found, behave like -S
       ;;
    2) strip="/";; # Set 'strip' to nothing but a forward slash
esac

# Main loop
# Feed the generated dirList into this while loop which is run line-by-line (ie. directory by directory)
while read -r dir;do
    if [[ "${dir}" != "${prev:0:${#dir}}" ]]; then
        # If current line is not contained within the previous line then that is a valid directory to display/create
        if [[ -v destinationRootDir ]]; then # If destinationRootDir is set (-m) then create directory in <target>
            mkdir -p${mdOpt} "${destinationRootDir%/}/${dir#$strip}"
            # -p - create intermediate directories if they don't exist. The filtered list means no unnecessary mkdir calls
            # if mdOpt is set, it is 'v', meaning mkdir will output each created directory path to stdin
            # ${dir#$strip} removes the set strip value from the line before it is displayed/created
        else
            echo "${dir#$strip}" # Same as above but no directories created. Displayed only, so -v ignored here
        fi
        prev="${dir}" # Set prev to this line before the loop iterates again and the next line passed to dir
    fi
done <<<"${dirList}" # This is a here string

A: This is still a loop, since it uses the branch command in sed:
find -depth -type d |sed 'h; :b; $b; N; /^\(.*\)\/.*\n\1$/ { g; bb }; $ {x; b}; P; D'

Based on a script in info sed (uniq work-alike).
Edit Here is the sed script broken out with comments (copied from info sed and modified):
# copy the pattern space to the hold space
h

# label for branch (goto) command
:b
# on the last line ($) goto the end of
# the script (b with no label), print and exit
$b
# append the next line to the pattern space (it now contains line1\nline2
N
# if the pattern space matches line1 with the last slash and whatever comes after
# it followed by a newline followed by a copy of the part before the last slash
# in other words line2 is different from line one with the last dir removed
# see below for the regex
/^\(.*\)\/.*\n\1$/ {
    # Undo the effect of
    # the n command by copying the hold space back to the pattern space
    g
    # branch to label b (so now line2 is playing the role of line1
    bb
}
# If the `N' command had added the last line, print and exit
# (if this is the last line then swap the hold space and pattern space
# and goto the end (b without a label)
$ { x; b }

# The lines are different; print the first and go
# back working on the second.
# print up to the first newline of the pattern space
P
# delete up to the first newline in the pattern space, the remainder, if any,
# will become line1, go to the top of the loop
D

Here is what the regex is doing:

*

*/ - start a pattern

*^ - matches the beginning of the line

*\( - start a capture group (back reference subexpression)

*.* - zero or more (*) of any character (.)

*\) - end capture group

*\/ - a slash (/) (escaped with \)

*.* - zero or more of any character

*\n - a newline

*\1 - a copy of the back reference (which in this case is whatever was between the beginning of the line and the last slash)

*$ - matches the end of the line

*/ - end the pattern

A: I think you can look at all the directories and then redirect the ouput and use xargs for counting the number files for each subdirectories, when there's no subdirectory ( xargs find SUBDIR -type d | wc -l ... something like that, i cannot test right now ) you've found a leaf.
This is still a loop though.

A: Try the following one-liner (tested on Linux & OS X):
find . -type d -execdir sh -c 'test -z "$(find "{}" -mindepth 1 -type d)" && echo $PWD/{}' \;

A: On most filesystems (not btrfs), the simple answer is:
find . -type d -links 2

In https://unix.stackexchange.com/questions/497185/how-to-find-only-directories-without-subdirectories there is a solution that works on btrfs, but it's unbearably ugly:
find . -type d \
    \( -exec sh -c 'find "$1" -mindepth 1 -maxdepth 1 -type d -print0 | grep -cz "^" >/dev/null 2>&1' _ {} \; -o -print \)

There's an alternative to find called rawhide (rh) that makes this much easier:
rh 'd && "[ `rh -red %S | wc -l` = 0 ]".sh'

A slightly shorter/faster version is:
rh 'd && "[ -z \"`rh -red %S`\" ]".sh'

The above commands search for directories and then list their sub-directories and only match when there are none (the first by counting the number of lines of output, and the second by checking if there is any output at all per directory).
If you don't need support for btrfs, it's more like find but still shorter:
rh 'd && nlink == 2'

For a version that works on all filesystems as efficiently as possible:
rh 'd && (nlink == 2 || nlink == 1 && "[ -z \"`rh -red %S`\" ]".sh)'

On normal (non-btrfs) filesystems, this will work without the need for any additional processes for each directory, but on btrfs, it will need them. This is probably best if you have a mix of different filesystems including btrfs.
Rawhide (rh) is available from https://raf.org/rawhide or https://github.com/raforg/rawhide. It works at least on Linux, FreeBSD, OpenBSD, NetBSD, Solaris, macOS, and Cygwin.
Disclaimer: I am the current author of rawhide


text:
Q: How to Fetch and Display an Image from an express backend server to a React Native frontend? Searching this same topic i`ve found another question:
How to Fetch and Display an Image from an express backend server to a React js frontend?
and in the comments has this:"Convert your blob to File var file = new File( res.data, { type: "image/jpeg" } ); var imageUrl = URL.createObjectURL(file); Then use this imageUrl ". So I've done it similar to his code and got error.
fetchImages = () => {
 const imageName = 'Vinicius_0-1577392361334.jpg';
 api.get(`/image/${imageName}`)
  .then(res => {
    var file = new File(res.data, { type: 'image/jpg' });
    var imageURL = URL.createObjectURL(file);
    return (
      <Image source={imageURL} />
    )
  }).catch((err) => {
    console.log(err)
  });}

routes.get('/image/:file', (req,res) =>{
  let file = req.params.file;
  let fileLocation = path.join(__dirname, '..', '..', 'backend/uploads/', file);

  res.sendFile(`${fileLocation}`);
});

         .....
<View style={styles.viewBotao}>
     {this.fetchImages()}
         .....

Console OutPut

A: Try to assign you imageURL to state variable
constructor(props) {
    super(props);
    this.state = {
        imageURL: ''
    }
}

fetchImages = () => {
    ...
        var imageURL = URL.createObjectURL(file);
        this.setState({ imageURL });
    ...
}

<View style={styles.viewBotao}>
     <Image source={this.state.imageURL} />
</View>


text:
Q: numeric palindrome with leading zeros c++ I wanted to solve a problem, yet my code passes only 8 out of 10 tests. The problem is to determine whether a number 1<=N<=10^9 can be a numeric polyndrome. The thing is, you may add as many leading zeros as it requires to make a non-polyndrome into a polyndrome. If it is possible, or a number is polyndrome, the result must be yes, otehrwise no. For example, 2020 is not a polyndrome, but If I add a leading zero, it becomes 02020, which is a polyndrome. One main problem of my code is that i don't know the number of leading zeros needed to make a number a polyndrome. Here's my code:
#include <cstdio>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    string N, N2;
    cin >> N;
    N2 = N;
    reverse(N.begin(), N.end());
    if (N2 == N) {
        cout << "Yes" << "\n";
        return 0;
    }
    else {
        N2 = "0" + N2;
        N = N + "0";
        if (N != N2) {
            cout << "No" << "\n";
            return 0;
        }
        else {
            cout << "Yes";
            return 0;
        }
    }
}

I would be grateful for any help to enhance my code!
edit: I have to add leading zeros if it can turn a number into a polyndrome, that's the main thing

A: I would do something like:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    string n;
    cin>>n;
    string m =n;
    reverse(n.begin(),n.end());
    if(n==m){
        cout<<"Yes"<<endl;
        return 0;
 }
  int count=0;
  int k=m.length();
 for(int i=1; i<=k;i++){
     if(m[i]=='0'){
         count+=1;
     }
 }

 for(int i=1;i<=count;i++){
     m='0'+m;
 }
 string m2=m;
 reverse(m.begin(), m.end());
 if (m2 == m)
 {
     cout << "Yes" << endl;
     return 0;
}
else{
    cout << "No" << endl;
    return 0;
}
}

A: Just to be complete, I will show you the answer based on the comments.
It is the same, if you add 0es to the beginning or remove them from the end.
If you have 2020, you can either add one leading 0 --> 02020 or remove a trailing 0 -> 202. Result is the same.
So, the algorithm will be.

*

*Search from the right end for the first character that is not '0'

*Build a pair forward and a pair reverse iterators, based on the iterator, found by `std::find

*Compare temporary created strings, build from forward and reverse iterators

*Output comparison result

Very simple example code:
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main() {
    if (std::string numberAsString{}; std::cin >> numberAsString) {

        std::string::reverse_iterator newEnd = std::find_if(numberAsString.rbegin(), numberAsString.rend(), [](const char c) {return c != '0'; });

        std::cout << (std::string(numberAsString.begin(), newEnd.base()) == std::string(newEnd, numberAsString.rend()) ? "Yes\n" : "No\n");
    }
}

A: I only changed in main else part of your code.
1. Now understand if some numerical string is not palindrome and you are going to make it palindrome by adding leading 0's then it must end with 0's.
For Ex. 100 is not palindrome but you can make it by 00100 it possible because two 0's present at end.
same with 10 -> 010
2. some numbers which are ends with 0's and not palindromes but we can make them by adding leading 0's
10, 20, 30.....90  -> (respective palindrome) 010,020,.....090
100, 110, 200, 220,.....900, 990  -> (respective palindrome) 00100, 0110, 00200, 0220.....00900, 0990
3. some numbers which are  ends with 0's and not palindromes and we can't make them by adding leading 0's
120, 130...190
210, 230, 240,....290
.
.
.
11010
4.
Now if you see carefully the numbers which we can make palindrome you get that to be able to do so we have to add exact number of 0's at starting as present at the end. if you pause for minute and think then you get logical sense too.
5.
Now I am creating condition to right code on above analysis. I will talk about just else part
i> So I will check first that how many 0's present at end of number(while loop). at least one 0's must be present.
ii> Then I am adding as many leading 0's present at end.( for loop).
iii> Then storing N2 in N3 so I can reverse and check palindrome become or not because all numbers end with 0's do not become palindromes.
Code
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;

int main()
{
    string N, N2;
    cin >> N;
    N2 = N;
    reverse(N.begin(), N.end());
    cout<<N<<" "<<N2<<"\n";

    if (N2 == N)
    {
        cout << "Yes" << "\n";
        return 0;
    }
    else
    {

        int k=N2.length(), count=0, i=1;

        while(N2[k-i]=='0')
        {
            count++;
            i++;
        }
        if(count==0)
        {
            cout<<"No";
            return 0;
        }
        for(int i=1; i<=count; i++)
        {
            N2="0" + N2;
        }
        string N3=N2;
        reverse(N2.begin(), N2.end());
        cout<<N3<<" "<<N2<<"\n";

        if (N3 != N2)
        {
            cout << "No" << "\n";
            return 0;
        }
        else
        {
            cout << "Yes";
            return 0;
        }

    }
}

Also just note that you added <cstdio> two times even it didn't required one time  also. Sometime if you include same header file twice it might cause error. Also there is no requirement of <cmath> library file. By the way you didn't include <string> library file might be in some cases your program run quite well without including it but it is not standard practise.


text:
Q: Why is "result := char variable" getting me access violation? I created a function that has a Char represented by a variable named fsinal:
type
  TCalculo = class(TObject)
  private
    fnumero1 : integer;
    fnumero2 : integer;
    fsinal   : char;
  public

I then created a method to get this Char:
function getSinal   : char;

function TCalculo.getSinal: char;
begin
  result := fsinal;
end;

Whenever I rum my program and press any button, I receive an error

access violation at address 005FD704, read of address 0000000C:

What am I doing wrong?
Whole code:
https://github.com/murillojndem/Calculadora/blob/master/Unit1.pas

A: An Access Violation error near address $00000000 usually means you are accessing memory via a nil pointer.
In this case, address $0000000C is 12 bytes from address $00000000.  The TCalculo.getSinal() method is accessing the fsinal member, which is at an offset of 12 bytes from the start of the TCalculo class (offset 0 is a hidden pointer to TCalculo's vtable, offset 4 is the fnumero1 member, offset 8 is the fnumero2 member, and finally offset 12 is the fsinal member).
result := fsinal; is the same as result := Self.fsinal;, where the compiler adds the offset of fsinal (12) to the address that Self is pointing at, and then dereferences the resulting address to access the value of fsinal.  In your case, you are calling TCalculo.getSinal() via a nil pointer to a TCalculo object, so the method's Self pointer is nil (0), thus dereferencing the address of fsinal (0+12) causes an AV error.
In your TForm code, all of your TButton.OnClick handlers are calling getSinal() on a global calculo variable that is never being initialized to point at a valid TCalculo object.  Since the calculo variable is declared in global memory, it is default-initialized to nil at program startup.
type
  TCalculo = class(TObject)
    ...
  end;

var
  Form1  : TForm1;
  calculo: TCalculo; // <-- initialized to nil here!

...

procedure TForm1.Button0Click(Sender: TObject);
begin
  if calculo.getSinal = 'a' then // <-- calculo is still nil here!
  ...
end;

... and so on...

You need to add a call to TCalculo.Create(), either in the TForm.OnCreate event (and conversely, Free the object in the TForm.OnDestroy event), eg:
procedure TForm1.FormCreate(Sender: TObject);
begin
  calculo := TCalculo.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  calculo.Free;
end;

Or, use the unit's initialization section instead (and conversely, the finalization section), eg:
implementation

...

initialization
  calculo := TCalculo.Create;
finalization
  calculo.Free;

end.


text:
Q: Информация по Битрикс Какую информацию лучше всего собрать по Битриксу для разработчика, что работает в основном с 1С, перед тем как дать ему задание для их интеграции?

A: Битрикс-разработчик, должен обладать информацией (в том или ином объёме) по всем курсам. Для интеграции с 1С советую посмотреть курсы:

*

*Администратор. Базовый (Понимание инфоблоков)

*Администратор. Бизнес

*Разработчик Bitrix Framework

Лучше всего, чтобы интеграцию выполняли 2 специалиста - 1С-программист и разработчик по Битрикс. Если всё должен выполнить 1 программист, то быстрее и проще начать с практики:

*

*Создать бэкап 1С;

*Поднять тестовую/локальную копию сайта;

*Настроить стандартную интеграцию по официальной документации.
А дальше уже решать вопросы по мере их появления.

Курсы: http://dev.1c-bitrix.ru/learning/index.php
Интеграция с 1С: http://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=42&CHAPTER_ID=1158
Протокол обмена с сайтом: http://v8.1c.ru/edi/edi_stnd/131/
Также у Битрикс есть замечательная бесплатная служба поддержки, где гарантированно отвечают на заданный вопрос в установленные сроки и помогают их решить.
http://www.1c-bitrix.ru/support/customers/ticket.php?show_wizard=Y


text:
Q: Rails - delete_all or destroy_all not working on production server but working fine in development server I have a rails app where I need to periodically delete search logs from a model. For this I am using a rake task with the syntax model.destroy_all, it is working fine in development server. However, nothing seems to be happening on production server.
Both development and production servers are using Ubuntu Server 10.04, Rails 3.0.7, Mysql Database. Did you face similar situation before?
Below is the rake task code:
task :cleansed_log => :environment do
raw_logs = Searchlog.find_by_sql("SELECT q from searchlogs")
flag = 0
pres_log, prev_log = "", ""
if raw_logs.count > 1
  raw_logs.each do |raw_log|

    if flag == 0
      prev_log = raw_log.q
      flag = 1

    else

      pres_log = raw_log.q
      if pres_log =~ /#{prev_log}/
        prev_log = pres_log

      else
        @cleansedlog = Cleansedlog.new(:keyword => prev_log)
        @cleansedlog.save

        prev_log = pres_log
      end

    end
  end
  @cleansedlog = Cleansedlog.new(:keyword => pres_log)
  @cleansedlog.save

  Searchlog.destroy_all

end

end

Below is the cron job which calls above rake task:
# Begin Whenever generated tasks for: cleansedlog
# 0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd       /var/www/prodsite//releases/20110715035538 && RAILS_ENV=production rake cleansed_log -- silent >> /work/saptcodes/cron.log 2>&1'
# End Whenever generated tasks for: cleansedlog

A: I am not sure, but do you pass RAILS_ENV option to you rake task?
For example:
rake logs:destroy RAILS_ENV='production'

A: Can you try with
model.delete_all

Careful since this will not honor callbacks, dependent associations and goes straight to the database.
I have encountered similar behavior sometimes with destroy_all, especially in migrations.


text:
Q: Mac OS 10.7 Lion - Can't open text file at login (permission denied) Here's the main problem: I just installed Mac OS 10.7 (Lion) and created a new Administrator user account (called "test").  Then I used TextEdit to creat a text file called test.rtf.  I dragged test.rtf onto the dock and checked off the "Open at Login" option.
When I log out and log back in, the file does not open at login, but rather, I get a dialog that says: The document "test.rtf" could not be opened.  You don't have permission.
ls -la on the terminal outputs the following info for the file:
-rw-r--r--@ 1 test staff Apr 23 11:22 /Users/test/Desktop/test.rtf

I even tried chmod 777 on the file, and it still doesn't open at login.  Same error dialog.
I checked system.log and saw this:

sandboxd[361] ([356]): TextEdit(356) deny file-read-data /Users/test/Desktop.rtf

I also tried repairing permissions (while logged in and also while booting up off of the Command+R recovery boot) and that didn't solve the problem either.

Extra background info:
Yesterday, I backed up my Mac OS 10.6 (Snow Leopard) User directory onto an external hard drive.  Next, I wiped out the contents of my hard drive and did a fresh install of OS 10.7 (Lion).
When I copied my backed up files and folders back onto my newly installed OS, I had some permission issues.  Directories like Movies and Documents weren't readable, so I used chmod to change the permissions appropriately.  Then everything seemed fine.
For good measure, I also chowned all of those files using chown -R MyUserName:staff.
Note: The new user account that I created in Lion had the same name as my user account from Snow Leopard before I backed up my files and erased the hard drive.
The problems that I described in the above section with the "test" user account also occurred with my regular user account, but I figured I'd create a fresh account to see if it was just a permissions issue that stemmed from the copying over of my old files.

A: It looks like it's related to the application sandbox implementation in OS X Lion.
I can reproduce it with Preview and TextEdit.

Possible workaround:

*

*Assign a non-sandboxed program (e.g. TextMate) to open the document. You can just change the program association for one text file in its Get Info dialog.

*Don't open the document upon login, but instead e.g. an Automator application that opens the file. You don't need to keep it in the Dock to do this either.

A: The workaround I used, having had the same problem, was to have TexTEdit opened at Login and use Lion's ability to remember open documents.
I realize this will break if someone uses TextEdit, but in my case the document is a warning saying the wrong OS of a dual-boot system has been started up, and advising the user to restart using the other partition.

A: This was driving me crazy after I upgraded to Lion. I have a text file of bills and due dates that I've had auto-open at login for years.
My solution was to use an app called DelayedLauncher that opens the file in TextEdit several seconds after login. Essentially, it is the same solution as having Automator open the file.
I am now running Mountain Lion. I have not tested whether the behavior is the same in 10.8, but I suspect it is.


text:
Q: Run script for many profile path at once in global mapper This code when I run it in Global Mapper, that create a .xyz file of profile path between two points
GENERATE_PATH_PROFILE \
FILENAME="C:\Users\Bella\Desktop\ProfPath.xyz" \
ELEV_UNITS=METERS \
POINT_SPACING=10.0 \
START_POS=765287.9,3813969.2 \
END_POS=771481.8,3815738.6 \
SAVE_DIST_Z_FILE=YES \

1- If I would to create many segments at once, all the segments share the same origin point, how to do it in script, so I can export it all in a file?
2- Could I use the geographic coordinates in START_POS and END_POS instead of utm projection?

A: What version of Global Mapper are you using?
For part 2, try entering coordinates in degrees with optional N,S,E,or W appended.
Washington DC, for example is -77.0364 W,38.8951 N
I think you can also put in other lat/log formats such as
38° 49' 45.9768'' N,  76° 58' 39.1044'' W
For part 1, I would highly suggest contacting Global Mapper support group.


text:
Q: Harmon.ie sidebar and ribbon is missing One of my users has suddenly lost the Outlook sidebar and the harmon.ie ribbon band is replaced with another icon with the words "Save to Sharepoint" but it is deactivated (grey). Also there is no arrow to see options and no other choices available. We tried to uninstall and reinstall. Nothing changes. How do we get back the Outlook sidebar?
/Susannevj

A: -In order to rule out any plugin conflict would you please check whether any additional plugins are enabled in Outlook - if so, disable (temporarily) all other add-ins except harmon.ie To disable Outlook add-ins
•   Go under File -> Options -> Add-ins -> Manage COM Add-ins and click Go...
•   Deselect all add-ins except harmon.ie and click OK.
Restart Outlook - and go back under File -> Options -> Add-ins to verify that harmon.ie is the only add-in listed in the Active application add-ins section.
 Then please run the following recovery procedure:
-Please stop Outlook.
-Uninstall harmon.ie from control panel, program feature
-Delete all dirs.  C:\Users[user_name]\AppData\Local\Microsoft_Corporation\harmony_Path_pzllr20oqrnqmrstb3lfbn4njpshdzry (path can slightly change)
-Delete C:\Users[user_name]\AppData\Local\Mainsoft
-Register the registry key at: ftp://free:free@ftpus.mainsoft.com/Clean%20Mainsoft%20Reg_New.reg.zip
-Register the PreferredCLRversion registry key at ftp://free:free@ftpus.mainsoft.com/PreferredCLRVersion4.0.zip
-Reinstall latest harmon.ie version from the below link
ftp://free:free@ftpus.mainsoft.com/HarmonieSharePointSetup.x86.msi
-Start Outlook


text:
Q: Stumped on Extended Multiplication for LC-3 Assembly I'm trying to get Extended Multiplication to work on the LC-3. Relevant excerpts from my code:
    .ORIG   x3000

; Calculate AB = A x B
    LEA R6, ARGS
    LD  R0, B
    STR R0, R6, #0  ; Store B into Multiplier address of ARGS
    JSR PRINT
    LD  R0, A
    STR R0, R6, #1  ; Store A into Multiplicand address of ARGS
    JSR PRINT
    LEA R0, AB      ; R0 <- starting address of AB
    STR R0, R6, #2  ; Store starting address of AB into Product word of ARGS

    JSR XMULT

    ; DID WE LOAD THE PRODUCT PROPERLY?

    ; THIS SHOULD PRINT THE LEAST SIGNIFICANT BITS OF PRODUCT

    LDR R0, R0, #0
    JSR PRINT

    ; THIS SHOULD PRINT THE MOST SIGNIFICANT BITS OF PRODUCT

    LEA R0, AB
    ADD R0, R0, #1
    LDR R0, R0, #0
    JSR PRINT

; Calculate XY = X * Y

    TRAP    x25
;   Test Data
A   .FILL   x0010
B   .FILL   x00AB
X   .FILL   x1234
Y   .FILL   xABCD
AB  .BLKW   2
XY  .BLKW   2

;   Argument List
ARGS    .BLKW   1   ;Multiplier   (value)
    .BLKW   1   ;Multiplicand (value)
    .BLKW   1   ;Product      (address)
;**********************************************************

 XMULT  ;Extended Multiplication
    ;Arguments located by R6
    ;   multiplier (value)
    ;   multiplicand (value)
    ;   product (address)

    ST  R7, XMU7    ;Save Registers
    ST  R0, XMU0    ; TEMP register (for storing temp results and passing to RightShift subroutine)
    ST  R1, XMU1    ; Will store MPR (Multiplier)
    ST  R2, XMU2    ; Will store MND (Multiplicand)
    ST  R3, XMU3    ; Will store ACC (Accumulator)
    ST  R4, XMU4    ; Will serve as a COUNTER for loop
    ST  R5, XMU5    ; Will store BITMASK for testing
    ST  R6, XMU6    ; Argument list

    LDR R1, R6, #0  ; Store MPR into R1 (Multiplier is first item in the argument list pointed to by R6)
    LDR R2, R6, #1  ; Store MND into R2 (Multiplicand is second item)
    AND R3, R3, #0  ; ACC <- 0
    LD  R4, COUNTER ; Set counter
    LD  R5, BITMASK ; Set R5 to 0000 0000 0000 0001, the bitmask needed to test MPR[0]

    ; Counter and operands ready - now we can start the loop

MULOOP  ; MUltiplication LOOP

    AND R0, R5, R1  ; Test MPR[0]
    BRz ELSE    ; Branch if MPR[0] isn't set
    ADD R3, R3, R2  ; ACC <- ACC + MND

ELSE
    AND R0, R0, #0  ; Clear R0
    ADD R0, R3, #0  ; R0 <- ACC
    JSR SHIFT       ; ShiftRight(ACC)
    ADD R3, R0, #0  ; R3 <- Right-shifted ACC
    ADD R0, R1, #0  ; R0 <- MPR
    JSR SHIFT       ; ShiftRight(MPR)
    ADD R1, R0, #0  ; R1 <- Right-shifted MPR
    ADD R4, R4, #-1 ; Decrement Counter

    BRp MULOOP      ; If Counter > 0, branch to beginning of loop

MULOOPEND   ; MUltiplication LOOP ends here

; Write results to memory addresses (OUT-parameter segment)

    LDR R0, R6, #2  ; R0 <- Product(address), least significant digit
    STR R1, R0, #0  ; Right-shifted MPR goes in the lower address word
    STR R3, R0, #1  ; Right-shifted ACC goes in the higher address word

    LD  R7, XMU7    ; Restore Registers
    LD  R0, XMU0
    LD  R1, XMU1
    LD  R2, XMU2
    LD  R3, XMU3
    LD  R4, XMU4
    LD  R5, XMU5
    LD  R6, XMU6
    RET

XMU0    .BLKW   1
XMU1    .BLKW   1
XMU2    .BLKW   1
XMU3    .BLKW   1
XMU4    .BLKW   1
XMU5    .BLKW   1
XMU6    .BLKW   1
XMU7    .BLKW   1

; Data

COUNTER .FILL   x0010
BITMASK .FILL   x0001

Please note that the subroutines PRINT and SHIFT simply print the contents of R0 to the console in bit form and execute a right-shift on the contents of R0, respectively. Please assume these are working correctly (I've tested them multiple times and they are).
So, the code is supposed to calculate the double-word product of two N-bit unsigned integers. Of course, the product is stored in two contiguous words, with the "least significant" bits being stored at the lower-address word.
In the XMULT subroutine, I use R3 (ACC for ACCumulator) and R1 (MPR for MultiPlieR) to store the "most significant" and "least significant" parts of the product, respectively. These are calculated using the standard General Multiplication Algorithm
MPR <- Multiplier
MND <- Multiplicand
ACC <- 0

for (int k = 1; k <= N; k++)
{
if (MPR[0])    // Test MPR[0]
  ACC <- ACC + MND

ShiftRight(ACC:MPR)
}

So that by the end of the loop, the double-word product is available in ACC:MPR.
ACC appears to store the correct value when the loop terminates, but MPR doesn't. For example, taking the values X and Y, consulting a bit multiplication calculator shows that x1234 * xABCD = xC374FA4
Now, if I run my code and multiply X and Y, once the multiplication loop terminates, ACC (the most significant apart of the product) stores b0000 1100 0011 0111 = x0C37 , so this part seems to be correct. However, MPR stores zero (b0000 0000 0000 0000 = x0000).
I've been using breakpoints and the Step Into function on my LC-3 simulator to go through my code step by step for the past few hours to try and figure out why this is happening, and the only thing I've noticed is that the Logical right shifts that occur during the multiplication loop are reducing MPR to 0 before the loop terminates (ACC gets the right value, though).
As I said, all the subroutines (SHIFT for logical right shift is the most important of them) are working correctly, and it SEEMS like MULOOP implements the General Multiplication Algorithm properly, so why is MPR getting zeroed out?
What's even more confusing is that I tried multiplying x0100 and x0200 (just to try two simple numbers), and I got the correct answer: x0002 was stored in ACC and x0000 was stored in MPR, making the product x20000 (since ACC is the most significant part of the product and MPR is the least significant).
I don't know what's wrong. I've been spinning my wheels trying all sorts of things for hours now:

*

*I changed the order of the operands (swapped multiplier and multiplicand), which of course doesn't matter for multiplication, but I was desperate

*I tried a totally different logical right SHIFT implementation that was also correct. As expected, the results were exactly the same as with the original one

*I've changed the value of the loop Counter, trying to see if less iterations of the loop result in MPR NOT geting zeroed out before the loop terminates. Answer: it does, but as expected, this results in ACC not storing the correct value at loop termination anymore. Also, MPR doesn't store the correct value either - it just doesn't end up being zero (if I use a smaller counter).
I'm legitimately stumped. Is it a problem with my Multiplication loop's implementation, or is there something else wrong? I don't even know where to look for errors anymore.

A: Quick question:
Does the PRINT procedure preserve R6 ? If not you would need to reload it for the 2nd and 3rd arguments with extra LEA R6, ARGS instructions.

You don't actually ShiftRight(ACC:MPR)
You ShiftRight(ACC) ShiftRight(MPR)

ADD R0, R3, #0  ; R0 <- ACC
JSR SHIFT       ; ShiftRight(ACC)
ADD R3, R0, #0  ; R3 <- Right-shifted ACC
ADD R0, R1, #0  ; R0 <- MPR
JSR SHIFT       ; ShiftRight(MPR)
ADD R1, R0, #0  ; R1 <- Right-shifted MPR

In this part of your program you perform 2 completely independant operations. You shift the word in R3 (ACC) to the right and you shift the word in R1 (MPR) to the right.
You're forgetting however that ACC:MPR is supposed to be a 32-bit quantity. The bit that got shifted out on the right side of the ACC must get shifted in on the left side of MPR. Since this is not happening, you end up with an empty MPR.
What you should do:
If Bit(ACC,0) = 0
    ShiftRight(ACC)
    ShiftRight(MPR)
Else
    ShiftRight(ACC)
    ShiftRight(MPR)
    Add(MPR,32768)
Endif


text:
Q: Securing a password by verifying encrypted random string I want to make an application that saves some encrypted configuration data in a XML file. The idea is that I want the user to set a password and with it to encrypt my data.
If I have the password: 'mypass' and the data: 'mydata'.
When a user defines the password, my app will generate a random string:'myRandomString'. In my XML file I will save:

*

*'myRandomString'

*'f6354a1eb2a1deb2' -witch is  'myRandomString' encrypted
with 'mypass'

*'69380d137534519' -witch is  'mydata' encrypted
with 'mypass'

When the users logs in, I will compare 'myRandomString' with the decrypted version of 'f6354a1eb2a1deb2'. If they are equal then my pass is OK and I can decrypt 'mydata'.
From AES key finding from encrypted and plaintext data I know that this method is prety secure but I want to know if there are better methods to secure the password withouth using 'Protected Configuration'

A: You should instead use an HMAC in this scenario.  It is a keyed-hash function.
Even if the random string has not been modified, you cannot assume that the password hasn't either.
Using an HMAC you can be aware of any changes made to the entire file since it was created by your application.
Build your XML file with the encrypted fields, feed it through an HMAC and then append the result.  You can do the same when you use the file again and if the HMACs aren't equal, the file has been changed.
It wouldn't hurt to use a time-safe comparison for checking the HMACs


text:
Q: Page show - Index of - instead of content I have a site running just fine, but since shortly my support page stopped working. Whenever I link to it, it shows me a blank page with the text index of /support instead of the content that should be loaded.
My index.php is as followed
<?php
    require_once ('inc/db/dbControl.php');
    require_once ('inc/db/functionControl.php');
    include_once ("inc/page/header.php");
    include_once ("inc/elements/body.php");
    if (!empty($_GET['p'])){
        if($_GET['p'] == "admin"){
        }else{
            include_once ("inc/page/navigation.html");
        }
    }else{
        include_once ("inc/page/navigation.html");
    }
    include_once ("inc/page/pagepicker.php");
    if (!empty($_GET['p'])){
        if($_GET['p'] == "admin"){
        }else{
            include_once ("inc/page/footer.html");
        }
    }else{
        include_once ("inc/page/footer.html");
    }
    include_once ("inc/elements/body_close.php");
    include_once ("inc/page/scripts.php");
?>

In my index.php is a pagepicker, that runs as followed
if (!empty($_GET['p'])){
    $pages_dir = 'inc/content';
    $pages = scandir($pages_dir, 0);
    unset($pages[0], $pages[1]);

    $p = $_GET['p'];

    if(in_array($p.'.inc.php', $pages)){
        include($pages_dir.'/'.$p.'.inc.php');
    }
    else
    {
            echo '
404 Page not found. Deze website is momenteel in aanbouw. Kom later nog eens terug of neem contact met ons op via info@jellyfishwebdesign.nl
';
    }
}else{
    include('inc/content/home.inc.php');
}

It works for every page, except for the support page which contains the following.
<?php
    include_once ("inc/elements/support_front.html");
    include_once ("inc/elements/video.php");
    echo '
';
        include_once  ("inc/elements/support_algemeen.html");
    echo '
';
?>

Since there is no folder called support (this is done via rewritting URL), I have no clue what is going on here.
The htacces file is this
    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([A-Za-z0-9-]+)$ index.php?p=$1 [L]
    RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$  index.php?p=$1&t=$2 [L]

For the example online, surft to the website and hit the support icons. How can I solve this?
edit
When I check console, it tries to load the page but in 2 instances. Once as jellyfishwebdesign/support and once as jellyfishwebdesign/support/ ... the last one is the one that gets accepted, the other gives me in the headers this:
Remote Address: ------- blanked
Request URL:http://jellyfishwebdesign.nl/support
Request Method:GET
Status Code:301 Moved Permanently (from cache)
Request Headers
Provisional headers are shown
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer:http://jellyfishwebdesign.nl/home
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Response Headers
Content-Length:245
Content-Type:text/html; charset=iso-8859-1
Date:Sun, 14 Dec 2014 21:47:45 GMT
Location:http://jellyfishwebdesign.nl/support/
Server:Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips mod_bwlimited/1.4


text:
Q: Intercept Blobstore Request and Save responded File I want to intercept a request to blobservice on my Android application
to url looks like that:
http://foo.appspot.com/simpleams/blobservice?blob-key=AMIfv94NAAoxn1oi_ySWYSiNF3MforFVI6SvDi_NeF0rjNr_QW
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if(url.contains("blobservice")) {
            return getAppWebResourceResponseFromBlobstore(view, url);
        } else {
            return super.shouldInterceptRequest(view, url);
        }

    }

private WebResourceResponse getAppWebResourceResponseFromBlobstore(WebView view, String url) {
    try {
        // TODO:
                    return file from local data or download it from
                    blob service, save it and return it...
    } catch (IOException e) {
        return null;
    }
}

How can i make the request to the server and save the file locally?

A: I found the solution by my self and want to share it with you:
    private WebResourceResponse getAppWebResourceResponseFromBlobstore(WebView view, String url) {

        int slashIndex = url.lastIndexOf("blobservice?blob-key=");

        String key;
        key = url.substring(slashIndex + "blobservice?blob-key=".length());

        System.out.println(key);
                BlobstoreManager m = new BlobstoreManager(ctx, url);

        return m.getBlob(key);

    }

public class BlobstoreManager{

    Context mContext;
    String url;

    public BlobstoreManager(Context c, String url) {

        this.url = url;
        this.mContext = c;

    }

    public WebResourceResponse getBlob(String key) {

        String path =  key;
        File file = mContext.getFileStreamPath(key);
        if(file.exists()) {
             try {
                 System.out.println("Response from Blob");
                return new WebResourceResponse("", "",mContext.openFileInput(path));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            try {

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(new HttpGet(url));
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    FileOutputStream output = mContext.openFileOutput(path, Context.MODE_PRIVATE);

                    response.getEntity().writeTo(output);

                    output.flush();
                    output.close();

                } else{
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }

             System.out.println("Save new Blob");
                return new WebResourceResponse("", "",mContext.openFileInput(path));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

}


text:
Q: Naming a service changes dependency injection behavior in Symfony I have a factory service class which needs access to Symfony´s (v6.0.2) service_container and is specified in the services.yaml as follows:
App\Service\SomeService:
    public: true
    arguments: ['%some_arguments%']
    calls:
        - [ setContainer, [ '@service_container' ] ]

It works fine and I can access the service container and all the other injected arguments from within my service as desired.
However, if I change the service definition into a named service like this - without changing anything else:
app.some_service:
    class: App\Service\SomeService
    public: true
    arguments: ['%some_arguments%']
    calls:
        - [ setContainer, [ '@service_container' ] ]

I still have access to the injected arguments ("%some_arguments%"), but the service container suddenly becomes null.
I would expect the behavior of the dependency injection to be the same - regardless of whether I use a named service or not.
Does the DI behavior change as soon as I give my service a name or do I need to take another approach if I want to give my service a name?


text:
Q: How should I call the superclass's custom initialiser, when I use a custom one for my subclass? I'm learning Objective-C and I don't clearly understand what is the best way to call superclass' custom initializer, while defining one in its subclass.
Here is my class' (superclass) custom initializer:
-(id) initWithWidth:(int)w andHeight:(int)h {
    self = [super init];

    if (self) {
        [self setWidth:w andHeight:h];
    }
    return self;
}

-(instancetype) init {
    return [self initWithWidth:0 andHeight:0];
}

Here I call its superclass' (NSObject) initializer and assign it to self. After checking that self is not nil, I call a method defined in the class. After that, assuming that my custom initializer is a designated one, I override the standard init.
Now, I create a subclass of that class. The subclass also has a custom initializer. Here it is:
-(id) initWithSide:(int)side {
    self = [super initWithWidth:side andHeight:side];

    if (self) {
        [self setSide: side];
    }
    return self;
}

-(instancetype) init {
    return [self initWithSide:0];
}

The logic is the same (again, it calls a custom method defined inside the class).
The problem is, I'm not quite sure what is the right way of calling its superclass' initializer (I still should call it, right?). In forums I've seen that some people don't call it at all, and that confuses me.
Should I call the designated initializer of the superclass or don't call it at all. If you could explain me how this works and the right choice in this case (or best practices, maybe), I would appreciate your help.


text:
Q: Web page stripped away from "layout" after adding paging through "PagedList.Mvc" I wanted to add paging to my website so I installed the "PagedList.Mvc"
then I made some changes to model like for example changing the type from IEnumerable to IPagedList :
 public IPagedList <Product> Products.

but I don't think changing model property has anything to do with the problem of layout disappearance.
And in controller part, I just added some properties to send through ViewModel to "Index" page, which I don't think has anything to do with the main problem.
i also added some
 and
 elements to the "Index" page which i don't think it has anything to do with layout problem since its universal to all pages.
I didn't touch the _layout.cshtml page :
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

.

            <button type="button" class="navbar-toggle" data-
 toggle="collapse" data-target=".navbar-collapse">

            </button>
            @Html.ActionLink("Application name", "Index", "Home", new { area
   = "" }, new { @class = "navbar-brand" })

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Shop by Category", "Index",
    "Categories")

@Html.ActionLink("View All Our Products", "Index",
    "Products")

            @using (Html.BeginForm("Index", "Products", FormMethod.Get, new
    @class = "navbar-form navbar-left"}))
            {

                    @Html.TextBox("Search",null,new {@class="form-
    control",@placeholder="Search Products"})

                <button type="submit" class="btn btn-default">Submit</button>
            }
            @Html.Partial("_LoginPartial")

    @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

the layout also is mentioned in _ViewStart.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

but at the end what could be the reason that index page is looking like this, stripped away from menu, links, search box ...

i'm sure the link between "_layout page" and "views" is broken , but which factors beside  @RenderBody( which already is there) are involved, I don't know.
btw. in the controller, I removed all viewbag and I'm using ViewModel , could it be a reason?


text:
Q: Tensorflow object detection : Using transfer learning on local running From Tensorflow docs, we can use transfer learning for object detection when you run from cloud. Also, can we using transfer-learning for running locally ? i see that we have a doc about running on local but i can not find any documents that write about transfer learning when run on local machine . I expected it in pipeline but i can not find it. So how can we config transfer learning on running locally ?

A: You are correct. You can use transfer learning when running locally.
The steps are similar to the instruction on running pets on google cloud, but your training config should reference your local file system instead of a path on GCS. In particular, you need to configure the train_config.fine_tune_checkpoint field to point to the unzipped checkpoint.
See the sample resnet101 config for more details. You should only have to change the PATH_TO_BE_CONFIGURED strings to point to the correct value.


text:
Q: What prevents a race condition on a lock? I understand the basics of what data races are, and how locks/mutexes/semaphores  help prevent them. But what happens if you have a "race condition" on the lock itself? For example, two different threads, perhaps in the same application, but running on different processors, try to acquire a lock at the exact same time.
What happens then? What is done to prevent that? Is it impossible, or just plain unlikely? Or is it a real race condition waiting to happen?

A:
Is it impossible, or just plain unlikely?

Impossible. It can be implemented in different ways, e.g., via the Compare-and-swap where the hardware guarantees sequential execution. It can get a bit complicated in presence of multiple cores or even multiple sockets and needs a complicated protocol between the cores, but this is all taken care of.

A: Simply put the code to get into the critical section is specially designed so a race condition won't violate the mutual exclusion.
Most of the time atomic compare and set loops are used that execute at the hardware level
while(!CompareAndSet(&lock, false, true));//busy loop won't continue until THIS thread has set the lock to true
//critical section
CompareAndSet(&lock, true, false);

In absence of that there are well studied software solutions to enable mutual exclusion.

A: Study the concept of atomic "Test and Set" operations.
Essentially the operation cannot be divided - it is not possible for two things to do it at exactly the same time. It will check a value, set it if it is clear, and return the value as it was when test.  In a lock operation, the result will always be "lock == TRUE" after a test-and-set, the only difference is was it set or not at the start.
At the micro code level in a single core processor, this is one indivisible instruction, and is easy to implement. With multiple and multicore processors, it becomes harder, but as programmers we have no need to worry about it, as it is designed to work by the really smart guys who do the silicon.  Essentially they do the same thing - make an atomic instruction that a fancy version of test-and-set

A: It is not possible that two (or more) threads acquire lock on the same time. There are few types of synchronization methods for instance:
Active waiting - spin lock
Pseudocode:
1. while ( xchg(lock, 1) == 1); - entry protocole

XCHG is an example of atomic operation (exists on x86 architecture) which first sets new value for a "lock" variable and then returns old value. Atomic means that it can't be interrupt - in above example between setting new value and returning old. Atomic - deterministic result no matter what.
2. Your code
3. lock = 0; - exit protocol

When lock is equal to 0 another thread can enter to critical section - while loop ends.
Thread suspending - for example counting semaphore
There exists two atomic operation .Wait() and .Signal() and we have integer variable lets call it int currentValue.
Wait():
if (currentValue > 0) currentValue -= 1;
else suspend current thread;

Signal():
If there exists thread suspended by semaphore wake up one of them
Else currentValue += 1;

Now solving critical section problem is really easy:
Pseudocode:
mySemaphore.Wait();
do some operations - critical section
mySemaphore.Signal();

Usually your programming thread API should give you ability to specify maximal concurrent threads in semaphore critical section. Obviously there are more types of synchronization in multithreaded systems (mutex, monitors, binary semaphore etc.) but they base on above ideas. One could argue that methods which use thread suspending should be preferred to active waiting (so cpu is not wasted) - it's not always the truth. When thread is being suspended - expensive operation called context switch takes it place. However it's reasonable when waiting time is short ( number of threads ~ number of cores ).


text:
Q: How to tell vsftpd which ssl to use I already have vsftp set up with an SSL which is working fine.  The issue is that the SSL is for the server's host name and not one of my client's.  This client has to be PCI compliant, so when the PCI scan takes place it checks the FTP ports and sees that the SSL is not associated with my client's URL.  My question is how can I set vsftp up to serve an SSL based off the IP address or the hostname?
vsftpd version 3.0.3
Red Hat 8.2

A: I finally found the answer to this on Red Hat's site (https://access.redhat.com/solutions/5172631).
Essentially, the default configuration file is located at /etc/vsftpd/vsftpd.conf.  You need to update this file to listen to the default IP address for the server using listen_address=....  Then, copy that file to /etc/vsftpd/[site].conf and change the listen_address to the one for the other site.  (Obviously, you have to have different IP addresses for different sites for this to work.)
Once done, enable vsftpd.target and start it:
systemctl enable vsftpd.target
systemctl start vsftpd.target

I also had to restart vsftpd to get this to work:
systemctl restart vsftpd

After that, when connecting to FTP for site 1, everything worked as expected.  When connecting to site 2 (the one with it's own unique SSL) I got the correct SSL.


text:
Q: iTextSharp for converting aspx with highcharts to pdf please refer me free dll or tool that could help me in converting aspx page with highcharts filling via javascripts on runtime on page into pdf file.
Public Sub lnkExport_Click(sender As Object, e As EventArgs) Handles lnkExport.Click
        Dim attachment As String = "attachment; filename=" & "abc" & ".pdf"
        Response.ClearContent()
        Response.AddHeader("content-disposition", attachment)
        Response.ContentType = "application/pdf"
        Dim s_tw As New StringWriter()
        Dim h_textw As New HtmlTextWriter(s_tw)
        h_textw.AddStyleAttribute("font-size", "7pt")
        h_textw.AddStyleAttribute("color", "Black")
        MasterDiv.RenderControl(h_textw)
    'Name of the Panel
    Dim doc As New Document()
    doc = New Document(PageSize.A4, 5, 5, 15, 5)
    FontFactory.GetFont("Verdana", 80, iTextSharp.text.Color.RED)
    PdfWriter.GetInstance(doc, Response.OutputStream)
    doc.Open()
    Dim s_tr As New StringReader(s_tw.ToString())
    Dim html_worker As New HTMLWorker(doc)
    html_worker.Parse(s_tr)
    doc.Close()
    Response.Write(doc)
End Sub

    html_worker.Parse(s_tr) is giving error

A: These kinds of charts are difficult because they use techniques like AJAX which have a rather indeterminate finish point. As such it's hard for an automated tool to know when they are complete.
So these things do rather depend on the particular type of chart you're doing. Some are easier. Some are more difficult. More interactive features = more difficult.
Having said that we did some work on our Gecko HTML rendering engine specifically to aid compatibility with Highcharts. So you might want to take a look at ABCpdf.
I work on the ABCpdf .NET software component so my replies may feature concepts based around ABCpdf. It's just what I know. :-)

A: Vá em todas as livrarias como highcharts.js, highcharts-all.js,heatmap.js e drilldown.js procure a palavra animation:{duration: e substitua o valor que tem dentro de (animation:{duration:1E3 OU animation:{duration:50 ou animation:{duration:500) substitua todos POR animation:{duration:0
Tem com setar sem animação no código mas não funcionou só setar no código, depois que substitui tudo por 0 ai sim funcionou e carregou todas as linhas do gráfico.
Antes da substituição o itextsharp não esperava terminar a animação para carregar todas as linhas do gráfico e ficava incompleto.
colunas:
plotOptions: {
    line: {
        animation: false
    }
}
series
plotOptions: {
    series: {
        animation: false
    }
}
Em inglês:
Go all bookstores as highcharts.js, Highcharts-all.js, heatmap.js and drilldown.js search for the word animation: {duration: and replace the value that is inside (animation: {duration: 1E3 OR animation: { duration: 50 or animation: {duration: 500) replace all FOR animation: {duration: 0
It has to set with no animation in the code did not work only to set the code after replacing all for 0 oh yes it worked and carried all the chart lines.
Before replacing the itextsharp not expect to finish the animation to load all the graph lines and was incomplete.
column:
plotOptions: {
     line: {
         animation: false
     }
}
series
plotOptions: {
     Series: {
         animation: false
     }
}