text:
Q: C# - How can i color string if they start and end with the same number As mentioned above i need to have a part of my string colored if they start and end with the same number.
Im a beginner and can't really figure it out, i have googled but haven't found any answers.
EDIT
To clarify, i need to print the whole string and not just the colored part.
string userInput = "29535123p48723487597645723645";
            //Console.WriteLine(userInput);

            for (int i = 0; i < userInput.Length; i++)
            {
                if (Char.IsDigit(userInput[i]))
                {
                    for (int j = i + 1; j < userInput.Length; j++)
                    {
                        if (userInput[i] == userInput[j])
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine(userInput.Substring(i, j - i + 1));
                            break;
                        }
                        else if (!Char.IsDigit(userInput[j]))
                        {

                            break;
                        }
                    }
                }

            }
            Console.ReadKey();

A: I gave it a quick try. I'll try and explain in comments:
class Program
{
    // input given in Question by OP
    public static string testinput = "29535123p48723487597645723645";

    static void Main(string[] args)
    {
        ProcessString(testinput);
        Console.ReadKey();
    }

    private static void ProcessString(string input)
    {
        // We'll have one index running from start of the string
        for (int fromStart = 0; fromStart < input.Length - 1; fromStart++)
        {
        // and another one running from the end
            for (int fromEnd = input.Length - 1; fromEnd > fromStart; fromEnd--)
            {
                // If both match, check if the found substring is all-digits
                if (input[fromStart] == input[fromEnd])
                {
                    if( input.Substring(fromStart, fromEnd-fromStart).IsNumCharOnly() )
                        PrintResult(testinput, fromStart, fromEnd);
                }
            }
        }
    }

    public static void PrintResult(string original, int fromIndex, int toIndex)
    {
        // remember the original fg-color
        var originalColor = Console.ForegroundColor;
        // Print the part before the hit
        Console.Write(original.Substring(0, fromIndex));
        // change color
        Console.ForegroundColor = ConsoleColor.Green;
        // print the hit
        Console.Write(original.Substring(fromIndex, toIndex-fromIndex +1));
        // change color back
        Console.ForegroundColor = originalColor;
        // print the rest, if there is something left
        if( toIndex < original.Length-1)
            Console.Write(original.Substring(toIndex+1));
        // add a newline in any case.
        Console.WriteLine();
    }
}

static class StringExtensions
{
    // Extensionmethod on string
    public static bool IsNumCharOnly(this string str)
    {
        // if any of the string's chars is outside '0'-'9' chars,
        // return false, otherwise return true
        return !str.Any(c => c < '0' || c > '9');
    }
}

Now, what does it do?
We go through the string from start and end until we find a match.
Then we check if the string delimited by the to indices contains a non-digit.
If so, we ignore the candidate, else we have a winner and print it.

29535123p48723487597645723645
^                           ^ = No
^                          ^  = No
^                         ^   = No
^                        ^    = No
^                       ^     = YES !!
=> Candidate : 29535123p4872348759764572 contains "p" => meh
29535123p48723487597645723645
^                      ^      = No
... // Some more false positives, we ignore ...
29535123p48723487597645723645
^     ^                       = YES !!
=> Candidate : 2953512 => PRINT!
...
29535123p48723487597645723645
^^                            = No
// Next OUTER loop iteration:
29535123p48723487597645723645
 ^                          ^ = No
... and so on

Output:

EDIT: C# 8
With access to the "Range" notation it's even a little more readable:
if( input[fromStart..fromEnd].IsNumCharOnly() )

A: Perhaps something like this?
        String s1 = "1234567890";
        String s2 = "1234567891";

        changeColor(s1);
        changeColor(s2);

        void changeColor(String s)
        {
            char start = s[0];
            char end = s[s.Length-1];

            if (start == end)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(s[0]);
                Console.ForegroundColor = ConsoleColor.White;
                for (int i = 1; i < s.Length - 2; i++)
                {
                    Console.Write(s[i]);
                }
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(s[s.Length-1]);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine(s);
            }
        }


text:
Q: "word-break" does not work correctly in CSS Grid I have a problem with CSS grid.
In a Firefox, when the width of the screen is reduced (eg to 600px), some elements on pages that uses CSS Grid do not support word-break value. They remain on the same line as they were.
I tried to add a display: inline-block but it didn't fix that.
That's the bug:

* {
box-sizing: border-box;
}

body {
margin: 0 0;
padding: 0 0;
}

.grid {
text-align: center;
align-items: center;
justify-content: center;
width: 100%;
display: grid;
margin-right: auto;
margin-left: auto;
}

.item {
grid-area: one;
display: grid;
}

Some looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line

Some looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line

Another example: link

Is there any property I have to or can use to solve this problem?

A: You need to Wrap your text using CSS. You can check how it works on w3schools here: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_word-wrap
Example code copied from above page:

<!DOCTYPE html>

The word-wrap Property

word-wrap: normal (default):

 This div contains a very long word: thisisaveryveryveryveryveryverylongword. The long word will break and wrap to the next line.

word-wrap: break-word:

 This div contains a very long word: thisisaveryveryveryveryveryverylongword. The long word will break and wrap to the next line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: System.out.println("Sklep:"+sklep1+sklep2); how to view I have some problem with my code when I run this code:
Sklep{
    private static double ch; //cena hurtowa
    private static double cd; // cena detaliczna
    private int zilosc;
    private int silosc;
    private int nr;

    static void setCenaHurtowa(double nch){ ch = nch; }
    static void setCenaDetaliczna(double ncd){ cd = ncd;}
    {licznik++;}
    public Sklep(){
        zilosc = 0;
        silosc = 0;
        nr=licznik;
    }

    void kupno(int nzilosc){
        zilosc = nzilosc;
    }

    void sprzedaz(int nsilosc){
        silosc = nsilosc;
    }
}
public static void main(String[] args){
    Sklep.setCenaHurtowa(1.5);
    Sklep.setCenaDetaliczna(3);
    Sklep sklep1 = new Sklep();
    Sklep sklep2 = new Sklep();
    Sklep sklep3 = new Sklep();
    sklep1.kupno(100);
    sklep2.kupno(200);
    sklep3.kupno(300);
    System.out.println("Sklep:"+sklep1+sklep2);
}

Console give me:

Sklep:zad_1$Sklep@35a8767zad_1$Sklep@2c6f7ce9

How can I get something like this:

Sklep nr 1 aktualny stan jabłek 100.0 kg
Sklep nr 2 aktualny stan jabłek 200.0 kg

Or where I can find an answer?

A: Override toString() method in your Sklep class. By default, it call's Object.toString().
Something like:
 public class Sklep{

  public String toString(){
     return "put whatever you wanna return from toString here";
  }
  public static void main(String[] args) {
  Sklep sk = new Sklep();
  //rest of your code
  System.out.println(sk);

   }

 }


text:
Q: Filtering list items with ng-repeat from a selection/de-selection of a combination of checkboxes I have a list of items which are frequently updated, based on changes to a price property. If the price of an item falls below a certain value (below 5) that item has a 'selected' property set to true and displayed in the results table (filtered on the selected property).
ng-repeat="item in dataPrices | filter: {selected:true}"

I want to add a series of checkboxes which, based on the selection/de-selection of a combination of checkboxes used should further filter the results - zero to three selections are possible

        <input type="checkbox">
        Large items

        <input type="checkbox">
        Small items

        <input type="checkbox">
        Medium items

I did try to add an additional filter to the ng-repeat
ng-repeat="item in dataPrices | filter: {selected:true} | filter: {size:'large'}"

which works, but I'm not sure how to add a combination of these based on the result of a combination of checkbox selection/de-selection. Any help would be GREATLY appreciated.
I have put this plunkr together which might make this a little clearer -  https://plnkr.co/edit/DHsOcWbfld7V7V1G8nIF?p=preview

A: You should apply custom oRfilter after built-in filter : {selected: true}:

angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
    $scope.items = [
      {selected: true, size: 'large'},
      {selected: false, size: 'large'},
      {selected: false, size: 'medium'},
      {selected: true, size: 'medium'},
      {selected: true, size: 'small'}
    ];
    $scope.search = {};
}])
.filter('oRfilter', function(){
  return function(items, search){
    var out = [];
    var atLeastOne = false;
    for(var prop in search)
      if(search[prop]){
        atLeastOne = true;
        out = out.concat(items.filter(function(x){ return x.size == prop; }));
      }
    return atLeastOne ? out : items;
  }
})

    {{size}}: <input type='checkbox' ng-model='search[size]' />

{{item | json}}

Your plunker does not work, because you have two separated controllers. You should connect them via events(updated plunker):
navController:
$scope.$watchCollection('search', function(arg){
    $scope.$parent.$broadcast('changed', arg);
});

priceController:
$scope.search = {};
$scope.$on('changed', function(event, arg){
    $scope.search = arg;
})

A: If you use a lot of additional filters, it ins't work, because every filter is applied on the result of the previous filter.
So when if you select 'large' and 'small' when you do this: {size:'large'}, the result doesn't contain the 'small' itens to apply another filter.
I think you can do this in two ways.
1 - You can return a function to your ng-repeat, that returns the filtered list:
 ng-repeat="item in filtered()"

In your controller:
$scope.filtered = function() {
  //take the selected filter and your data and apply the filters
  //return the filtered list
  // you can code this with lodash
  // $scope.data -> your data
  // $scope.productType ->  can be one or multiple
  var filtered = _.filter($scope.data, function(item) {
      //Note that this filter is just an example, this implementation depends on what you really need and how your filter selection works.
      return item.selected && item.size === $scope.productType;
  });
  return filtered;
}

In this situation you need to write your own filter and apply to the list. A library like lodash should help you a lot.
You could apply another filter in ng-repeat too:
ng-repeat="item in filtered() | anotherFilter"

2 - You can control manually your filter flow. This is a lite bit complex because you need to know exactly how your view should work and when you need to update your view. You will have performance improvements with this approach.
Basically you will use another list to receive your filtered data:
ng-repeat="item in filteredList"

And when you need to call a function (manually) to update this list. So
$scope.filteredList = getFilteredData();
function getFilteredData() {
  return _.filter($scope.data, function(item) {
      return item.selected && item.size === $scope.productType;
  });
}

Note that in this approach you need to call $scope.filteredList = getFilteredData(); every time that you want to update your view. So every time that you select a new size filter or something like that, you need to execute the code.


text:
Q: Show that the following group is not left orderable I was trying to solve an exercise from a book but i got stuck in my calculation.
I'm trying to show that foundamental groups of a class of orientable 3-manifold is not left orderable where by this i mean that they admits a strict ordere invariant for left multiplication.
The groups are Seifert manifold built over a surface where the surface is $\mathbb{R}P^{2}.$
They admit the following presentation: $$\pi_{1}(M)=\langle\gamma_{1},...,\gamma_{n},y,h\;|$$
$$yhy^{-1}=h^{-1},\gamma_{j}^{\alpha_{j}}=h^{-\beta_{j}},\gamma_{j}h\gamma_{j}^{-1}=h,y^{2}\gamma_{1}\cdots\gamma_{n}=1\rangle.$$
With some calculation I got to show that if $k>0,h>1$ the following holds: $h^{-k}<y^2<h^k$ and $h^{-k}<y^{-2}<h^{k}.$ In the book I was given the hint to show that $$yhy^{-1}>1\tag{$*$}$$ and this in facts concludes as it is a contradiction with the assumption that $h>1$ given the first relation but I could not find a way to prove the key fact $(*)$. Any suggestion in what kind of relations I should look for?
Thanks in advance.


text:
Q: How to move several divs up the DOM with jQuery I would like to move several divs up the DOM with jQuery.

I would like to move all the .list divs after the .title div.  How can I do this with jQuery.
This $('.temps').insertAfter('.title'); does not work, it places all the .list after the first .title

A:
I would like to move all the .list divs after the .title div.

You can use each method like this:

    $('.list').each(function(){
       $(this).insertAfter(
          $(this) //.list div
            .closest('section') //find parent div section
            .find('.title') //find child div
        );
    });

title

temps

list

title

temps

list

title

temps

list

A: simply try this, demo
$('.list').insertAfter($('.title'));

or
$('.list').insertAfter('.title'); //only selector no object

A: Try this
$('.list').each(function(){
   $(this).prevAll('.title').after($(this));
});

A: I wouldn't of been anble to get this working without @Bhojendra Nepal help in his answer above, and while his solution worked in his code snippit it did not work on my application.  In the end the below worked for me.
jQuery('.list').each(function(){
   jQuery(this).insertAfter(jQuery(this).parent().find('.title'));
});


text:
Q: The parameter is incorrect while finding video capture sources in Directshow By using Directshow.NET I have developed an C# application everything is fine but on some machines I am unable to find video capture sources (camera) by line of using code DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice). This line of code generating Exception The parameter is incorrect.. I have checked with GraphStudio also but no camera is listed under Video capture sources but I can see the attached camera in Device Manager.
While checking with Directshow Filter Manager I get following error:

The parameter is incorrect.
Scope:[CDENum.CreateClassEnumerator({860BB310-5D01-11d0-BD3B-00A0C911CE86})].

What is the possible cause of this, where camera is found under Device Manager but not by Directshow? and How I can solve this?

A: There might be certain problem with the driver of the camera (WDM or user mode driver), which prevents form normal device enumeration with DirectShow. Or there is a chance that there is another faulty device/camera that triggers an unexpected problem on enumeration. Enumeration itself is not expected to fail this way (it is expected to return S_FALSE when no devices are found in first place), so it is likely that you need to identify faulty component installed in this particular system, and fix it to restore class enumerator operation. The first thing to do is to reinstall the drivers/software for the video device in question.


text:
Q: How to call method in state class in flutter? I want to call the method from HomeState class to _MyHomePageState class.But i have no idea to do that.
this is main.dart :
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
Home home = new Home();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){}
      ),
    );
  }
}

Home class:
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State<Home> {

  int numberPrint(){
    setState((){});
  }

  @override
  Widget build(BuildContext context) {
  }
}

I want to call the method numberPrint() in floatingbutton in _MyHomePageState class in main.dart.
Please help me to do that.

A: Please take a look at how I would have handled, this is not the best, but it would give you a better idea.
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
//MyHomePage---------------------------------------------------
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MyController controller = MyController();
  @override
  Widget build(BuildContext context) {
Home home = new Home(controller:controller);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: controller.execute,
      ),
    );
  }
}
//Home---------------------------------------------------------------------
class Home extends StatefulWidget {
  Home({this.controller});
  final MyController controller;
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State<Home> {
  initState(){
    widget.controller.addListener(numberPrint);
  }

  numberPrint(){
    setState((){});
  }

  @override
  Widget build(BuildContext context) {
  }
}

//MyController--------------------------------------------------------
class MyController{
  Function listener;
  addListener(Function fn){
    listener = fn;
  }

  execute(){
    listener();
  }
}

A: In general, I use some kind of page nerve center through which widgets can register their setState functions or other things such as FocusNode and even data.
For example,
class PageNerveCenter{
  Function requireHomeRebuild;
}

PageNerveCenter _pageNerveCenter = PageNerveCenter();

class Home extends StatefulWidget{...}

class _HomeState extends State<Home>{

...
  @override
  initState(){
    super.initState();
    // register setState
    _pageNerveCenter.requireHomeRebuild = (){
      setState((){})
    };
  }

  @override
  dispose(){
    // remove setState when object is disposed
    _pageNerveCenter.requireHomeRebuild = (){};
  }

...

}

In some other widget (same file/library),
_pageNerveCenter.requireHomeRebuild();

This approach then allows you to call a widget's setState from anywhere in the file, from inside another widget.
In my own experience, this approach has helped to easily break down my widget tree and only rebuild those widgets that actually need to rebuilt too.
I would certainly like to hear other more experienced flutter developers about their take on this approach since I am relatively new too.


text:
Q: How to set the color of PopupMenuButton border with custom shape? In this answer I found a great solution how to make PopupMenuButton with tooltip shape. Here is the solution:
class TooltipShape extends ShapeBorder {
  const TooltipShape();

  final BorderSide _side = BorderSide.none;
  final BorderRadiusGeometry _borderRadius = BorderRadius.zero;

  @override
  EdgeInsetsGeometry get dimensions => EdgeInsets.all(_side.width);

  @override
  Path getInnerPath(
    Rect rect, {
    TextDirection? textDirection,
  }) {
    final Path path = Path();

    path.addRRect(
      _borderRadius.resolve(textDirection).toRRect(rect).deflate(_side.width),
    );

    return path;
  }

  @override
  Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
    final Path path = Path();
    final RRect rrect = _borderRadius.resolve(textDirection).toRRect(rect);

    path.moveTo(0, 10);
    path.quadraticBezierTo(0, 0, 10, 0);
    path.lineTo(rrect.width - 30, 0);
    path.lineTo(rrect.width - 20, -10);
    path.lineTo(rrect.width - 10, 0);
    path.quadraticBezierTo(rrect.width, 0, rrect.width, 10);
    path.lineTo(rrect.width, rrect.height - 10);
    path.quadraticBezierTo(
        rrect.width, rrect.height, rrect.width - 10, rrect.height);
    path.lineTo(10, rrect.height);
    path.quadraticBezierTo(0, rrect.height, 0, rrect.height - 10);

    return path;
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}

  @override
  ShapeBorder scale(double t) => RoundedRectangleBorder(
        side: _side.scale(t),
        borderRadius: _borderRadius * t,
      );
}

And then
PopupMenuButton(
  offset: Offset(0, 50),
  shape: const TooltipShape(),
  ...
)

Now I want to change the color of PopupMenuButton border with this such shape. I mean the color of the popup menu border that is shown on button tap. Could anyone say how to do?

A: You can use the paint() function
@override
void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
  Paint paint = new Paint()
    ..color = Colors.red
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2;
  canvas.drawPath(getOuterPath(rect), paint);
}

You should also add path.close(); to the end of the outerPath before return path; else the left side won't get a border.


text:
Q: PHP: simplexlsx Parser specialchars hope someone can help me out.
Im using simplexlsx
( http://www.phpclasses.org/package/6279-PHP-Parse-and-retrieve-data-from-Excel-XLS-files.html ) to read out my Excel files and display them/write them into my DB.
Now i have the problem that the class wont parse specialchars like : "Ä, Ü, Ö, ß..." correct
i tryed to write a function to fix it, but it wont work.
Hope some of you guys could help me.
Thx so far
xQp
// Try
function unhtmlspecialchars( $string ){
  $string = str_replace ( '&', '&', $string );
  $string = str_replace ( ''', '\'', $string );
  $string = str_replace ( '"', '"', $string );
  $string = str_replace ( '<', '<', $string );
  $string = str_replace ( '>', '>', $string );
  $string = str_replace ( 'ü', 'ü', $string );
  $string = str_replace ( 'Ü', 'Ü', $string );
  $string = str_replace ( 'ä', 'ä', $string );
  $string = str_replace ( 'Ä', 'Ä', $string );
  $string = str_replace ( 'ö', 'ö', $string );
  $string = str_replace ( 'Ö', 'Ö', $string );
  return $string;
}

tryed to get call that function within the simplexlsx.class before return the $value
// edit 2
my try was the to add the function unhtmlspecialchars to simplexlsx.class and call it at the end of the "function value()" before returning the value
like this just to test it...
  $value2 = $this->unhtmlspecialchars($value);

        return $value2 ;

A: The solution (as stated by the OP in the comments) is to use
utf8_decode($value);

to restore the special chars in the output.


text:
Q: What is :: in declaration and why is it used? I came from C working environment and new to C++.
Please help in the following declaration.
Inside some function foo() I have found this code .
::ifstream ifObj;
I know it is declaring input filestream object.
But I completely don't know this concept of :: scope resolution here.
What is this and why is it used in declaration of object.
Could not have found out anywhere, hence asked.

A: Specifically for your Question,
It is to let the compiler to resolve the disambiguity while tracing the origin of the type ifstream.
ifstream may be declared in 3rd party libs like boost to provide different meaning,
Consider you have,
namespace boost {
 typedef int ifstream;
}

using namespace boost;

//but here you want global ifsteam, not from boost, so
::ifstream ifObj; // Here you are creating a object for global ifstream, not for boost's ifstream,

A: The unary scope resolution operator is used to refer to the global namespace version of a token if that token is overridden in a local namespace.
F.ex:
int count = 0;

int main(void) {
  int count = 0;
  ::count = 1;  // set global count to 1
  count = 2;    // set local count to 2
  return 0;
}


text:
Q: Downloading a dynamically created text file from Java, write directly to computer or save on server? When a user clicks a download button (coded in simple Javascript) on my webpage, it triggers a PHP function that calls to a java file. This Java code connects to the database and writes to a text file.
Currently, the code is in development on my local machine. Here is a snippet of the code is currently creating a local text file and writing the information to it:
        StreamFactory sf = StreamFactory.newInstance();
        sf.loadResource("mapping.xml");
        File file = new File("C:\\MyLocal\\foo.txt");
        BeanWriter bw = sf.createWriter("fileExport", file);

        // writes beans
        bw.write("", "");
        ...

        bw.flush(); // flushes to foo.txt located in C:\MyLocal

My question is is it possible to write this dynamically created text file to the user's computer instead of my local, and if so, is it a good web development practice? The benefit this way is that I don't need to store foo.txt on the server that the code will reside. However, I'm not very familiar with web development practices, and did not see a concrete rule on this subject matter.
If it is better to save it to the server and then implement some download code from there, should this be handled within the PHP of the page or the Java backend functions?

A: It's not possible to write on user's computer filesystem.
Because of javascript security measures, if it wasn't because of this, a malicious website/webapp could write a huge amount of data on users hard drive, or could write malicious scripts.
The option a user has it's to download a file, but a webpage doesn't have direct access to user filesystem.
There was a proposal API for doing something like this, but it was discontinued
https://www.html5rocks.com/en/tutorials/file/filesystem/
Answering to your question: definitely it's not a good practice to try to write files on users filesystem
You should handle the download with Java on the Backend


text:
Q: Dynamically assigning values to a jQuery array from database using ASP.NET Core razor pages I have a autocomplete functionality, which is hardcoded currently. Please find the code below.
jQuery(document).ready(function ($) {

        var availableTags = [
            "superadmin",
            "admin",
            "user1",
            "user2"
        ];
        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }

        $("#RequestorBox")
            // don't navigate away from the field on tab when selecting an item
            .on("keydown", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB &&
                    $(this).autocomplete("instance").menu.active) {
                    event.preventDefault();
                }
            })
            .autocomplete({
                minLength: 0,
                source: function (request, response) {
                    // delegate back to autocomplete, but extract the last term
                    response($.ui.autocomplete.filter(
                        availableTags, extractLast(request.term)));
                },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    var terms = split(this.value);
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push(ui.item.value);
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            });
            });

<label class="control-label" for="tags">Requestor/Country User</label>
<input id="RequestorBox" size="50">

Currently the var availabletags array is hardcoded, I want to populate those values from database using ASP.NET C#(Razor Pages).
How can I call the ASP.NET method here and assign the value to jQuery array. Any help would be appreciated.


text:
Q: Disabling the functions in a string c# I know that we can call functions with their name stored in a string like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Is their any way in C# by which I can call all the functions in the class except the function in a string?
Want it in late binding, as I have array of strings which includes the methods name which needs to be discarded from the execution.

A: If you are trying to use reflection to execute all methods except a particular one, you just need to get all methods and exclude the one(s) you're not interested in. For example to exclude a single method name:
var methods = this.GetType().GetMethods()
    .Where(t => t.Name != "Whatever");

foreach(var method in methods)
{
    method.Invoke(this, userParameters);
}

If you have an list of method names, then you just need to change the filter, for example:
var methodNames = new [] { "Method1", "Method2" };

var methods = this.GetType().GetMethods()
    .Where(t => !methodNames.Contains(t.Name);


text:
Q: Put powershell code into function, script or cmdletbinding If I put this code below (to check a certain gpo setting) into the console of Powershell, the output is shown correctly. If I want to make a function, script or cmdletbinding of it, it only shows me the output of $policydetails.
#Get the GPO Guid
[xml]$GpoXml = Get-GPOReport -Guid (Get-GPO $GPOName).Id -ReportType xml

#Create a custom object containing only the policy "fields" we're interested in
$PolicyDetails = foreach ($p in $GpoXml.GPO.Computer.ExtensionData.Extension.Policy) {
    [PSCustomObject]@{
        "Name" = $p.Name
        "State" = $p.State
        "Filter" = $p.EditText.Value
    }
}
$SvcPolicyDetails = foreach ($p in $GpoXml.GPO.Computer.ExtensionData.Extension.NTServices.NTService.Properties) {
    [PSCustomObject]@{
        "Service" = $p.ServiceName
        "Action" = $p.ServiceAction
        "Start" = $p.StartupType
    }
}
$PolicySecurity = foreach ($p in $GpoXml.GPO.SecurityDescriptor.Permissions.TrusteePermissions.Trustee.Name) {
    [PSCustomObject]@{
        "SecurityFiltering" = $p.'#text'
    }
}
$PolicyLinks = foreach ($p in $GpoXml.GPO.LinksTo) {
    [PSCustomObject]@{
        "OU-Link" = $p.SOMPath
        "Enabled" = $p.Enabled
    }
}

#Let's see the results
$PolicyDetails
$SvcPolicyDetails
$PolicySecurity
$PolicyLinks

I tried several things...
1.Function:
Function Get-GpoDetails {
  <script code>
}

2.Cmdletbinding:
Function Get-GpoDetails {
  param (
     [Parameter(Mandatory = $true)]
     [string]$GPONameWinRm )

  <script code> ### without variable $GPONameWinRm
}

3.Script:
Copy <script code> into .ps1

None of these things worked. They all give the same output, only the output of the variable '$policydetails' is shown.
How can I make this work in a function or script or cmdletbinding so that not all the code needs to be put into the console for the right output?

A: The problem you're having is because you output 3 different object "types" in a single list. Powershell knows that they're all [PSCustomObject], so it wraps them together
Powershell displays results using properties from the first object by default:
$result = Get-GpoDetails

$result  ## outputs like

Name                                        State   Filter
----                                        -----   ------
Configure wireless policy processing        Enabled
Specify startup policy processing wait time Enabled

## missing other output... ##

All the data does still get returned. Try formatting the output or manually specifying fields to display it:
$result | Format-List
$result | ConvertTo-Json

# example of adding fields that Format-Table would ignore
$result | select Name,State,SecurityFiltering,OULink,Enabled | Format-Table -AutoSize

A: I changed the code like this and get the wanted results in nice output format
Function Get-GpoWinRM
{
[CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$GPOName
    )

#Get the GPO Guid
[xml]$GpoXml = Get-GPOReport -Guid (Get-GPO $GPOName).Id -ReportType xml

#Create a custom object containing only the policy "fields" we're interested in
$PolicyDetails = foreach ($p in $GpoXml.GPO.Computer.ExtensionData.Extension.Policy) {
    [PSCustomObject]@{
        "Name" = $p.Name
        "State" = $p.State
        "Filter" = $p.EditText.Value
    }
}
$SvcPolicyDetails = foreach ($p in $GpoXml.GPO.Computer.ExtensionData.Extension.NTServices.NTService.Properties) {
    [PSCustomObject]@{
        "Service" = $p.ServiceName
        "Action" = $p.ServiceAction
        "Start" = $p.StartupType
    }
}
$PolicySecurity = foreach ($p in $GpoXml.GPO.SecurityDescriptor.Permissions.TrusteePermissions.Trustee.Name) {
    [PSCustomObject]@{
        "SecurityFiltering" = $p.'#text'
    }
}
$PolicyLinks = foreach ($p in $GpoXml.GPO.LinksTo) {
    [PSCustomObject]@{
        "OU-Link" = $p.SOMPath
        "Enabled" = $p.Enabled
    }
}

#Let's see the results
$PolicySummary = $PolicyDetails,$SvcPolicyDetails,$PolicySecurity,$PolicyLinks
Write-Host -ForeGroundColor Green "*** WINRM POLICY ***"
Write-Host -ForeGroundColor Cyan "PolicySetting and Status:"
$PolicySummary.name
$PolicySummary.state
Write-Host -ForeGroundColor Cyan "Allowed IP-range to WinRM:"
$PolicySummary.filter
Write-Host -ForeGroundColor Cyan "PolicySetting Service:"
$PolicySummary.service
$PolicySummary.action
$PolicySummary.start
Write-Host -ForeGroundColor Cyan "SecurityFiltering:"
$PolicySummary.securityfiltering
Write-Host -ForeGroundColor Cyan "OU Link:"
$PolicySummary.'ou-link'
$PolicySummary.enabled
}

All the previous code results in this output:
*** WINRM POLICY ***
PolicySetting and Status:
Allow remote server management through WinRM
Enabled
Allowed IP-range to WinRM:
172.16.0.0-172.16.0.254, 172.16.1.0-172.16.1.254
*
PolicySetting Service:
WinRM
START
AUTODELAYED
SecurityFiltering:
DH\Enterprise Admins
DH\Domain Admins
NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS
NT AUTHORITY\SYSTEM
NT AUTHORITY\Authenticated Users
OU Link:
DH.herhaling.loc/HO-DIGITAL3/Machines
true


text:
Q: Css Div won't stay inside parent Div I have a div that is 1000px wide. Inside that div is another div that is 4000px wide.
The code looks like this
JS Fiddle
HTML

CSS
#parent_div{
 position:relative;
 height:500px;
 width:1000px;
 overflow:hidden;
}
#child_div{
 position:relative;
 height:500px;
 width:4000px;
}

Now this code works in Chrome and Safari, it looks like this in Chrome in Safari

Black box is Parent Div - Red box is Child Div
This is how I would expect the code to work, but in FireFox the code looks like this

The child div is pushed out of its Parent. Why does it do this? How can I stop it from doing this?

A: use "position:absolute" instead of relative in child div

A: just remove overflow : hidden;
#parent_div{
 position:relative;
 height:500px;
 width:1000px;
}


text:
Q: How to get the size of the memory allocated dynamically? Allocating memory dynamically using malloc will return the address from where the memory is allocated. Before that address meta-data is stored; it's a struct.
struct malloc_chunk {
    int      prev_size;
    int      size;           // size of memory allocated
    struct malloc_chunk* fd;
    struct malloc_chunk* bk;
    struct malloc_chunk* fd_nextsize;
    struct malloc_chunk* bk_nextsize;
};

I want to print value of size without using malloc_usable_size(). I tried but I am getting a segfault.  I am working on 64-bit Ubuntu.

A: The structure is implementation dependent. You should not use the information at all since it might change at the next compiler or even at the next compiler version.
You should manage the size of memory in user defined structures.
Edit:
Memory allocation algorithms usually work with some alignments to

*

*avoid unaligned addresses in further allocations

*provide best performance on architectures where unaligned access is allowed but could result in performance penalties

*reduce the heap fragmentation be using chunks that are a multiple of a base, e.g. 16 bytes.

Therefore malloc doesn't need to allocate exactly the size that you passed as parameter. It can allocate a chunk the is sufficient to hold the requested size but probably more. It's not necessary for mallocto store the original value, only the chunk size is necessary to free the chunk.
Therefore it's probably impossible to retrieve the size parameter passed in the malloc function call.

A: In the general case, the exact mechanism malloc uses to store the size -- if it even has a mechanism -- is going to be implementation defined. You need to keep track of the size yourself if you need it for anything specific.

A: Consider the following test code (which has no error checking):
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    void *v1 = malloc(160);
    void *v2 = malloc(160);
    void *v3 = malloc(160);

    printf("v1 = %p\n", v1);
    printf("v2 = %p\n", v2);
    printf("v3 = %p\n", v3);

    ptrdiff_t d1 = v2 - v1;
    ptrdiff_t d2 = v3 - v2;

    printf("d1 = %td\n", d1);
    printf("d2 = %td\n", d2);
    return 0;
}

When compiled on 64-bit Ubuntu 14.04 LTS, the output I got was:
v1 = 0x742010
v2 = 0x7420c0
v3 = 0x742170
d1 = 176
d2 = 176

Since the gap between the returned blocks is 176 bytes and the size allocated is 160 bytes, there are just 16 bytes of overhead.  The struct malloc_chunk outlined in the question occupies 40 bytes on a 64-bit platform (24 on a 32-bit platform).  It does not fit into the space between allocated chunks of memory.
Therefore, any attempt to access a struct malloc_chunk from a regular block of allocated memory is doomed to failure.
You will have to obtain the source to malloc() to find out how it uses that structure.  If I had to guess, it uses it in a separate area altogether.  Maybe some of the 16 bytes of overhead tells malloc() where to find the struct malloc_chunk.  But that's a guess; I've not looked.

A: First of all malloc_usable_size is Linux/Unix specific function and will not work on Windows, for example.
So, the best way is to save size when allocating memory: just remember how much memory was allocated and than use that value.

A: Malloc library normally maintains a list of struct malloc_chunk internally to manage the amounts of memory given to the user up to this point.  Normally, to cope with that they have a way to map the returned pointer from malloc(3) to the address of this structure (so free(3) can get to it), but you don't know that mapping for sure.
Normally, they alloc internally the amount to store the memory they give to you and this struct malloc_chunk together, and the struct is aligned in a way that they can get the structure address from the pointer you pass to free(3).
The normal way to cope with this is: The malloc(3) function gives you (void *)(ref + 1), where ref is a struct malloc_chunk * pointer (so it's aligned to the end of this structure) and you have to do just the opposite to get a valid pointer to that structure, that is: ((struct malloc_chunk *)ptr - 1) (convert the pointer to a struct malloc_chunk * pointer, and then go back one structure size to point there)
This expression is of type pointer to struct malloc_chunk, so you can reference its fields with the following code:
void *p = malloc(120);
struct malloc_chunk *mc = (struct malloc_chunk *)p - 1;

printf("prev_size:   %d\n"
       "size:        %d\n"
       "fb:          %p\n"
       "bk:          %p\n"
       "fw_nextsize: %p\n"
       "bk_nextsize: %p\n",
       mc->prev_size,
       mc->size,
       mc->fb,
       mc->bk,
       mc->fw_nextsize,
       mc->bk_nextsize);

I have not been able to test this code, as my <malloc.h> implementation doesn't have this struct malloc_chunk type defined anywhere (or I have not been able to find it).  You have to provide a reference of where do you have acquired this type if you want me to be able to reproduce your environment.  I'm using gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)


text:
Q: ContentScript in Firefox Add-On in chrome.manifest? I am wondering how I can add a JS file that runs on all pages opened in firefox and that will reload each time user opens a new page/tab.
I would like my script to load before the DOM (and if possible CSS) of the page has loaded.
Here is what I have so far (//COMMENTS were added just for better understanding purposes):
main.js
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "http://*/*","https://*/*",//LOADS ON ALL PAGES (not sure if I'm correct)
contentScriptFile: data.url("performcheck.js"),//LOADS THE JS FILE I WANT
});

performcheck.js
if (document.domain=="www.google.com"){
    alert('Welcome Google user! I said it before the page loaded.');
}

I don't know in which folders I should be placing these files and what I should add to my
install.rdf or chrome.manifest file so that the script can be generated on every page.
Thanks in advance for your help.

A: Place the  main.js in lib folder and performcheck.js in the data folder and that should be fine. Make sure "main": "main" is set in the package.json file (no need to mention this line if it is missing default is main.js)
There is no need to modify install.rdf its job is for describing the addon and compatibility.
Further information can be read from this documentation link https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials


text:
Q: Options if a nuget package hasn't been updated We use jQgrid in many in many of our apps and nuget would be the perfect way to ensure that we keep up to date with the latest version but if the author of the nuget package doesn't keep it up to date then it makes more sense for us to manually keep it up to date.
JQGrid is on v4.4.0 while the only useable nuget package is on v4.2.0 (last updated Nov 2011). There are some specific fixes in the new version that I want to upgrade for.
http://www.trirand.com/blog/
http://nuget.org/packages/jquery.jqgrid
Is there anything I can do if the author of a nuget package has stopped updating it?
Is there a way to recommend that the package gets taken over, removed or a new one created from scratch?
Update
I tried to contact the owner to ask him to update it but unfortunately didn't get an answer. I would create a nuget package myself (with multiple owners) but all the good names for jqGrid have been taken too so unfortunately I think I'm going to have to avoid nuget for jqGrid and go back to updating it manually :(

A: If you want to take over maintaining it, you can contact the owner and ask to be made into an "Owner".  I was in a similar situation before, but then the current owner got to be much more regular in keeping the NuGet package up to date.  I never got around to requesting permission in that case.
In other cases I've had packages that I wanted on NuGet that weren't mine so I just put them up there (license allowing, of course).  In those cases I email the author and let them know that I'm willing to transfer ownership if they want.  They usually thank me for putting it up there and then do not ask to take over the package.  So far I haven't seen any cases of "jealous owners".  Most are happy to have someone else take on the task.
There doesn't appear to be any standard way of suggesting that a NuGet Owner be evicted.  As for starting one from scratch, that's entirely possible if you use a different package ID.  However, keep in mind that NuGet packages cannot be deleted from NuGet.org, only unlisted.  So, it might be a better idea to post your "unofficial" version on an alternate host like MyGet.org.


text:
Q: Cannot login to wordpress admin once i change the admin url I have just installed a wordpress website, and i was working with some security measures but now my wordpress admin is not loading. It gets redirected to page not found.
Steps which i have done

*

*I have installed wordpress in the following url icg.projects.com

*Then i have moved the wp files to a sub-folder named "core-files" (as per this url http://www.ampercent.com/move-core-wordpress-files-custom-directory/6211/).
Till now frontend and wp admin works fine

*

*Now i just tried to change the admin url to icgadmin (ie. from icg.projects.com/core-files/wp-admin/ to icg.projects.com/core-files/icgadmin/). The problem is after giving the username and password in wp-login page my url becomes http://icg.projects.com/core-files/icgadmin/. But the content of the page is "Page not Found". But the actually i should get the wordpress admin.

Any help would be really appreciated.
Thanks in advance


text:
Q: Double slider in plotly I'm trying to implement two sliders in one fig of plotly I tried the following
# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(1, 5, 1):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name=" = " + str(step),
            x=np.arange(0, 10, 0.01),
            y=[step]*50))

# Make 10th trace visible
fig.data[1].visible = True

# Create and add slider
sliders = []

for j in range(int(len(fig.data)/2)):
    steps=[]
    for i in range(int(len(fig.data)/2)):
        step = dict(
            method="update",
            args=[{"visible": [False] * (int(len(fig.data)/2))},
                  {"title": "Slider switched to step: " + str(i)}],  # layout attribute
        )
        step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
        steps.append(step)
    sliders.append(dict(active=0, currentvalue={"prefix": "slider: "}, pad={"t": (80 * j + 20)}, steps=steps))

fig.update_layout(sliders=sliders)

plotly.offline.plot(fig, filename=f'test.html')

The two sliders not working together, in this example, each slider has two options.
But if the first one is in one position, moving the second one doesn't seem to know what the first one status is. Any suggestions?

A: You can use the dcc slider in dash.  The below code shows two sliders that control two different pi charts with a function (metrics) that reads in the slide output and outputs two percentages.  To make this work, replace the metrics function with a function that generates two percentages given two inputs.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go

app = dash.Dash(__name__)

app.layout = html.Div([
    html.P("par 1:"),
    dcc.Slider(0, 1, 0.1,
               value=0.5,
               id='names'
    ),
    html.P("par 2:"),
    dcc.Slider(0, 1, 0.1,
               value=0.5,
               id='values'
    ),
    dcc.Graph(id="pie-chart"),
])

@app.callback(
    Output("pie-chart", "figure"),
    [Input("names", "value"),
     Input("values", "value")])
def generate_chart(names, values):
    fig = make_subplots(rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "pie"}]])
    fig.add_trace(go.Pie(
        values=[metrics(values,names)[0], (100-(metrics(values,names)[0]))],
        domain=dict(x=[0, 0.5]),
        name="Recall"),
        row=1, col=1)

    fig.add_trace(go.Pie(
        values=[metrics(values,names)[1], (100-(metrics(values,names)[1]))],
        domain=dict(x=[0.5, 1.0]),
        name="Precision"),
        row=1, col=2)

    return fig

app.run_server(debug=True)


text:
Q: excel - advanced vlookup or other formula? I have a question regarding excel and I am looking for a formula that can help me transport my data from one sheet to the other. I have some experience with excel, however I am not a pro at it, so I apologize if this is a very trivial question but would also be happy since that would mean it probably has a very trivial answer! Unfortunately I do not have enough reputation points yet to post images, but I will try to explain it as clearly as possible.
Basically I am creating an excel template and the goal is to have 2 sheets in excel.
In the first sheet I have a column with following input in rows A1 - A3: Sales Region,
Country, Account ID's.
Above is the example of column A; from column B --> x; I will put e.g.
Americas, US and as many account numbers as there are in that specific country.
However on the second sheet it gets a bit complicated. My goal is that all the account numbers from sheet 1 irrespective of their sales region and country (which also means irrespective of their column) will automatically be listed on the second sheet.
The second sheet will be organized in the following way:
From column A - C; sales region, country and account ID.; from column D - x financial information for each account.
As a first step I want all the different account ID's from the different columns on the first sheet to be listed under column C (account ID's) on the seconds sheet.
As a second step I want column A - B to be automatically filled out according to account number by accessing the information in which column and thus sales region and country the account is in on sheet one.
I don't think a simple vlookup would do the job, especially for step 1, since I want the account ID's from many different columns and rows in sheet 1 to be listed in just one column....
hope it is clear enough! Would appreciate any help! :) thanks in advance!

A: The first step take all of column A and copy it to the 2nd sheet on column C.
Select data ribbon and select remove duplicates.
For column A insert vlookup for column C for all the data in 1st sheet
For column B insert vlookup for column B for all the data in 1st sheet
Those value will work well only if an ID has one valid Region and country.
Now just use custom sort to sort it in the way you desire.


text:
Q: Running react-native run-android builds successfully but stays stuck at Starting the app Running my React Native application via the Bash terminal onto the Android emulator builds successfully, but remains stuck at:
info Starting the app (adb shell am start -n com.myapp/com.myapp.MainActivity...

The Metro Bundler is running, with nothing else on the same port and no errors. The app just never actually loads up into the emulator after a successful build (Pixel 2 XL API 27).
Running directly from Android Studio pushes the app into the emulator no problem and it runs just fine (pressing the green arrow button or hitting Shift+F10). This is happening on a new Windows 10 laptop. Running this same project on another Windows 10 desktop and macOS macbook 2018 this issue does not occur.
I've also let it sit at 'Starting the app' for almost half an hour, and nothing occurs. To note, on the other machines it loads instantly onto the emulator.
The other machine's differences lie in the version of Android Studio installed.
On working Windows 10 desktop:
Android Studio version 3.1.2
JRE version 1.8.0_152
java version "1.8.0_211"

On working macOS Mojave 10. macbook 13" 2018 macbook:
Android Studio version 3.3.2
JRE version 1.8.0_152
java version "1.8.0_181"

On this Windows 10 laptop where it's NOT working:
Android Studio 3.4.1
JRE version 1.8.0_152
java version "1.8.0_211"

This is happening with React Native 0.59.8 which is the latest stable version at the time of this question being posted, with React version 16.8.3. The following command is being run through the bash terminal.
react-native run-android

The expected output of running the above should be that it loads up into the already-on emulator.
I'm suspecting the difference being in how brand new Android Studio is on this laptop, but downgrading to an older version is not an option. Any suggestions or guidance is greatly appreciated.

A: Managed to solve it, had to run through a few steps to get it working. Here's what I did.
With the project open in Visual Studio Code, cd into the android folder and run:
./gradlew clean

That stops it from getting stuck at 'Starting app' but I then ran into:
'adb' is not recognized as an internal or external command,
operable program or batch file.

To fix that, open Environment Variables (hit Windows key, search for 'environment' and click on Edit the system environment variables).
Click on the button that says 'Environment Variables...'.
Under System variables, click 'New...'.
Variable name: ANDROID_HOME
Variable value: C:/Users/USER/AppData/Local/Android/Sdk

Where USER is whatever your Windows username is.
That fixed the 'adb' error, but I then ran into the metro server error:
Unable to load script. Make sure you're either running a Metro server ...

Despite closing all terminals, visual studio code, and any node processes this issue persisted. Only after restarting Windows, did this issue go away and running the following worked:
react-native run-android

That's it. Hopefully it helps another. Basically, needed to clean gradle, add Android studio sdk to environment variables and do a restart. Now it all works.


text:
Q: How do I make my button stay at the bottom of the textbox everytime I press add? How do I make my button stay at the bottom of the textbox everytime I press the add experience button to add another textbox?

Work Experiece

        <textarea class="form-control" id="form-control-10"rows="5">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris nunc arcu, dignissim sit amet sollicitudin iaculis, vehicula id urna. Sed luctus urna nunc. Donec fermentum, magna sit amet rutrum pretium, turpis dolor molestie diam, ut lacinia diam risus eleifend sapien. Curabitur ac nibh nulla. Maecenas nec augue placerat, viverra tellus non, pulvinar risus.</textarea>

    <input type="button" class="ticker-btn1 add-exp" value="Add Experience" onclick="add_field();">

function add_field() {
  var total_text = document.getElementsByClassName("form-control");
  total_text = total_text.length + 1;
  document.getElementById("field_div").innerHTML = document.getElementById("field_div").innerHTML +
  "<textarea class='form-control add-exp add-textbox' rows='5' id='form-control-" + total_text + "'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris nunc arcu, dignissim sit amet sollicitudin iaculis, vehicula id urna. Sed luctus urna nunc. Donec fermentum, magna sit amet rutrum pretium, turpis dolor molestie diam, ut lacinia diam risus eleifend sapien. Curabitur ac nibh nulla. Maecenas nec augue placerat, viverra tellus non, pulvinar risus.</textarea>";
}

A: Create a new div section over the existing text area and
add your new text areas inside the new div
Here is the solution

function add_field() {
  var total_text = document.getElementsByClassName("form-control");
  total_text = total_text.length + 1;
  document.getElementById("text_area_section").innerHTML +=
  "<textarea class='form-control add-exp add-textbox' rows='5' id='form-control-" + total_text + "'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris nunc arcu, dignissim sit amet sollicitudin iaculis, vehicula id urna. Sed luctus urna nunc. Donec fermentum, magna sit amet rutrum pretium, turpis dolor molestie diam, ut lacinia diam risus eleifend sapien. Curabitur ac nibh nulla. Maecenas nec augue placerat, viverra tellus non, pulvinar risus.</textarea>";
}

Work Experiece

        <textarea class="form-control" id="form-control-10"rows="5">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris nunc arcu, dignissim sit amet sollicitudin iaculis, vehicula id urna. Sed luctus urna nunc. Donec fermentum, magna sit amet rutrum pretium, turpis dolor molestie diam, ut lacinia diam risus eleifend sapien. Curabitur ac nibh nulla. Maecenas nec augue placerat, viverra tellus non, pulvinar risus.</textarea>

        <input type="button" class="ticker-btn1 add-exp" value="Add Experience" onclick="add_field();"/>

note:- As CSS is not available, it is not applied in this solution. modify your CSS for the perfect view


text:
Q: Gulp having issues with folders that are named like a file I have a gulp task:
gulp.task('css-dependencies', function() {
  return gulp.src(['bower_components/**/*.css','!bower_components/**/*.min.css'])
        .pipe(rename({dirname: './css'}))
        .pipe(gulp.dest('./'));
});

which works fine for all other components, however I want to use animate.css and adding via bower puts it in a folder called animate.css:
Project
 |
 +-- bower_components
    |
    +-- animate.css
        |
        +--animate.css
        +--animate.min.css (etc)

which causes gulp fail on the rename task:

Error: EISDIR: illegal operation on a directory, open '~/css/animate.css' at Error (native)

Other than putting a specific exemption in, how can I fix this?

A: Your problem is that the pattern in gulp.src() matches two things:

*

*The directory bower_component/animate.css

*The file bower_component/animate.css/animate.css
You then proceed to do a rename({dirname: './css'}) which means you end up with:

*

*A directory css/animate.css

*A file css/animate.css
Both cannot exist at the same time obviously.
You need to make sure that your pattern in gulp.src() doesn't match any of the directories themselves (only files in those directories).
gulp.src() uses glob internally and options to gulp.src() are passed through to glob. That means you can use the nodir option of glob to prevent directories from being matched:
return gulp.src(['bower_components/**/*.css','!bower_components/**/*.min.css'], {nodir:true})
  .pipe(rename({dirname: './css'}))
  .pipe(gulp.dest('dist'));


text:
Q: Python+PDB: how to stop at breakpoint in function called from within PDB? I have a Python program with a function foo() in it.
I run the program with PDB, and stop at an arbitrary breakpoint somewhere within the program.
Now, it's easy for me to call foo() from within PDB, I just type:
!foo()

And foo runs. As soon as it finishes, it drops back to PDB, and I'm still waiting at the original line my program was at before.
But now let's say I want PDB to stop at a breakpoint within foo. I set a breakpoint in my source file on the first line of foo(), and then execute !foo().
But PDB doesn't stop at the breakpoint. It only seems to stop there if foo() is called from within the program, not from PDB's command-line while the program is running.
Does anybody know any way around this? I've searched the PDB documentation and Google to no avail.
(The reason I need to do this is because my program takes an hour to read all necessary data to boot up, and I need to be able to debug as much as possible within a single debugging session, as opposed to simply adding breakpoints and re-running the program. So the flexibility of calling functions interactively, and debugging them within, would be tremendously helpful.)

A: Python debugger: Stepping into a function that you have called interactively has the answer: PDB has a 'debug' command that allows you to start a recursive debug session on a function call from within the debugger.


text:
Q: what drawable folders are used for Amazon Appstore Tablets? I am trying to build my app for Amazon App Store wanted to know which drawable folder does Amazon Tablets use?
most of the tablets have a screen size of 1280x800
drawable-large-hdpi
drawable-xlarge-hdpi
drawable-large-mdpi
drawable-xlarge-mdpi

A: To help you target some of your designs for different types of devices, here are some numbers for typical screen widths:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7" tablet (600x1024 mdpi).
720dp: a 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc).

http://developer.android  see link and  Configuration examples point in it may be at last point in it.

A: You can find the screen size qualifiers in their documentation:
Screen Layout and Resolution


text:
Q: about a series $\sum_{n \geq1}{\frac{2n^2}{3^n}} $ How is this series ?

$$\sum_{n \geq1}{\frac{2n^2}{3^n}} ?$$

How I made:
$$a_{n}=\frac{2n^2}{3^n}$$ and then $$\frac{a_{n+1}}{a_n} \leq 1$$ so the series is convergence .
Is ok ?
thanks :)

A: Having  ratio $\le 1$ is not enough for convergence. The simplest example is $1+1+1+\cdots$. There are more subtle examples. (By the way,  $\dfrac{a_2}{a_1}\gt 1$, though this does not matter.)
We want to show that there is a fixed $b$ with $0\le b\lt 1$ such that for large enough $n$, $\dfrac{a_{n+1}}{a_n}\le b$. It will be enough to show that
$$\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=\frac{1}{3}.$$

A: Since $2n^2 < 4\cdot 2^n$, the series is dominated by a geometric series, so it is convergent. Moreover, we have:
$$ \forall x:|x|<3,\quad \sum_{n\geq 1}\frac{x^n}{3^n} = \frac{x}{3-x}, $$
$$ \forall x:|x|<3,\quad \sum_{n\geq 1}\frac{n x^n}{3^n} = x\cdot\frac{d}{dx}\left(\frac{x}{3-x}\right) = \frac{3x}{(x-3)^2}$$
$$ \forall x:|x|<3,\quad \sum_{n\geq 1}\frac{n^2 x^n}{3^n} = x\cdot\frac{d}{dx}\left(\frac{3x}{(x-3)^2}\right) = \frac{3x(3+x)}{(3-x)^3}$$
so:
$$\sum_{n\geq 1}\frac{2n^2}{3^n}=2\cdot\frac{3\cdot 4}{8} = 3.$$

A: Not quite.
You need the limit of the ratio $a_{n+1}/a_n$ to be strictly less than one for the ratio test to apply. In symbols, you need:
$$\lim_{n \to \infty} \left|\frac{a_{n+1}}{a_n}\right| < 1 \, . $$
In your example, you have:
$$\lim_{n \to \infty}  \left|\frac{a_{n+1}}{a_n}\right| = \lim_{n \to \infty} \left|\frac{(n+1)^2}{3n^2}\right| = \frac{1}{3} < 1 \, . $$
Thus, by the ratio test, you sequence converges. Moreover, one can show that:
$$\lim_{k \to \infty} \left(\sum_{n=0}^k \frac{2n^2}{3^n}\right) = 3 \, . $$


text:
Q: Why "hexdump" displays a new empty line? I have noticed a strange behavior when hexdump displays the hex values of a file, I have executed the following command:
hexdump -C 1.txt

And I got the following result:

Notice how hexdump displayed a new empty line (0000000b).
Why this empty line is displayed, and how can I get rid of it?


text:
Q: Azure B2C Tenant wise User management I am referring following example : https://azure.microsoft.com/en-in/resources/samples/active-directory-dotnet-webapp-roleclaims/
I have created main (physical) Azure B2C Tenant, in that I am managing virtual tenant.
 e.g. Azure B2C Tenant (Main)
         - Virtual tenant in Storage table
           - Tenant 1
           - Tenant 2 etc.

But I have single AD and I want to separate the user based on Tenant.
How can I achieve this with Role base user management for tenant ?

A: Role based user management is yet not supported in Azure AD B2C. I would recommend you request this in the Azure AD B2C feedback forum.
I can think of two options for you:

*

*Use a custom attribute to assign users their "tenant". You would then need to make sure you set this custom attribute via the Azure AD Graph. You can then include this claim in your token and use it in your application to drive behavior.

*Define Azure AD groups that map to "tenants". However, given that in Azure AD B2C, groups are not included in the claims, you won't be able to do what's recommended for Azure AD, instead, you will need to query the Azure AD Graph to retrieve the user's group membership and drive behavoir from that.


text:
Q: Is there a simple proof that the matrix is diagonalizable? Let
$A^n=D$, where $D$ is a diagonal invertible matrix, and $n\ne0$ is a real number. Is there a simple proof (without involving Jordan canonical form) that the matrix $A$ is diagonalizable?

A: As $A$ and $D$ commute, eigenspaces of $D$ are stable by $A$. The vector space is therefore a (finite) direct sum of vectors spaces $E_\lambda$ such taht he restriction of $A$ to $E_\lambda$ satisfies $A^n=\lambda. Id$. This restriction is diagonalizable as the polynomial $x^n-\lambda$ has simple roots. Putting together bases of diagonalization of $A$ restricted to the $E_\lambda$ yields a diagonal base for $A$.


text:
Q: Cannot Actvate Setup assistant in MacOS Catalina after Migration Crash I bought a new Macbook Air 2018 with macOS Catalina.  I wanted to transfer my stuff from my old computer so I tried to use Migration Assistant.  It crashed in the middle of the process.
Now my main user is "corrupted".  I cannot login because it crashes and reboots every time I try to access.
I tried Activate Setup assistant in recovery mode but I'm still getting the message /Volumes/Macintosh HD/var/db/.AppleSetupDone no such file or directory.
What else can I do to fix this?


text:
Q: tar folder in s3 bucket? Let's say I have a folder on s3:
s3://tmp/folder1

With several folders within. I would like this to now be:
s3://tmp/folder1.tar.gz

in which the contents of folder1 have been tar.gz'd. However, from what I can find, the only way to do this would be to:

*

*Either download folder1 to a local directory or cp/mv to an existing ec2 instance,

*run tar czv folder1.tar.gz folder1

*Reupload to s3://tmp

Is there a way to do this without having to move/download folder1? In other words, is there an amazon cli command / set of commands to do this without the download / moving?

A: No.
Amazon S3 does not provide the ability to manipulate the contents of objects.
You would need to copy the data somewhere, run the tar command, then upload it.
Think of it like asking a Hard Disk to tar/zip a file without a computer attached. It doesn't know how to do that.


text:
Q: Youtube api v3 sample for uploading videos under .net As the youtube api v3 sample for uploading videos under c# .net does not compile in visual studio 2010, please upload a working solution zip file containing all necessary dependencies for those having the same problem.
A zip file containing sln, csproj etc. of a working(!) project uploading video files to youtube using the v3 of the api(https://developers.google.com/youtube/v3/code_samples/dotnet).

A: I found the solution: It's the profile of visual studio. Select your project in the solution manager and press Alt+Enter. Choose Target framework: ".net Framework 4" instead of ".net Framework 4 Client Profile".


text:
Q: Get Shipping Methods by postCode and countryId I want to get all the available shipping methods along with their prices by postCode and countryId in a page which is not Checkout page.
Example: I have CountryId as 'IN' and postCode as '560029' in a phtml file of backend orders page. Now i want to get all the available shipping methods with their prices which will be displayed for the customer in frontend in checkout page as follows.

Please let me know how can i get all the shipping methods with their prices using countryId and postCode.

A: Thank you Magento Stack Exchange Viewers,
I found the answer in one of the Question - Magento : Get all Shipping Rates
and the answer is:

// Change to your postcode / country.
$zipcode = '560029';
$country = 'IN';

// Update the cart's quote.
$cart = Mage::getSingleton('checkout/cart');
$address = $cart->getQuote()->getShippingAddress();
$address->setCountryId($country)
        ->setPostcode($zipcode)
        ->setCollectShippingrates(true);
$cart->save();

// Find if our shipping has been included.
$rates = $address->collectShippingRates()
                 ->getGroupedAllShippingRates();

foreach ($rates as $carrier) {
    foreach ($carrier as $rate) {
        print_r($rate->getData());
    }
}


text:
Q: My file gets uploaded with my fineuploader setup but yet it shows upload failed. What is the reason for this? I'm using fine uploader in a rails application and I've made a gist of what my method and my jQuery script looks like here
Here's my console log

and here's my upload returning failed when it actually didn't fail:

I thought this was just with my development server where files are being uploaded to FS but I tried it with my staging server that sends the files to a CDN server and it is still successfully uploaded with the same upload failed prompt:

A: It looks like you are not including the mandatory "success" property in your response. It must be set to a value of true to indicate success. This is mentioned in the server documentation at http://docs.fineuploader.com/endpoint_handlers/traditional.html. There is an open case to remove this requirement for newer browsers, scheduled for version 6.0. See https://github.com/FineUploader/fine-uploader/issues/1325 for specifics.


text:
Q: mysql select dates without tables I simply need to return a list of all days within a month.  I'm not accessing a specific table.  So I need a sql select statement if given the month of February, return the following:
Day
----
2011-02-01
2011-02-02
2011-02-03
... etc, etc.
2011-02-27
2011-02-28

This should be fairly simple, i would think,  if I knew the sql select statement I need to make.  The month should be selectable, I'll pass that in from a webpage select box which lets the user select the month and year.  This is going to be the basis of a report.  I already have a select statement that will take each of the days and give counts on records related to those dates, but I need this table as a basis of my reports.

A: I agree with the comments, that something like this shouldn't be done in the database, but technically its possible.
If you give the start and end date, adding additional numbers to the subquery if necessary:
SELECT '2011-02-01' + INTERVAL a + b DAY dte
FROM
 (SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
    UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
    UNION SELECT 8 UNION SELECT 9 ) d,
 (SELECT 0 b UNION SELECT 10 UNION SELECT 20
    UNION SELECT 30 UNION SELECT 40) m
WHERE '2011-02-01' + INTERVAL a + b DAY  <  '2011-03-01'
ORDER BY a + b

Results:
"2011-02-01"
"2011-02-02"
"2011-02-03"
....
"2011-02-28"

A: -- This may be overkill, but you can make a procedure like this:
use dbname;

DELIMITER $$

DROP PROCEDURE IF EXISTS `days_of_month` $$

CREATE PROCEDURE `days_of_month`(iDate DATETIME) DETERMINISTIC

BEGIN

    DECLARE last_day,mm,yy,dd INT DEFAULT 0;
    SET dd = 1;
    SET mm = month(iDate);
    SET yy = year(iDate);

    set iDate = case when iDate is null then now() else iDate end;
    SET last_day = date_format(LAST_DAY(iDate),'%d');

    DROP TABLE IF EXISTS `days_of_month_tblTemp`;
    CREATE TEMPORARY TABLE days_of_month_tblTemp(tmpDate DATE);

    label1: LOOP
         insert into days_of_month_tblTemp(tmpDate) values (concat(yy,'-',mm,'-',dd));
        SET dd = dd + 1;
        IF dd < (last_day+1) THEN ITERATE label1; END IF;
         LEAVE label1;
      END LOOP label1;
      SELECT * from days_of_month_tblTemp;
END $$

DELIMITER ;

--  run it like this: CALL days_of_month('2012-02-22');

A: I have slightly augmented to give the all preceeding dates for the last month:
SELECT (SELECT Date(NOW() - INTERVAL 1 MONTH)) + INTERVAL a + b DAY dte
FROM
 (SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
    UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
    UNION SELECT 8 UNION SELECT 9 ) d,
 (SELECT 0 b UNION SELECT 10 UNION SELECT 20
    UNION SELECT 30 UNION SELECT 40) m
WHERE (SELECT Date(NOW() - INTERVAL 1 MONTH)) + INTERVAL a + b DAY  <  (select date(now()))
ORDER BY a + b;


text:
Q: Existence of Polynomial P such that P(A)=0 Let E be a Banach space of infinite dimension and A a compact operator of E in itself.
I'm looking for this equivalence:
There exists a polynomial P such that P (A) = 0 $\iff$ there exists $m \in \mathbb{N ^ *}$  such that $A ^ m$ be a  of finite rank operator.
My attempt to show the sens $\Longrightarrow $
If P exist such that P(A)=0  then necessarily P(0)=0 and we can write $0=P(A)=A^m .(I+a_1A+...a_pA^p)$ forsome integer m>0
Then $Ker (A^m)$ have a supplementary $Ker (I+a_1A+...a_pA^p)$. We know also that $Rank (A^m)$ is a supplementary of $Ker (A^m)$. Then  $Rank (A^m)$ and $Ker (I+a_1A+...a_pA^p)$ are isomorphic.
By Riesz The dimension of $Ker (I+a_1A+...a_pA^p)$ is finite, then the dimension of $Rank (A^m)$ is finite
I need help to show the sens $\Longleftarrow$

A: If $A^m = B$ has finite rank, there is a finite-dimensional subspace $V$ such that $E = V + \text{Ker}(B)$.  Let $W = \text{span}(V, BV)$, so $B$ maps the finite-dimensional space $W$ to itself.  This corresponds to a matrix $\hat{B}$.  If $C(x)$ is the characteristic polynomial of $\hat{B}$, we have $C(B) = 0$.  Then we can take $P(x) = x C(x^m)$.


text:
Q: How to set multiple output when build lib with vite When I try to build a lib in vue3, I want to set multiple output file. Code like this:
rollupOptions {
  output: [
    {
      file: 'bundle.js',
      format: 'cjs'
    },
    {
      file: 'bundle.min.js',
      format: 'iife',
      name: 'version',
    }
  ]
}

Then I will get an error:

You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks"

So, how should I do can make this work?
vite: 2.3.7

A:  You are missing the input config in rollupOptions.
The following full vite config example will generate a index.bundle.[moduleFormat].js
(you may need to adjust file path according to your setup)* :
import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default (opts: { mode: "production" | "development"; command: "build" | "serve" }) => {
    return defineConfig({
        build: {
            target: "es2020",
            commonjsOptions: {
                sourceMap: false
            },
            rollupOptions: {
                input: {
                    index: "./src/index.js"
                },
                /* single
                output: {
                    format: "umd",
                    strict: false,
                    chunkFileNames: `[name].[hash].js`,
                    entryFileNames: "[name].bundle.umd.js",
                    dir: "dist"
                },
                */
                // array config example
                // from rollup: export type InternalModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd';
                output: [
                    {
                        format: 'cjs',
                        entryFileNames: "[name].bundle.[format].js",
                    },
                    {
                        format: 'es',
                        entryFileNames: "[name].bundle.[format].js",
                    },
                    {
                        format: 'umd',
                        entryFileNames: "[name].bundle.[format].js",
                    },
                ]
            }
        }
    });
};

 To understand this answer better, please read the following sentence :
If you provide an array of entry points or an object mapping names to entry points, they will be bundled to separate output chunks.
And unless the output.file option is used, generated chunk names will follow the output.entryFileNames option. When using the object form, the [name] portion of the file name will be the name of the object property while for the array form, it will be the file name of the entry point.
Note that it is possible when using the object form to put entry points into different sub-folders by adding a / to the name.
If we follow the doc we can get more precisions and we know that :
output.dir
Type: string
Set in build.rollupOptions

Is for: The directory in which all generated chunks are placed and this option is required if more than one chunk is generated. Otherwise, the file option can be used instead.
output.file
Type: string

The file to write to. Can only be used if not more than one chunk is generated.

A: I guess your looking for https://vitejs.dev/guide/build.html#library-mode
And see https://vitejs.dev/config/#build-lib to tweak your needs.


text:
Q: How to filter/remove columns in Tableau when there is no data Trying to create a longish timeseries of trends in A-level results over past three years.
It looks like this:

Two problems. I can't find any options to remove the columns in visualisation where there is no data such as 2019 or 2023.
And how I squeeze the padding so the data is more scrollable?
https://public.tableau.com/app/profile/elksie5000/viz/TopAgradesatA-levelin2022/Dashboard1?publish=yes

A: Edit: I just changed the data type of "Year" into date and dragged it to the columns pane. now the values range between 2020 to 2022


text:
Q: Magento 2 security patches We have an old Magento 2 installation, roughly a year old. Browsing the magento site it looks like patches are only for 1.x and not 2.x. Is that right? So for the latest fixes I need to upgrade to the latest version of 2.x?
Thanks

A: Magento provides the patches for 2.x version:

*

*Download tab: https://magento.com/tech-resources/download

*https://magento.com/security

*Old info: https://magento.com/security/patches/magento-2010-and-212-security-update
Note: it's better if we upgrade our Magento source to the newer version.


text:
Q: Como ocorre a truncagem de um número float ou double? Tenho o seguinte trecho:
double valor = 1.5;

while(valor >= 0) {
    System.out.println(valor);
    valor -= 0.15;
}

A saída será de números truncados devido ao armazenamento de 8 bytes para double, correto?
(...)
0.30000000000000016
0.15000000000000016
1.6653345369377348E-16

Como as linguagens tratam essas situações de truncagem internamente? A operação é simplesmente interrompida para aquele número, retornando-o até o ponto onde ocorreu a truncagem? Qual seria a sequência do número 0.30000000000000016 se não estivesse truncado?


text:
Q: retrieving textbox data to sql from asp.net i have a code to move data from asp.net (c# code) to sql. In the following code i have inserted  values directly (i.e) xxx and yyy.This works too. Now i want to insert the values which was entered in text boxes. What will be the code to do so?. Help  me friends.
protected void Button2_Click(object sender, EventArgs e)
{
    string  comm="insert into login values('xxx','yyy')";
    con = new SqlConnection();
    con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString();
    cmd = new SqlCommand(comm, con);
    cmd.Connection.Open();
    con.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();
}

A: protected void Button2_Click(object sender, EventArgs e)
{
     string  comm="insert into login values(@val1,@val2)";
    con = new SqlConnection();
    con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString();
    cmd = new SqlCommand(comm, con);
    cmd.Connection.Open();

    cmd.Parameters.Add("@val1",TextBox1.Text); //Replace TextBox1.Text with your first textbox
    cmd.Parameters.Add("@val2",TextBox2.Text); //Replace TextBox2.Text with your second textbox

    con.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();
}


text:
Q: create a countdown that the remain time is equal no mather the country i can image someone had donde this already or it can be considered a duplicated question, i've been searching for weeks and i can't figure out how to accomplish this.
I have a countdown made in js, the problem i'm facing is that when ever i test it in another country the times throw out different hours example.
i'm in centralamerica, end date is  apr 16, 2018 23:59:59" if i test this in centralamerica it says 6 days and 10 hours remaining, if i run this in italy for example it says 6 days and 3 hours remaining, i need it to be equal all the time and that the timezone doesn´t affects, is this even possible, and please help on how to get it done.
the script i have is working but not the way i need to, i have a promo that will expire on "apr 16, 2018 23:59:59" so if it only has 5 hours remaining it shout say 5 hours remaining no matter where its been seeing from, but that is not happening.

$("#masterslider").append("
.
")
  $("#masterslider").append(" remaining time  ")

//******************************** update date here ************************
var serverDate = new Date("apr 16, 2018 23:59:59");
var offset = serverDate.getTimezoneOffset();
serverDate = addOffset(serverDate, offset);

 setInterval(function(){
    updateCountdown();
}, 1000);

 function addOffset(date, offset) {
    var time = date.getTime() ;
 return new Date(time + offset  * 6000);
}

 function updateCountdown() {
 var userDate = new Date();

    var distance = serverDate.getTime() - userDate.getTime();

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
   //var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  if(serverDate.getTime()  > userDate.getTime()){

       $('#demo').html( days +"day(s)"+ " / " + hours + "hour(s)"  + minutes + "minutes(s)");

  }
   else
  {
   $("#demo").html(mas);
   $("#masterslider span").hide();
 }

 }
 </script>

A: I've checked and setting correct timezone for "event timestamp" works for me regardless local client timezone I use.

let targetDate = new Date("2018-04-11 23:59:59 GMT-0800");
let refreshDelayMs = 1000;
function updateCounter() {
   let distance = (targetDate - new Date()) / 1000;
   let seconds = Math.floor(distance % 60).toString().padStart(2, '0');
   distance = distance / 60;
   let minutes = Math.floor(distance % 60).toString().padStart(2, '0');
   distance = distance / 60;
   let hours = Math.floor(distance % 24).toString().padStart(2, '0');
   let days = Math.floor(distance / 24).toString().padStart(2, '0');
   document.querySelector('.counter').innerHTML = `${days} days ${hours}:${minutes}:${seconds}`;
   setTimeout(updateCounter, refreshDelayMs);
}

updateCounter();
Remains:

A: You can use moment-timezone from CDN or use NPM
repl.it sample

const moment = require("moment-timezone");

function toTimeZone(time, offset) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).utcOffset(offset).format(format);
}

toTimeZone("2018/04/10 15:37", "+0730")


text:
Q: Make transition between two Menus with UIScrollView
I want to have 2 menus (the other one will be the same as the one shown in the screenshot, but it will contain other items).
Each menu is in its own UIStackView.
I've decided to rule out the UIPageViewController and instead use UIScrollView because it's the behaviour I want.
How can I put both menus inside of UIScrollView and make a nice animation?

A: Are you avoiding UIPageViewController because of the complexity? Because if you are there is a much easier way to accomplish the same gesture controlled transition using UIScrollView's pagingEnabled property
Based on what I see in the screenshots...
var size                                      = CGSize()
    size.height                               = self.view.frame.height
    size.width                                = self.view.frame.width * 2

let scrollView                                = UIScrollView()
    scrollView.frame                          = self.view.frame
    scrollView.contentSize                    = size
    scrollView.pagingEnabled                  = true
    scrollView.showsHorizontalScrollIndicator = false

    nav.center.y                              = scrollView.frame.height / 2
    nav.center.x                              = scrollView.frame.width / 2
    nav2.center.y                             = scrollView.frame.height / 2
    nav2.center.x                             = nav.center.x  + scrollView.frame.width

    scrollView.addSubview(nav1)
    scrollView.addSubview(nav2)

self.view.addSubview(scrollView)

A: @dsieczko did fantastic job answering my question. I'm not experienced with AutoLayout, so that was the problem. My final code looks something like this:
    import UIKit

class MainMenuViewController: UIViewController, UIScrollViewDelegate {
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var nav2: UIStackView!
    @IBOutlet var nav: UIStackView!
    @IBOutlet var pageControl: UIPageControl!

    override func viewDidLoad() {
        super.viewDidLoad()

        /* MAIN MENUS */
        var size                                      = CGSize()
        size.height                               = self.nav.frame.height
        size.width                                = self.view.frame.width * 2

        scrollView.frame                          = self.view.frame
        scrollView.contentSize                    = size
        scrollView.pagingEnabled                  = true
        scrollView.showsHorizontalScrollIndicator = false

        nav.center.y                              = scrollView.frame.height / 2
        nav.center.x                              = self.view.frame.width * 1.5
        nav2.center.y                             = scrollView.frame.height / 2
        nav2.center.x                             = nav.center.x  + scrollView.frame.width + 400

        scrollView.addSubview(nav)
        scrollView.addSubview(nav2)

        self.view.addSubview(scrollView)

        /* MAIN MENUS */

        // Change the Navigation Bar Color to Red
        navigationController!.navigationBar.barTintColor = UIColor(red: 0.79, green: 0.19, blue: 0.19, alpha: 1)

        // Change the Navigation Bar Font to Lato
        self.navigationController?.navigationBar.titleTextAttributes =
            [NSForegroundColorAttributeName: UIColor.whiteColor(),
                NSFontAttributeName: UIFont(name: "Lato-Semibold", size: 20)!]
    }

  }

And my layout something like this:
If anyone encounters a problem like this, I will gladly help with my exp with this.


text:
Q: Libgdx: SpriteBatch.draw spriteVertecies wierd UV coords behavior I'm trying to display a simple textured trapezoid (a road in perspective). For this I'm using SpriteBatch.draw with vertexes array as a parameter. But the result is unexpected.
What I expected:

What I got:

What exactly gone wrong? Or maybe I'm using the wrong method?
Here is the code:
@Override
public void create () {
    texture = new Texture("road.jpg");

    spriteBatch = new SpriteBatch();

    float color = Color.toFloatBits(255, 255, 255, 255);

    verts = new float[]{
            0,                              0,      color, 0, 0,
            Gdx.graphics.getWidth()/2-100,  300,    color, 0, 1,
            Gdx.graphics.getWidth()/2+100,  300,    color, 1, 1,
            Gdx.graphics.getWidth(),        0,      color, 1, 0,
    };

    shapeRenderer = new ShapeRenderer();
}

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0.5f, 1f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.rect(0, 0, 640, 300);
    shapeRenderer.end();

    spriteBatch.begin();
    spriteBatch.draw(texture, verts, 0, verts.length);
    spriteBatch.end();
}

A: From documentation

draw(Texture texture, float[] spriteVertices, int offset, int count)
Draws a rectangle using the given vertices.

LibGDX draws these rectangles as two triangles, so it splits the texture. The problem is that these triangles in rectangle are the same size, but in trapezoid they are not, so they become distorted.
Solution would be to use projection or mesh.


text:
Q: Как присвоить значение переменной из файла. А переменная - object Мне нужно допустим перекачать объект класса Example в файл и потом из файла его восстановить и присвоить обратно

A: Вот пример сериализации класса в файл
            MyClass myClassVariable = new MyClass(<параметры>);
            FileOutputStream fileOut = new FileOutputStream(filepath);
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(myClassVariable);
            objectOut.close();
            System.out.println("Done");


text:
Q: How to position my button to the Bottom of the Screen? SwiftUI Below is my code to make a View in SwiftUI. I want to position my Welcome button to the bottom of the screen as shown below.
struct welcomeViewControllerView: View {
      var body: some View {
            Text("Welcome")
              .font(.system(size: 20, design: .rounded))
              .padding(.leading)
              .multilineTextAlignment(.center)
              .background(

            Image("splashBackground")
              .resizable()
              .edgesIgnoringSafeArea(.all)
              .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))

            Button(action:{print("button pressed")})
              {
                Text("Continue")
                .font(.system(size: 20, design: .rounded))
                .foregroundColor(.black)
                .frame(width: 300, height: 50, alignment: .center)
               .background((Image("buttonImage")).resizable().frame(width: 300, height: 50, alignment: .center))
         }
      }
   }

class welcomeViewController: UIHostingController<welcomeViewControllerView> {
        required init?(coder: NSCoder)
         {
             super.init(coder: coder,rootView: welcomeViewControllerView());
          }

          override func viewDidLoad()
         {
           super.viewDidLoad()
            view.backgroundColor = .white
         }
}

How can I position my button to the bottom of the screen? I posted the screen below. I am fairly new to using SwiftUI.

A: Your question included a background image, the code below uses ZStack and Spacer to get the layout with a background underneath. Spacer is definitely your friend to push content horizontally or vertically.
For the background, because it is mostly black, I used Color.black to paint the entire screen and assume you could use a smaller image for the logo. This lets you ship a way smaller image which won't distort. Separating the screen color also lets you match the device light/dark mode settings. See Color(UIColor.systemBackground) and @Environment(.colorScheme) if interested.
ZStack {
    Color.black

    Text("Welcome")
        .foregroundColor(.white)
        .font(.title)

    VStack {
        Image(systemName:"flame.fill")
            .resizable()
            .aspectRatio(contentMode:.fit)
            .foregroundColor(Color.blue)
            .frame(height:100)
            .padding([.top], 20)
        Spacer() // will spread content to top and bottom of VStack
        Button(action:{print("Continue")}){
            Text("Continue")
                .foregroundColor(.black)
                .padding(10)
                .background(Color.green)
                .cornerRadius(10)
        }
        Spacer()
            .frame(height:50)  // limit spacer size by applying a frame
    }
}

Above gets you below:
Layout with bkg using ZStack and Spacer

A: struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "heart.fill")
                .resizable()
                .frame(width: 60, height: 60)
                .foregroundColor(.red)

            Group{
                Text("Welcome!")
                    .font(.title)

                Button(action: {
                    print("tapped!")
                }, label: {
                    Text("Continue")
                        .foregroundColor(.white)
                        .frame(width: 200, height: 40)
                        .background(Color.green)
                        .cornerRadius(15)
                        .padding()
                })
            }.frame(maxHeight: .infinity, alignment: .bottom)
        }
    }
}

Result:


text:
Q: passing value in hidden field from one page to another in php I have a simple registration form.
I want to pass value entered in one page to other in a text field.
how to pass and access it from next page in php.
this is my first php page.
Thanks in advance.

A: You can add hidden fields within HTML and access them in PHP:
<input type="hidden" name="myFieldName" value="someValue"/>

Then in PHP:
$val = $_POST['myFieldName'];

If you're going to ouput this again you should use htmlspecialchars or something similar to prevent injection attacks.
<input type="hidden" name="myFieldName" value="<?=htmlspecialchars($_POST['myFieldName']);?>"/>

A: Suppose this the form input in page A
<form name="" action="" method=post enctype="multipart/form-data">
<input type="text" name="myvalue" value="">
<input type=submit>
</form>

In  page B
In the page you want to get values put this code
         <?PHP
           foreach ($_REQUEST as $key => $value ) {
             $$key=(stripslashes($value));
          }
         ?>

<form name="" action="" method=post enctype="multipart/form-data">
<input type="text" name="myvalue" value="<?PHP echo $myvalue" ?>">
<input type=submit>
</form>

So yo can use or  attach variable value to another form do what else you want to do

A: use following code, that should help you.
<form action ="formhandler.php" method ="POST" >
    <input name = "inputfield" />
    <input type="submit" />
</form>

on formhandler.php file yo need to enter following code to get the value of inputfiled.
$inputfield = isset($_POST['inputfield'])?$_POST['inputfield']:"";
// now you can do what ever you want with $inputfield value
echo($inputfield);


text:
Q: Factory_boy not creating different User objects Django I am new to Factory_boy with Django. After spending some time I understood how to create a factory for User model.
I am using the default user model and following is my factory. I am using Faker for randomness
import factory
from . import models
from django.contrib.auth.models import User
from faker import Faker
from django.contrib.auth.hashers import make_password

fake = Faker()

class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = User
        django_get_or_create = ('email',)

    first_name = fake.first_name()
    last_name = fake.last_name()
    email = first_name+"."+last_name+"@gmail.com"
    password = make_password("ojasojas")
    username = first_name+"_"+last_name

Now in the django shell
I use UserFactory.create() to crate an user. this works fine. Is it possible to loop through create statement and crate 5 different users? Now when I am doing that I am getting only one user (crated once and 'get' 4 times) as follows. What am I missing?

A: You are defining class attributes for your factory, which get evaluated only when the class is defined. email = first_name+"."+last_name+"@gmail.com" will be evaluated once, not each time you call UserFactory.create(), hence the unique constraint errors. The usual solution to this is to instead define instance attributes via __init__(), but FactoryBoy has their own solution to this:  lazy attributes.

A: This may not be the best solution, but its a work around I've been using lately.  I set the following Global:
NAMES = [factory.Faker('name')._get_faker().name() for i in range(5)]

In this case, the above will generate a list of 5 fake names.
NOTE:  this does not guarantee a unique name (as FuzzyChoice will just select one from the list).
and within your factory:
name = factory.LazyAttribute(lambda obj: factory.fuzzy.FuzzyChoice(NAMES).fuzz())

A: FactoryBoy offers LazyFunction and LazyAttribute classes to achieve this. Difference between them is that you can access other model-factory fields in LazyAttribute.
Here is an example:
class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.User
        django_get_or_create = ('email',)

    @staticmethod
    def gen_email(x):
        return x.first_name + "." + x.last_name + "@gmail.com"

    first_name = factory.LazyFunction(fake.first_name)
    last_name = factory.LazyFunction(fake.last_name)
    email = factory.LazyAttribute(gen_email)
    password = make_password("ojasojas")
    username = factory.LazyAttribute(lambda x: x.first_name + "_" + x.last_name)

You can use lambda expressions as I've used here for demonstration in making the username field 'lazy-evaluated', or create functions (static method) and pass them to LazyFunction/LazyAttribute.

You can read more about these classes in official documentation of Factory Boy:

*

*LazyFunction

*LazyAttribute